milla

Milla is an extremely simple WSGI framework for web applications

class milla.Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)[source]

WebOb Request with minor tweaks

GET

Return a MultiDict containing all the variables from the QUERY_STRING.

POST

Return a MultiDict containing all the variables from a form request. Returns an empty dict-like object for non-form requests.

Form requests are typically POST requests, however PUT requests with an appropriate Content-Type are also supported.

ResponseClass

alias of Response

accept

Gets and sets the Accept header (HTTP spec section 14.1).

accept_charset

Gets and sets the Accept-Charset header (HTTP spec section 14.2).

accept_encoding

Gets and sets the Accept-Encoding header (HTTP spec section 14.3).

accept_language

Gets and sets the Accept-Language header (HTTP spec section 14.4).

application_url

The URL including SCRIPT_NAME (no PATH_INFO or query string)

as_bytes(skip_body=False)

Return HTTP bytes representing this request. If skip_body is True, exclude the body. If skip_body is an integer larger than one, skip body only if its length is bigger than that number.

authorization

Gets and sets the Authorization header (HTTP spec section 14.8). Converts it using parse_auth and serialize_auth.

classmethod blank(path, *args, **kwargs)[source]

Create a simple request for the specified path

See webob.Request.blank for information on other arguments and keywords

body

Return the content of the request body.

body_file

Input stream of the request (wsgi.input). Setting this property resets the content_length and seekable flag (unlike setting req.body_file_raw).

body_file_raw

Gets and sets the wsgi.input key in the environment.

body_file_seekable

Get the body of the request (wsgi.input) as a seekable file-like object. Middleware and routing applications should use this attribute over .body_file.

If you access this value, CONTENT_LENGTH will also be updated.

cache_control

Get/set/modify the Cache-Control header (HTTP spec section 14.9)

call_application(application, catch_exc_info=False)

Call the given WSGI application, returning (status_string, headerlist, app_iter)

Be sure to call app_iter.close() if it’s there.

If catch_exc_info is true, then returns (status_string, headerlist, app_iter, exc_info), where the fourth item may be None, but won’t be if there was an exception. If you don’t do this and there was an exception, the exception will be raised directly.

client_addr

The effective client IP address as a string. If the HTTP_X_FORWARDED_FOR header exists in the WSGI environ, this attribute returns the client IP address present in that header (e.g. if the header value is 192.168.1.1, 192.168.1.2, the value will be 192.168.1.1). If no HTTP_X_FORWARDED_FOR header is present in the environ at all, this attribute will return the value of the REMOTE_ADDR header. If the REMOTE_ADDR header is unset, this attribute will return the value None.

Warning

It is possible for user agents to put someone else’s IP or just any string in HTTP_X_FORWARDED_FOR as it is a normal HTTP header. Forward proxies can also provide incorrect values (private IP addresses etc). You cannot “blindly” trust the result of this method to provide you with valid data unless you’re certain that HTTP_X_FORWARDED_FOR has the correct values. The WSGI server must be behind a trusted proxy for this to be true.

content_length

Gets and sets the Content-Length header (HTTP spec section 14.13). Converts it using int.

content_type

Return the content type, but leaving off any parameters (like charset, but also things like the type in application/atom+xml; type=entry)

If you set this property, you can include parameters, or if you don’t include any parameters in the value then existing parameters will be preserved.

cookies

Return a dictionary of cookies as found in the request.

copy()

Copy the request and environment object.

This only does a shallow copy, except of wsgi.input

copy_body()

Copies the body, in cases where it might be shared with another request object and that is not desired.

This copies the body in-place, either into a BytesIO object or a temporary file.

copy_get()

Copies the request and environment object, but turning this request into a GET along the way. If this was a POST request (or any other verb) then it becomes GET, and the request body is thrown away.

create_href(path, **keywords)[source]

Combine the application’s path with a path to form an HREF

Parameters:path – relative path to join with the request URL

Any other keyword arguments will be encoded and appended to the URL as querystring arguments.

The HREF returned will will be the absolute path on the same host and protocol as the request. To get the full URL including scheme and host information, use create_href_full() instead.

create_href_full(path, **keywords)[source]

Combine the application’s full URL with a path to form a new URL

Parameters:path – relative path to join with the request URL

Any other keyword arguments will be encoded and appended to the URL as querystring arguments/

The HREF returned will be the full URL, including scheme and host information. To get the path only, use create_href() instead.

date

