Python Bottle Guide (Translation) Part 4 - Creating Content
In the previous part (Python Bottle Guide (Translation) Part 3 - Routing Requests) we discussed the main aspects related to routing requests. In this part, we will discuss the aspects related to the transmitted content.
Creating Content
In a clean WSGI standard, the range of returned types from the application is very limited. Applications must return strings with the possibility of breaking them down into a set of bytes. You can return a string (break it down into parts), but most servers force you to send the content character by character. Unicode strings are not allowed at all. This is not very practical.
Bottle is much more flexible and supports a wide range of types. It automatically adds the Content-Length header when possible and automatically encodes Unicode, making it easier for the developer. Below is a list of data types that can be returned from the application and a brief description of how they are handled by the platform:
Dictionaries
Python dictionaries (or their subclasses) are automatically converted to JSON strings and returned to the browser with the Content-Type header set to application/json. This makes it easier to implement a json-based API. However, other data formats are also supported.
Empty strings, False, None / non-true values
Produce an empty output with the Content-Length header set to 0.
Unicode strings
Unicode strings (or iterations leading to Unicode strings) are automatically encoded using the codec specified in the Content-Type header (default: utf8) and then handled as regular byte strings.
Byte strings
Bottle returns strings in their entirety (instead of iterating over each character) and adds the Content-Length header based on the string length. Byte string lists are concatenated first. Other iterable strings with byte strings are not concatenated because they can become too large and not fit in memory. The Content-Length header is not set in this case.
HTTPError or HTTPResponse instances
Returning them has the same effect as calling them as an exception. In the case of HTTPError, the error handler is applied.
File objects
Anything with a .read() method is handled as a file or similar file object and passed to the wsgi.file_wrapper callable defined by the WSGI server environment. Some WSGI server implementations may use optimized system calls (sendfile) for more efficient file transfer. In other cases, fragments are simply iterated over and placed in memory. Additional headers such as Content-Length or Content-Type are not automatically set. You should use send_file() if possible.
Iterables and generators
It is allowed to use yield in calls or return an iterable if iteration yields byte strings, Unicode strings, HTTPError or HTTPResponse instances. Nested iterations are not supported. Note that the HTTP status code and headers are sent to the browser as soon as the iteration returns its first non-empty value.
The order of the list is important. For example, you can return a subclass of str using the read() method. In this case, it will still be handled as a string instead of a file because strings are handled first.
Changing the default encoding (Default Encoding)
Bottle uses the charset parameter of the Content-Type header to determine how to encode Unicode strings. By default, the header has the value text/html; charset=UTF8 and can be changed using the Response.content_type attribute or by directly setting the Response.charset attribute.
from bottle import response
@route(\'/iso\')
def get_iso():
response.charset = \'ISO-8859-15\'
return u\'This will be sent with ISO-8859-15 encoding.\'
@route(\'/latin9\')
def get_latin():
response.content_type = \'text/html; charset=latin9\'
return u\'ISO-8859-15 is also known as latin9.\'
In some rare cases when Python encoding names differ from those supported by the HTTP specification, you need to perform both actions: first set the Response.content_type header (which is sent to the client unchanged), and then set the Response.charset attribute (which is used for Unicode encoding).
Static Files (STATIC FILES)
You can directly return files, but the static_file() method is recommended for serving static files. It automatically determines the MIME type, adds the Last-Modified header, limits paths to the root directory for security reasons, and generates corresponding error messages (403 for access errors, 404 for missing files). This method even supports the If-Modified-Since header and generates a 304 Not Modified response. However, you can specify a custom MIME type to disable detection.
from bottle import static_file
@route(\'/images/<filename:re:.*\\.png>\')
def send_image(filename):
return static_file(filename, root=\'/path/to/image/files\', mimetype=\'image/png\')
@route(\'/static/<filename:path>\')
def send_static(filename):
return static_file(filename, root=\'/path/to/static/files\')
You can return the return value of static_file() as an exception if necessary.
Forced Download
Most browsers try to open downloaded files if the MIME type is known and associated with the application (e.g., PDF files). If this is not enough, you can call a file download dialog and even offer the user a file name:
@route(\'/download/<filename:path>\')
def download(filename):
return static_file(filename, root=\'/path/to/static/files\', download=filename)
If the download parameter is True, the original file name is used.
HTTP Errors and Redirects (HTTP ERRORS AND REDIRECTS)
The abort() function is a reference for generating HTTP error pages.
from bottle import route, abort
@route(\'/restricted\')
def restricted():
abort(401, "Извините, доступ запрещён.")
To redirect the client to another URL, you can send a 303 See Other response with the Location header set to the new URL. redirect() does this for you:
from bottle import redirect
@route(\'/wrong/url\')
def wrong():
redirect("/right/url")
You can specify a different HTTP status code as the second parameter.
Note: Both functions will interrupt your method, raising an HTTPError exception.
Other exceptions
All exceptions except HTTPResponse or HTTPError will result in a 500 Internal Server Error response, so they will not abruptly terminate the WSGI server. You can disable this behavior for exception handling in your middleware by setting bottle.app().Catchall to False.
The Response Object (THE RESPONSE OBJECT)
Metadata such as the HTTP status code, response headers, and files cookie are stored in an object called Response until they are sent to the browser. You can directly manipulate these metadata or use predefined helper methods. Here are the most common use cases and functions described:
Status Code
The HTTP status code controls browser behavior and defaults to 200 OK. In most scenarios, you don't need to set the Response.status attribute manually, but using the abort() method will return an HTTPResponse instance with the corresponding status code. Any integer is allowed, but codes other than those defined in the HTTP specification will only confuse the browser and violate standards.
Response Header
Response headers such as Cache-Control or Location are determined through Response.set_header(). This method takes two parameters, the header name and value. The part with the name is case-insensitive:
@route(\'/wiki/<page>\')
def wiki(page):
response.set_header(\'Content-Language\', \'en\')
...
Most headers are unique, meaning only one header is sent to the client with the same name. However, some special headers can appear multiple times in the response. To add an additional header, you must use Response.add_header() instead of Response.set_header():
response.set_header(\'Set-Cookie\', \'name=value\')
response.add_header(\'Set-Cookie\', \'name2=value2\')
This is just an example. More information about working with Cookies will be described below.
Cookies (COOKIES)
Cookie is a named text fragment stored in the user's browser profile. You can access previously defined cookie files using Request.get_cookie() and set new cookie files using Response.set_cookie():
@route(\'/hello\')
def hello_again():
if request.get_cookie("visited"):
return "Добро пожаловать! Рады вновь вас увидеть"
else:
response.set_cookie("visited", "yes")
return "Привет! Рады вас видеть"
The Response.set_cookie() method takes several additional key arguments that control the lifetime and behavior of Cookie. Some of the most common settings are described here:
max_age: maximum lifetime in seconds (default: no)
expires: a datetime object or UNIX timestamp (default: no)
domain: domain that can read the cookie (default: current domain)
path: restrict the cookie to the specified path (default: /)
secure: restrict cookie usage to HTTPS connections (default: disabled)
httponly: prevent the JavaScript file on the client-side from reading this cookie (default: disabled, requires Python 2.7 or later)
same_site: disables cookie usage by third parties. Allowed attributes: lax and strict. In strict mode, cookies are never sent. In lax mode, cookies are sent only with top-level GET requests.
Unless expires or max_age is set, the cookie's lifetime expires at the end of the browser session or immediately after closing the browser window. There are other features to consider when using cookies:
- The cookie size limit is 4 KB text in most browsers.
- Some users configure their browsers to ignore cookies altogether. Most search engines also ignore cookies. Make sure the application still works without cookies.
- Cookies are stored on the client-side and are not encrypted in any way. Everything stored in a cookie can be read by the user. Worse still, an attacker can steal the user's cookies using XSS vulnerabilities. It is known that some viruses read browser cookies. Therefore, never store confidential information in cookies.
- Cookies are easily forged by malicious clients. Never trust cookies.
Signed Cookies (Signed Cookies)
As mentioned above, cookie files are easily forged by malicious clients. Bottle can cryptographically sign cookies to prevent such manipulations. All you need to do is provide the signing key using the secret keyword argument whenever you read or set a cookie, and keep this key secret. As a result, Request.get_cookie() will return None if the cookie is not signed or the signing keys do not match:
@route(\'/login\')
def do_login():
username = request.forms.get(\'username\')
password = request.forms.get(\'password\')
if check_login(username, password):
response.set_cookie("account", username, secret=\'some-secret-key\')
return template("<p>Добро пожаловать {{name}}! Вы не авторизованы.</p>", name=username)
else:
return "<p>Авторизация не удалась.</p>"
@route(\'/restricted\')
def restricted_area():
username = request.get_cookie("account", secret=\'some-secret-key\')
if username:
return template("Привет {{name}}. Добро пожаловать.", name=username)
else:
return "Вы не авторизованы. Доступ запрещён."
Furthermore, Bottle automatically selects and unpacks any data stored in signed cookie files. This allows you to store any object with a signature in cookie files, signed data that does not exceed the 4 KB limit.
Warning:
Signed cookie files are not encrypted (the client can still view the contents) and are not protected from copying (the client can restore the old cookie file). The main goal is to make cookie removal secure and prevent manipulations, not to store secret information on the client-side.
Comments (0)
No comments yet.