Coaster provides functions and decorators for common scenarios in view handlers.
Exception that combines TypeError with BadRequest. Used by requestargs().
Exception that combines ValueError with BadRequest. Used by requestargs().
Return the current URL including the query string as a relative path.
Get the next URL to redirect to. Don’t return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs.
This function looks for a next parameter in the request or in the session (depending on whether parameter session is True). If no next is present, it checks the referrer (if enabled), and finally returns either the provided default (which can be any value including None) or url_for('index'). If your app does not have a URL endpoint named index, / is returned.
Returns a JSON response with a callback wrapper, if asked for.
Decorator to load a model given a query parameter.
Typical usage:
@app.route('/<profile>')
@load_model(Profile, {'name': 'profile'}, 'profileob')
def profile_view(profileob):
# 'profileob' is now a Profile model instance. The load_model decorator replaced this:
# profileob = Profile.query.filter_by(name=profile).first_or_404()
return "Hello, %s" % profileob.name
Using the same name for request and parameter makes code easier to understand:
@app.route('/<profile>')
@load_model(Profile, {'name': 'profile'}, 'profile')
def profile_view(profile):
return "Hello, %s" % profile.name
load_model aborts with a 404 if no instance is found. load_model also recognizes queries to url_name of BaseIdNameMixin instances and will automatically load the model. TODO: that should be handled by the model, not here.
Parameters: |
|
---|
Decorator to load a chain of models from the given parameters. This works just like load_model() and accepts the same parameters, with some small differences.
Parameters: |
|
---|
In the following example, load_models loads a Folder with a name matching the name in the URL, then loads a Page with a matching name and with the just-loaded Folder as parent. If the Page provides a ‘view’ permission to the current user (g.user), the decorated function is called:
@app.route('/<folder_name>/<page_name>')
@load_models(
(Folder, {'name': 'folder_name'}, 'folder'),
(Page, {'name': 'page_name', 'parent': 'folder'}, 'page'),
permission='view')
def show_page(folder, page):
return render_template('page.html', folder=folder, page=page)
Decorator to render the wrapped method with the given template (or dictionary of mimetype keys to templates, where the template is a string name of a template file or a callable that returns a Response). The method’s return value must be a dictionary and is passed to the template as parameters. Callable templates get a single parameter with the method’s return value. Usage:
@app.route('/myview')
@render_with('myview.html')
def myview():
return {'data': 'value'}
@app.route('/otherview')
@render_with({
'text/html': 'otherview.html',
'text/xml': 'otherview.xml'})
def otherview():
return {'data': 'value'}
When a mimetype is specified and the template is not a callable, the response is returned with the same mimetype. Callable templates must return Response objects to ensure the correct mimetype is set.
If the method is called outside a request context, the wrapped method’s original return value is returned. This is meant to facilitate testing and should not be used to call the method from within another view handler as the presence of a request context will trigger template rendering.
Rendering may also be suspended by calling the view handler with _render=False.
render_with provides a default handler for the application/json, text/json and text/x-json mimetypes.
Decorator that loads parameters from request.values if not specified in the function’s keyword arguments. Usage:
@requestargs('param1', ('param2', int), 'param3[]', ...)
def function(param1, param2=0, param3=None):
...
requestargs takes a list of parameters to pass to the wrapped function, with an optional filter (useful to convert incoming string request data into integers and other common types). If a required parameter is missing and your function does not specify a default value, Python will raise TypeError. requestargs recasts this as RequestTypeError, which returns HTTP 400 Bad Request.
If the parameter name ends in [], requestargs will attempt to read a list from the incoming data. Filters are applied to each member of the list, not to the whole list.
If the filter raises a ValueError, this is recast as a RequestValueError, which also returns HTTP 400 Bad Request.
Tests:
>>> from flask import Flask
>>> app = Flask(__name__)
>>>
>>> @requestargs('p1', ('p2', int), ('p3[]', int))
... def f(p1, p2=None, p3=None):
... return p1, p2, p3
...
>>> f(p1=1)
(1, None, None)
>>> f(p1=1, p2=2)
(1, 2, None)
>>> f(p1='a', p2='b')
('a', 'b', None)
>>> with app.test_request_context('/?p2=2'):
... f(p1='1')
...
('1', 2, None)
>>> with app.test_request_context('/?p3=1&p3=2'):
... f(p1='1', p2='2')
...
('1', '2', [1, 2])