The Application class builds upon pants.contrib.http.HTTPServer, adding support for request routing, additional error handling, and a degree of convenience that makes writing dynamic pages easier.
Instances of Application are callable, and may be used as a HTTPServer’s request handler.
| Argument | Description |
|---|---|
| default_domain | Optional. The default domain to search for a route for if the request’s Host does not exist. |
| debug | Optional. If this is set to True, automatically generated 500 Internal Server Error response pages will include information about the failed request, including a traceback of the exception that caused the page to be generated. |
This function exists for convenience, and when called creates a HTTPServer instance with its request handler set to this application instance, calls listen() on that HTTPServer, and finally, starts the Pants engine to process requests.
| Argument | Description |
|---|---|
| port | Optional. The port to listen on. If this isn’t specified, it will be either 80 or 443, depending on whether or not SSL options for the server have been provided. |
| host | Optional. The host interface to listen on. If this isn’t specified, listen on all interfaces. |
| ssl_options | Optional. A dict of SSL options for the server. See pants.contrib.ssl.SSLServer for more information. |
The basic_route decorator registers a route with the Application without holding your hand over it.
It functions almost the same as the Application.route() decorator, but doesn’t wrap the provided function with any argument handling code. Instead, you’re provided with the request object and the the regex match object.
Example Usage:
@app.basic_route("/char/<char>")
def my_route(request):
char, = request.match.groups()
return 'The character is %s!' % char
That is, essentially, equivilent to:
@app.route("/char/<char>/")
def my_route(char):
return 'The character is %s!' % char
| Argument | Description |
|---|---|
| rule | The route rule to match for a request to go to the decorated function. See Application.route() for more information. |
| name | Optional. The name of the decorated function, for use with the url_for() helper function. |
| methods | Optional. A list of HTTP methods to allow for this request handler. By default, only GET and HEAD requests are allowed, and all others will result in a 405 Method Not Allowed error. |
The route decorator is used to register a new request handler with the Application instance. Example:
@app.route("/")
def hello_world():
return "Hiya, Everyone!"
Variables may be specified in the route rule by wrapping them with inequality signs (for example: <variable_name>). By default, a variable part accepts any character except a slash (/) and returns a string value. However, you may specify a specific type to be returned by using the format <type:name>, where type is the name of a callable in the pants.contrib.web namespace that accepts a single string as its argument, and returns a value. Built-in types, such as int and float, work well for this. Example:
@app.route("/user/<int:id>/")
def user(id):
return "Hi, user %d!" % id
The id is automatically converted into an integer for you, and as an added bonus, your function is never even called if the provided value for id isn’t a valid number.
Request handlers are easy to write and can send their output to the client simply by returning a value, such as a string:
@app.route("/")
def hello_world():
return "Hiya, Everyone!"
The previous code would result in a 200 OK` response, with a Content-Type header of text/plain, and a Content-Length header of 15. With, of course, the body Hiya, Everyone!.
If the returned string begins with <!DOCTYPE or <html, it will be assumed that the response is of Content-Type: text/html.
If a unicode object is returned, rather than a simple string, it will be automatically encoded and an encoding argument will be added to the Content-Type header.
If a dictionary is returned, it will be automatically converted to a string of JSON and the Content-Type header will be set to application/json.
If any other object is returned, it will be converted to a string via str() before any content headers are set. The exception to this is that, if the object has a __html__ method, that method will be called rather than str(), and the Content-Type will be automatically assumed to be text/html, regardless of the actual content of the string.
A tuple of (body, status) or (body, status, headers) may be returned, rather than simply a body, to set the HTTP status code of the result and additional response headers. If provided, status must be an integer, and headers must be a dict.
The following example returns a page with the status code 404 Not Found:
@app.route("/nowhere")
def nowhere():
return "This does not exist.", 404
| Argument | Description |
|---|---|
| rule | The route rule to be matched for the decorated function to be used for handling a request. |
| name | Optional. The name of the decorated function, for use with the url_for() helper function. |
| methods | Optional. A list of HTTP methods to allow for this request handler. By default, only GET and HEAD requests are allowed, and all others will result in a 405 Method Not Allowed error. |
| auto404 | Optional. If this is set to True, all response handler arguments will be checked for truthiness (True, non-empty strings, etc.) and, if any fail, a 404 Not Found page will be rendered automatically. |
The FileServer is a request handling class that, as it sounds, serves files to the client. It also supports the Content-Range header, HEAD requests, and last modified dates.
| Argument | Default | Description |
|---|---|---|
| path | The path to serve. | |
| blacklist | .py and .pyc files | Optional. A list of regular expressions to test filenames against. If a given file matches any of the provided patterns, it will not be downloadable and instead return a 403 Unauthorized error. |
| default | index.html, index.htm | Optional. A list of default files to be displayed rather than a directory listing if they exist. |
| renderers | None | Optional. A dictionary of methods for rendering files with a given extension into more suitable output, such as converting rST to HTML, or minifying CSS. |
It attempts to serve the files as efficiently as possible, using the sendfile system call when possible, and with proper use of ETags and other headers to minimize repetitive downloading.
Using it is simple. It only requires a single argument: the path to serve files from. You can also supply a list of default files to check to serve rather than a file listing.
When used with an Application, the FileServer is not created in the usual way with the route decorator, but rather with a method of the FileServer itself. Example:
FileServer("/tmp/path").attach(app)
If you wish to listen on a path other than /static/, you can also use that when attaching:
FileServer("/tmp/path").attach(app, "/files/")
Attach this fileserver to an application, bypassing the usual route decorator to ensure things are done right.
| Argument | Default | Description |
|---|---|---|
| app | The Application instance to attach to. | |
| path | '/static/' | Optional. The path to serve requests from. |
| domain | None | Optional. The domain to serve requests upon. |
Raise a HTTPException to display an error page.
If any of the provided arguments aren’t truthy, raise a 404 Not Found exception. This is automatically called for you if you set auto404=True when using the route decorator.
Return a very simple error page, defaulting to a 404 Not Found error if no status code is supplied. Usually, you’ll want to call abort() in your code, rather than error(), to streamline the process of abandoning your code. Usage:
return error(404)
return error("Some message.", 404)
return error("Blah blah blah.", 403, {'Some-Header':'Fish'})
Construct a 302 Found response to instruct the client’s browser to redirect its request to a different URL. Other codes may be returned by specifying a status.
| Argument | Default | Description |
|---|---|---|
| uri | The URI to redirect the client’s browser to. | |
| status | 302 | Optional. The status code to send with the response. |
Generates a URL to the route with the given name. The name is relative to the module of the route function. Examples:
| View’s Module | Target Endpoint | Target Function |
|---|---|---|
| test | index | test.index |
| test | .who | The first who function in any module. |
| test | admin.login | admin.login |
Any value provided to the function with an unknown key is appended to the generated URL as query arguments. For example, take the following route:
@app.route("/user/<int:id>/")
def user_page(id):
pass
Assuming url_for is used within the same module, the following examples will hold true:
>>> url_for("user_page", id=12)
'/user/12/'
>>> url_for("user_page", id=12, section=3)
'/user/12/?section=3'
>>> url_for("user_page", id=12, _external=True)
'http://www.example.com/user/12/'
As demonstrated above, the _external parameter is special, and will result in the generation of a full URL, using the scheme and host provided by the current request.
Note: This function has not yet been updated to properly make use of domains.
Raising an instance of HTTPException will cause the Application to render an error page out to the client with the given HTTP status code, message, and any provided headers.
This is, generally, preferable to allowing an exception of a different type to bubble up to the Application, which would result in a 500 Internal Server Error page.
The abort() helper function makes it easy to raise instances of this exception.
| Argument | Description |
|---|---|
| status | Optional. The HTTP status code to generate an error page for. If this isn’t specified, a 404 Not Found page will be generated. |
| message | Optional. A text message to display on the error page. |
| headers | Optional. A dict of extra HTTP headers to return with the rendered page. |