Gets and sets the Date header (HTTP spec section 14.8). Converts it using HTTP date.

classmethod from_bytes(b)

Create a request from HTTP bytes data. If the bytes contain extra data after the request, raise a ValueError.

classmethod from_file(fp)

Read a request from a file-like object (it must implement .read(size) and .readline()).

It will read up to the end of the request, not the end of the file (unless the request is a POST or PUT and has no Content-Length, in that case, the entire file is read).

This reads the request as represented by str(req); it may not read every valid HTTP request properly.

get_response(application=None, catch_exc_info=False)

Like .call_application(application), except returns a response object with .status, .headers, and .body attributes.

This will use self.ResponseClass to figure out the class of the response object to return.

If application is not given, this will send the request to self.make_default_send_app()

headers

All the request headers as a case-insensitive dictionary-like object.

host

Host name provided in HTTP_HOST, with fall-back to SERVER_NAME

host_port

The effective server port number as a string. If the HTTP_HOST header exists in the WSGI environ, this attribute returns the port number present in that header. If the HTTP_HOST header exists but contains no explicit port number: if the WSGI url scheme is “https” , this attribute returns “443”, if the WSGI url scheme is “http”, this attribute returns “80” . If no HTTP_HOST header is present in the environ at all, this attribute will return the value of the SERVER_PORT header (which is guaranteed to be present).

host_url

The URL through the host (no path)

http_version

Gets and sets the SERVER_PROTOCOL key in the environment.

if_match

Gets and sets the If-Match header (HTTP spec section 14.24). Converts it as a Etag.

if_modified_since

Gets and sets the If-Modified-Since header (HTTP spec section 14.25). Converts it using HTTP date.

if_none_match

Gets and sets the If-None-Match header (HTTP spec section 14.26). Converts it as a Etag.

if_range

Gets and sets the If-Range header (HTTP spec section 14.27). Converts it using IfRange object.

if_unmodified_since

Gets and sets the If-Unmodified-Since header (HTTP spec section 14.28). Converts it using HTTP date.

is_body_readable

webob.is_body_readable is a flag that tells us that we can read the input stream even though CONTENT_LENGTH is missing. This allows FakeCGIBody to work and can be used by servers to support chunked encoding in requests. For background see https://bitbucket.org/ianb/webob/issue/6

is_body_seekable

Gets and sets the webob.is_body_seekable key in the environment.

is_xhr

Is X-Requested-With header present and equal to XMLHttpRequest?

Note: this isn’t set by every XMLHttpRequest request, it is only set if you are using a Javascript library that sets it (or you set the header yourself manually). Currently Prototype and jQuery are known to set this header.

json

Access the body of the request as JSON

json_body

Access the body of the request as JSON

make_body_seekable()

This forces environ['wsgi.input'] to be seekable. That means that, the content is copied into a BytesIO or temporary file and flagged as seekable, so that it will not be unnecessarily copied again.

After calling this method the .body_file is always seeked to the start of file and .content_length is not None.

The choice to copy to BytesIO is made from self.request_body_tempfile_limit

make_tempfile()

Create a tempfile to store big request body. This API is not stable yet. A ‘size’ argument might be added.

max_forwards

Gets and sets the Max-Forwards header (HTTP spec section 14.31). Converts it using int.

method

Gets and sets the REQUEST_METHOD key in the environment.

params

A dictionary-like object containing both the parameters from the query string and request body.

path

The path of the request, without host or query string

path_info

Gets and sets the PATH_INFO key in the environment.

path_info_peek()

Returns the next segment on PATH_INFO, or None if there is no next segment. Doesn’t modify the environment.

path_info_pop(pattern=None)

‘Pops’ off the next segment of PATH_INFO, pushing it onto SCRIPT_NAME, and returning the popped segment. Returns None if there is nothing left on PATH_INFO.

