⌘BABAKOV.NET Let's code!
100% [light] [ru]

Python Bottle Guide (Translation) Part 5 - Request Data (Data in Request)

In the previous part (Python Bottle Guide (Translation) Part 4 - Creating Content) we considered the main aspects related to the transmitted content, in this part we will consider the data transmitted in requests.

Files Cookie, HTTP headers, HTML form fields, and other request data are available through the global object request. This special object always refers to the current request, even in multi-threaded environments where multiple client connections are being processed simultaneously:

from bottle import request, route, template

@route(\'/hello\')
def hello():
    name = request.cookies.username or \'Guest\'
    return template(\'Привет {{name}}\', name=name)


The object request is a subclass of BaseRequest and has a very rich API for accessing data. Here we will only consider the most commonly used functions, which should be enough to get started.

Introduction to FORMSDICT (INTRODUCING FORMSDICT)


Bottle uses a special dictionary type to store form data and file cookies. FormsDict behaves like a regular dictionary, but has some additional functions that make life easier for the developer.

Accessing attributes: all values in the dictionary are available as attributes. These virtual attributes return Unicode strings, even if the value is missing or cannot be decoded to Unicode. In this case, the string is empty, but still exists:

name = request.cookies.name

# это ссылка вот к этому:

name = request.cookies.getunicode(\'name\') # encoding=\'utf-8\' (default)

# которая по умолчанию делает это:

try:
    name = request.cookies.get(\'name\', \'\').decode(\'utf-8\')
except UnicodeError:
    name = u\'\'



Multiple values per key: FormsDict is a subclass of MultiDict and can store more than one value per key. Standard dictionary access methods will return only one value, but the getall() method returns (including empty) a list of all values for a given key:

for choice in request.forms.getall(\'multiple_choice\'):
    do_something(choice)



Support for WTForms: Some libraries (e.g. WTForms) require using dictionaries with Unicode as input. FormsDict.decode() does this for us. It decodes all values and returns its copy, preserving multiple values per key and all other goodies.

Note:

In Python 2 all keys and values are byte strings. If Unicode is needed, FormsDict.getunicode() or accessing attributes can be called. Both methods will try to decode the string (default: utf8) and return an empty string if this fails. No need to catch UnicodeError:

>>> request.query[\'city\']
\'G\\xc3\\xb6ttingen\'  # Строка utf8 byte string
>>> request.query.city
u\'Göttingen\'        # Идентичная строка в unicode

In Python 3 all strings are Unicode, but in the HTTP protocol exchange is based on exchanging a byte array. The server must somehow decode byte strings before passing them to the application. To ensure the process, WSGI proposes ISO-8859-1 (also known as latin1), a reversible single-byte codec, which can be recoded to another codec. Bottle does this for FormsDict.getunicode() and attribute access, but not for dict-access methods. They return the unchanged values provided by the server implementation, which is probably not what we need.

>>> request.query[\'city\']
\'Göttingen\' # Строка utf8 декодированная как ISO-8859-1 сервером
>>> request.query.city
\'Göttingen\'  # Та же строка корректно декодированная в utf8 движком Bottrle

If a complete dictionary with correctly decoded values is needed (e.g. for WTForms), FormsDict.decode() can be called to get a recoded copy.



Cookies (COOKIES)


Files Cookie are small text fragments stored on the client-side browsers and sent back to the server with each request. They are useful for storing some state for more than one request (HTTP does not have state), but should not be used for security-related things. They can be easily forged by the client.

All cookies sent by the client are available through BaseRequest.cookies (FormsDict). In this example, a simple view counter based on Cookie files is shown:

from bottle import route, request, response
@route(\'/counter\')
def counter():
    count = int( request.cookies.get(\'counter\', \'0\') )
    count += 1
    response.set_cookie(\'counter\', str(count))
    return \'Вы посетили эту страниц %d раз\' % count


The BaseRequest.get_cookie() method is another way to access Cookie files. It supports decoding signed Cookie files.

HTTP Headers (HTTP Headers)


All HTTP headers sent by the client (e.g. Referer, Agent, or Accept-Language) are stored in WSGIHeaderDict and available through the BaseRequest.headers attribute. WSGIHeaderDict is a dictionary with keys in case-insensitive:

from bottle import route, request
@route(\'/is_ajax\')
def is_ajax():
    if request.headers.get(\'X-Requested-With\') == \'XMLHttpRequest\':
        return \'Это AJAX запрос\'
    else:
        return \'Это обычный запрос\'



Query Variables (QUERY VARIABLES)


Query strings (e.g. /forum?Id=1&page=5) are usually used to transmit a small number of key/value pairs to the server. You can use the BaseRequest.query (FormsDict) attribute to access these values and the BaseRequest.query_string attribute to get the entire string.

from bottle import route, request, response, template
@route(\'/forum\')
def display_forum():
    forum_id = request.query.id
    page = request.query.page or \'1\'
    return template(\'Форум номер: {{id}} (страница {{page}})\', id=forum_id, page=page)



HTML Form Handling (HTML FORM HANDLING)


Let's start from the beginning. In HTML, a typical form form looks like this:

<form action="/login" method="post">
    Username: <input name="username" type="text" />
    Password: <input name="password" type="password" />
    <input value="Login" type="submit" />
</form>


The action attribute specifies the URL that will receive the form data. The method attribute determines the HTTP method to use (GET or POST). When using the method=«get» method, the form values are added to the URL and are available through BaseRequest.query, as described above. This is considered insecure and has several restrictions, so we will use method=«post» here. If in doubt, use POST.

Form fields, data transmitted via POST, are stored in BaseRequest.forms as FormsDict. Server-side code can look like this:

from bottle import route, request

@route(\'/login\')
def login():
    return \'\'\'
        <form action="/login" method="post">
            Username: <input name="username" type="text" />
            Password: <input name="password" type="password" />
            <input value="Login" type="submit" />
        </form>
    \'\'\'

@route(\'/login\', method=\'POST\')
def do_login():
    username = request.forms.get(\'username\')
    password = request.forms.get(\'password\')
    if check_login(username, password):
        return "<p>Авторизационные данные верны.</p>"
    else:
        return "<p>Авторизационные данные не верны.</p>"



There are several other attributes used to access form data. Some of them combine values from different sources for easier access.

Attribute	        GET Form fields    POST Form fields    File Uploads

BaseRequest.query       yes	           no	               no
BaseRequest.forms	no	           yes	               no
BaseRequest.files	no	           no	               yes
BaseRequest.params	yes	           yes	               no
BaseRequest.GET	        yes	           no	               no
BaseRequest.POST	no	           yes	               yes



File Uploads (FILE UPLOADS)


To upload files, we need to slightly modify the form tag. First, we tell the browser to encode the form data differently by adding the enctype=«multipart/form-data» attribute to the form tag. Then we add input type=«file» tags to allow the user to select a file. Example:

<form action="/upload" method="post" enctype="multipart/form-data">
  Категория:      <input type="text" name="category" />
  Выберите файл: <input type="file" name="upload" />
  <input type="submit" value="Загрузить файл" />
</form>


Bottle stores uploaded files in BaseRequest.files as FileUpload instances along with some metadata about the upload. Here's how you can save the file to disk:

@route(\'/upload\', method=\'POST\')
def do_upload():
    category   = request.forms.get(\'category\')
    upload     = request.files.get(\'upload\')
    name, ext = os.path.splitext(upload.filename)
    if ext not in (\'.png\',\'.jpg\',\'.jpeg\'):
        return \'Расширение файла не поддерживается.\'

    save_path = get_save_path_for_category(category)
    upload.save(save_path) # appends upload.filename automatically
    return \'OK\'


FileUpload.filename contains the file name in the client-side file system, which is cleaned and normalized to prevent errors related to unsupported characters or path segments in the file name. If you need the original file name sent by the client, you can find it in FileUpload.raw_filename.

The FileUpload.save method is highly recommended if you want to save the file to disk. It prevents some common errors (e.g. it does not overwrite existing files unless you tell it to) and saves the file with minimal memory usage. You can access the file object directly through FileUpload.file. However, you should be extremely cautious when doing so.

JSON Content


Some javascript or REST clients send content in application/json to the server. The BaseRequest.json attribute contains the structured data if it is available.

Getting Unprocessed Data (THE RAW REQUEST BODY)


You can access the unprocessed data as a file object through BaseRequest.body. This is a BytesIO buffer or a temporary file, depending on the content length and the BaseRequest.MEMFILE_MAX parameter. In both cases, the body is fully buffered before you can access the attribute. If you expect huge amounts of data and want to get direct, non-buffered access to the stream, note the request [\'wsgi.input\'].

WSGI Environment (WSGI ENVIRONMENT)


Each BaseRequest instance wraps the WSGI environment dictionary. The original is stored in BaseRequest.environ, but the request object itself also behaves like a dictionary. Most data is provided through special methods or attributes, but if you want to get direct access to WSGI environment variables, you can do so:

@route(\'/my_ip\')
def show_ip():
    ip = request.environ.get(\'REMOTE_ADDR\')
    # or ip = request.get(\'REMOTE_ADDR\')
    # or ip = request[\'REMOTE_ADDR\']
    return template("Your IP is: {{ip}}", ip=ip)



Continuation:
Python Bottle Guide (Translation) Part 6 - Templates (about Templates)

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.