Requests and Responses are crucial parts of a HTTP framework - the request contains data that is received from the client, and the Response contains data that is sent to the Client.
Kyoukai piggybacks off of Werkzeug for its request and response wrappers - this means that most of the request is handled by a well tested library used in thousands of applications across the web.
The Request
object for the current request is available on
request
for your route functions to use.
For example, returning a JSON blob of the headers:
async def my_route(ctx: HTTPRequestContext):
headers = json.dumps(dict(ctx.request.headers))
return headers
werkzeug.wrappers.
Request
Represents a request incoming from the client.
Request.
accept_charsets
¶List of charsets this client supports as
CharsetAccept
object.
Request.
accept_encodings
¶List of encodings this client accepts. Encodings in a HTTP term
are compression encodings such as gzip. For charsets have a look at
accept_charset
.
Request.
accept_languages
¶List of languages this client accepts as
LanguageAccept
object.
Request.
accept_mimetypes
¶List of mimetypes this client supports as
MIMEAccept
object.
Request.
access_route
¶If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server.
Request.
args
¶The parsed URL parameters (the part in the URL after the question mark).
By default an
ImmutableMultiDict
is returned from this function. This can be changed by setting
parameter_storage_class
to a different type. This might
be necessary if the order of the form data is important.
The Authorization object in parsed form.
Request.
base_url
¶Like url
but without the querystring
See also: trusted_hosts
.
Request.
cache_control
¶A RequestCacheControl
object
for the incoming cache control headers.
A dict
with the contents of all cookies transmitted with
the request.
Request.
data
¶Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle.
Request.
files
¶MultiDict
object containing
all uploaded files. Each key in files
is the name from the
<input type="file" name="">
. Each value in files
is a
Werkzeug FileStorage
object.
It basically behaves like a standard file object you know from Python,
with the difference that it also has a
save()
function that can
store the file on the filesystem.
Note that files
will only contain data if the request method was
POST, PUT or PATCH and the <form>
that posted to the request had
enctype="multipart/form-data"
. It will be empty otherwise.
See the MultiDict
/
FileStorage
documentation for
more details about the used data structure.
Request.
form
¶The form parameters. By default an
ImmutableMultiDict
is returned from this function. This can be changed by setting
parameter_storage_class
to a different type. This might
be necessary if the order of the form data is important.
Please keep in mind that file uploads will not end up here, but instead
in the files
attribute.
Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.
Request.
full_path
¶Requested path as unicode, including the query string.
Request.
headers
¶The headers from the WSGI environ as immutable
EnvironHeaders
.
Request.
host
¶Just the host including the port if available.
See also: trusted_hosts
.
Request.
host_url
¶Just the host with scheme as IRI.
See also: trusted_hosts
.
Request.
if_modified_since
¶The parsed If-Modified-Since header as datetime object.
Request.
if_none_match
¶An object containing all the etags in the If-None-Match header.
Return type: | ETags |
---|
Request.
if_unmodified_since
¶The parsed If-Unmodified-Since header as datetime object.
Request.
is_secure
¶True if the request is secure.
Request.
is_xhr
¶True if the request was triggered via a JavaScript XMLHttpRequest. This only works with libraries that support the X-Requested-With header and set it to “XMLHttpRequest”. Libraries that do that are prototype, jQuery and Mochikit and probably some more.
Request.
method
¶The request method. (For example 'GET'
or 'POST'
).
Request.
path
¶Requested path as unicode. This works a bit like the regular path info in the WSGI environment but will always include a leading slash, even if the URL root is accessed.
Request.
query_string
¶The URL parameters as raw bytestring.
Request.
remote_addr
¶The remote address of the client.
Request.
remote_user
¶If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.
Request.
scheme
¶URL scheme (http or https).
New in version 0.7.
Request.
trusted_hosts
= None¶Request.
url
¶The reconstructed current URL as IRI.
See also: trusted_hosts
.
Request.
url_charset
¶The charset that is assumed for URLs. Defaults to the value
of charset
.
New in version 0.6.
Request.
values
¶A werkzeug.datastructures.CombinedMultiDict
that combines
args
and form
.
Request.
get_data
(cache=True, as_text=False, parse_form_data=False)¶This reads the buffered incoming data from the client into one bytestring. By default this is cached but that behavior can be changed by setting cache to False.
Usually it’s a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server.
Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory.
If as_text is set to True the return value will be a decoded unicode string.
New in version 0.9.
Responses are automatically created for you when you return from a route function or error handler. However, it is possible to create them manually:
async def my_route(ctx: HTTPRequestContext):
return Response("Hello, world", status=200)
werkzeug.wrappers.
Response
Represents a response from the server to the client.
Response.
__init__
(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)¶Response.
data
¶A descriptor that calls get_data()
and set_data()
. This
should not be used and will eventually get deprecated.
Response.
status
¶The HTTP Status code
Response.
status_code
¶The HTTP Status code as number
Response.
freeze
()¶Call this method if you want to make your response object ready for being pickled. This buffers the generator if there is one. It will also set the Content-Length header to the length of the body.
Changed in version 0.6: The Content-Length header is now set.
Response.
get_data
(as_text=False)¶The string representation of the request body. Whenever you call this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
implicit_sequence_conversion
to False.
If as_text is set to True the return value will be a decoded unicode string.
New in version 0.9.
Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
Parameters: |
|
---|
Delete a cookie. Fails silently if key doesn’t exist.
Parameters: |
|
---|
Response.
set_data
(value)¶Sets a new string as response. The value set must either by a unicode or bytestring. If a unicode string is set it’s encoded automatically to the charset of the response (utf-8 by default).
New in version 0.9.
New in version 2.1.3.
There are some built-in helper functions to encode data in a certain form:
kyoukai.util.
as_html
(text, code=200, headers=None)[source]Returns a HTML response.
return as_html("<h1>Hel Na</h1>", code=403)
Parameters: | |
---|---|
Return type: | |
Returns: | A new |
kyoukai.util.
as_plaintext
(text, code=200, headers=None)[source]Returns a plaintext response.
return as_plaintext("hel yea", code=201)
Parameters: | |
---|---|
Return type: | |
Returns: | A new |
kyoukai.util.
as_json
(data, code=200, headers=None, *, json_encoder=None, **kwargs)[source]Returns a JSON response.
return as_json({"response": "yes", "code": 201}, code=201)
Parameters: | |
---|---|
Return type: | |
Returns: | A new |