Does not return '' when there’s an empty segment (like /path//path); these segments are just ignored.

Optional pattern argument is a regexp to match the return value before returning. If there is no match, no changes are made to the request and None is returned.

path_qs

The path of the request, without host but with query string

path_url

The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING

pragma

Gets and sets the Pragma header (HTTP spec section 14.32).

query_string

Gets and sets the QUERY_STRING key in the environment.

range

Gets and sets the Range header (HTTP spec section 14.35). Converts it using Range object.

referer

Gets and sets the Referer header (HTTP spec section 14.36).

referrer

Gets and sets the Referer header (HTTP spec section 14.36).

relative_url(other_url, to_application=False)

Resolve other_url relative to the request URL.

If to_application is True, then resolve it relative to the URL with only SCRIPT_NAME

remote_addr

Gets and sets the REMOTE_ADDR key in the environment.

remote_user

Gets and sets the REMOTE_USER key in the environment.

remove_conditional_headers(remove_encoding=True, remove_range=True, remove_match=True, remove_modified=True)

Remove headers that make the request conditional.

These headers can cause the response to be 304 Not Modified, which in some cases you may not want to be possible.

This does not remove headers like If-Match, which are used for conflict detection.

scheme

Gets and sets the wsgi.url_scheme key in the environment.

script_name

Gets and sets the SCRIPT_NAME key in the environment.

send(application=None, catch_exc_info=False)

Like .call_application(application), except returns a response object with .status, .headers, and .body attributes.

This will use self.ResponseClass to figure out the class of the response object to return.

If application is not given, this will send the request to self.make_default_send_app()

server_name

Gets and sets the SERVER_NAME key in the environment.

server_port

Gets and sets the SERVER_PORT key in the environment. Converts it using int.

static_resource(path)[source]

Return a URL to the given static resource

This method combines the defined static resource root URL with the given path to construct a complete URL to the given resource. The resource root should be defined in the application configuration dictionary, under the name milla.static_root, for example:

app = milla.Application(dispatcher)
app.config.update({
    'milla.static_root': '/static/'
})

Then, calling static_resource on a Request object (i.e. inside a controller callable) would combine the given path with /static/, like this:

request.static_resource('/images/foo.png')

would return /static/images/foo.png.

If no milla.static_root key is found in the configuration dictionary, the path will be returned unaltered.

Parameters:path – Path to the resource, relative to the defined root
str_GET

<Deprecated attribute None>

str_POST

<Deprecated attribute None>

str_cookies

<Deprecated attribute None>

str_params

<Deprecated attribute None>

text

Get/set the text value of the body

upath_info

Gets and sets the PATH_INFO key in the environment.

url

The full request URL, including QUERY_STRING

url_encoding

Gets and sets the webob.url_encoding key in the environment.

urlargs

Return any positional variables matched in the URL.

Takes values from environ['wsgiorg.routing_args']. Systems like routes set this value.

urlvars

Return any named variables matched in the URL.

Takes values from environ['wsgiorg.routing_args']. Systems like routes set this value.

uscript_name

Gets and sets the SCRIPT_NAME key in the environment.

user_agent

Gets and sets the User-Agent header (HTTP spec section 14.43).

class milla.Response(body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, **kw)[source]

WebOb Response with minor tweaks

accept_ranges

Gets and sets the Accept-Ranges header (HTTP spec section 14.5).

age

Gets and sets the Age header (HTTP spec section 14.6). Converts it using int.

allow

Gets and sets the Allow header (HTTP spec section 14.7). Converts it using list.

app_iter

Returns the app_iter of the response.

If body was set, this will create an app_iter from that body (a single-item list)

app_iter_range(start, stop)

Return a new app_iter built from the response app_iter, that serves up only the given start:stop range.

body

The body of the response, as a str. This will read in the entire app_iter if necessary.

body_file

A file-like object that can be used to write to the body. If you passed in a list app_iter, that app_iter will be modified by writes.

cache_control

Get/set/modify the Cache-Control header (HTTP spec section 14.9)

charset

Get/set the charset (in the Content-Type)

conditional_response_app(environ, start_response)

Like the normal __call__ interface, but checks conditional headers:

  • If-Modified-Since (304 Not Modified; only on GET, HEAD)
  • If-None-Match (304 Not Modified; only on GET, HEAD)
  • Range (406 Partial Content; only on GET, HEAD)
content_disposition

Gets and sets the Content-Disposition header (HTTP spec section 19.5.1).

content_encoding

Gets and sets the Content-Encoding header (HTTP spec section 14.11).

content_language

Gets and sets the Content-Language header (HTTP spec section 14.12). Converts it using list.

content_length

Gets and sets the Content-Length header (HTTP spec section 14.17). Converts it using int.

content_location

Gets and sets the Content-Location header (HTTP spec section 14.14).

content_md5

Gets and sets the Content-MD5 header (HTTP spec section 14.14).

content_range

Gets and sets the Content-Range header (HTTP spec section 14.16). Converts it using ContentRange object.

content_type

Get/set the Content-Type header (or None), without the charset or any parameters.

If you include parameters (or ; at all) when setting the content_type, any existing parameters will be deleted; otherwise they will be preserved.

content_type_params

A dictionary of all the parameters in the content type.

(This is not a view, set to change, modifications of the dict would not be applied otherwise)

copy()

Makes a copy of the response

date

Gets and sets the Date header (HTTP spec section 14.18). Converts it using HTTP date.

Delete a cookie from the client. Note that path and domain must match how the cookie was originally set.

This sets the cookie to the empty string, and max_age=0 so that it should expire immediately.

encode_content(encoding='gzip', lazy=False)

Encode the content with the given encoding (only gzip and identity are supported).

etag

Gets and sets the ETag header (HTTP spec section 14.19). Converts it using Entity tag.

expires

Gets and sets the Expires header (HTTP spec section 14.21). Converts it using HTTP date.

classmethod from_file(fp)

Reads a response from a file-like object (it must implement .read(size) and .readline()).

It will read up to the end of the response, not the end of the file.

This reads the response as represented by str(resp); it may not read every valid HTTP response properly. Responses must have a Content-Length

headerlist

The list of response headers

headers

The headers in a dictionary-like object

json

Access the body of the response as JSON

json_body

Access the body of the response as JSON

last_modified

Gets and sets the Last-Modified header (HTTP spec section 14.29). Converts it using HTTP date.

location

Gets and sets the Location header (HTTP spec section 14.30).

md5_etag(body=None, set_content_md5=False)

Generate an etag for the response object using an MD5 hash of the body (the body parameter, or self.body if not given)

Sets self.etag If set_content_md5 is True sets self.content_md5 as well

merge_cookies(resp)

Merge the cookies that were set on this response with the given resp object (which can be any WSGI application).

If the resp is a webob.Response object, then the other object will be modified in-place.

pragma

Gets and sets the Pragma header (HTTP spec section 14.32).

retry_after

Gets and sets the Retry-After header (HTTP spec section 14.37). Converts it using HTTP date or delta seconds.

server

Gets and sets the Server header (HTTP spec section 14.38).

Set (add) a cookie for the response.

Arguments are:

key

The cookie name.

value

The cookie value, which should be a string or None. If value is None, it’s equivalent to calling the webob.response.Response.unset_cookie() method for this cookie key (it effectively deletes the cookie on the client).

max_age

An integer representing a number of seconds or None. If this value is an integer, it is used as the Max-Age of the generated cookie. If expires is not passed and this value is an integer, the max_age value will also influence the Expires value of the cookie (Expires will be set to now + max_age). If this value is None, the cookie will not have a Max-Age value (unless expires is also sent).

path

A string representing the cookie Path value. It defaults to /.

domain

A string representing the cookie Domain, or None. If domain is None, no Domain value will be sent in the cookie.

secure

A boolean. If it’s True, the secure flag will be sent in the cookie, if it’s False, the secure flag will not be sent in the cookie.

httponly

A boolean. If it’s True, the HttpOnly flag will be sent in the cookie, if it’s False, the HttpOnly flag will not be sent in the cookie.

comment

A string representing the cookie Comment value, or None. If comment is None, no Comment value will be sent in the cookie.

expires

A datetime.timedelta object representing an amount of time or the value None. A non-None value is used to generate the Expires value of the generated cookie. If max_age is not passed, but this value is not None, it will influence the Max-Age header (Max-Age will be ‘expires_value - datetime.utcnow()’). If this value is None, the Expires cookie value will be unset (unless max_age is also passed).

overwrite

If this key is True, before setting the cookie, unset any existing cookie.
status

The status string

status_code

The status as an integer

status_int

The status as an integer

text

Get/set the text value of the body (using the charset of the Content-Type)

ubody

Deprecated alias for .text

unicode_body

Deprecated alias for .text

Unset a cookie with the given name (remove it from the response).

vary

Gets and sets the Vary header (HTTP spec section 14.44). Converts it using list.

www_authenticate

Gets and sets the WWW-Authenticate header (HTTP spec section 14.47). Converts it using parse_auth and serialize_auth.

milla.allow(*methods)[source]

Specify the allowed HTTP verbs for a controller callable

Example:

@milla.allow('GET', 'POST')
def controller(request):
    return 'Hello, world!'

Project Versions

Previous topic

milla.controllers

Next topic

milla.util

This Page