Class used to expose an admin area at a certain url in your application. The Admin object implements a flask blueprint and acts as the central registry for models and panels you wish to expose in the admin.
The Admin object coordinates the registration of models and panels and provides a method for ensuring a user has permission to access the admin area.
The Admin object requires an Auth instance when being instantiated, which in turn requires a Flask app and a py:class:Database wrapper.
Here is an example of how you might instantiate an Admin object:
from flask import Flask
from flask_turboduck.admin import Admin
from flask_turboduck.auth import Auth
from flask_turboduck.db import Database
app = Flask(__name__)
db = Database(app)
# needed for authentication
auth = Auth(app, db)
# instantiate the Admin object for our project
admin = Admin(app, auth)
| Parameters: |
|
|---|
Register a model to expose in the admin area. A ModelAdmin subclass can be provided along with the model, allowing for customization of the model’s display and behavior.
Example usage:
# will use the default ModelAdmin subclass to display model
admin.register(BlogModel)
class EntryAdmin(ModelAdmin):
columns = ('title', 'blog', 'pub_date',)
admin.register(EntryModel, EntryAdmin)
Warning
All models must be registered before calling setup()
| Parameters: |
|
|---|
Register a AdminPanel subclass for display in the admin dashboard.
Example usage:
class HelloWorldPanel(AdminPanel):
template_name = 'admin/panels/hello.html'
def get_context(self):
return {
'message': 'Hello world',
}
admin.register_panel('Hello world', HelloWorldPanel)
Warning
All panels must be registered before calling setup()
| Parameters: |
|
|---|
Configures urls for models and panels, then registers blueprint with the Flask application. Use this method when you have finished registering all the models and panels with the admin object, but before starting the WSGI application. For a sample implementation, check out example/main.py in the example application supplied with flask-turboduck.
# register all models, etc
admin.register(...)
# finish up initialization of the admin object
admin.setup()
if __name__ == '__main__':
# run the WSGI application
app.run()
Note
call setup() after registering your models and panels
Check whether the given user has permission to access to the admin area. The default implementation simply checks whether the admin field is checked, but you can provide your own logic.
This method simply controls access to the admin area as a whole. In the event the user is not permitted to access the admin (this function returns False), they will receive a HTTP Response Forbidden (403).
Default implementation:
def check_user_permission(self, user):
return user.admin
| Parameters: | user – the currently logged-in user, exposed by the Auth instance |
|---|---|
| Return type: | Boolean |
Decorator that ensures the requesting user has permission. The implementation first checks whether the requesting user is logged in, and if not redirects to the login view. If the user is logged in, it calls check_user_permission(). Only if this call returns True is the actual view function called.
Get a tuple of 2-tuples mapping urls to view functions that will be exposed by the admin. The default implementation looks like this:
def get_urls(self):
return (
('/', self.auth_required(self.index)),
)
This method provides an extension point for providing any additional “global” urls you would like to expose.
Note
Remember to decorate any additional urls you might add with auth_required() to ensure they are not accessible by unauthenticated users.
Class that determines how a turboduck Model is exposed in the admin area. Provides a way of encapsulating model-specific configuration and behaviors. Provided when registering a model with the Admin instance (see Admin.register()).
List or tuple of columns should be displayed in the list index. By default if no columns are specified the Model‘s __unicode__() will be used.
Note
Valid values for columns are the following:
If a column is a model field, it will be sortable.
class EntryAdmin(ModelAdmin):
columns = ['title', 'pub_date', 'blog']
Exclude certain fields from being exposed as filters. Related fields can be excluded using “__” notation, e.g. user__password
Only allow filtering on the given fields
A list of field names to exclude from the “add” and “edit” forms
Only display the given fields on the “add” and “edit” form
Number of records to display on index pages
Default pagination when filtering in a modal dialog
Collect and display a list of “dependencies” when deleting
Delete “dependencies” recursively
Determines the list of objects that will be exposed in the admin. By default this will be all objects, but you can use this method to further restrict the query.
This method is called within the context of a request, so you can access the Flask.request object or use the Auth instance to determine the currently-logged-in user.
Here’s an example showing how the query is restricted based on whether the given user is a “super user” or not:
class UserAdmin(ModelAdmin):
def get_query():
# ask the auth system for the currently logged-in user
current_user = self.auth.get_logged_in_user()
# if they are not a superuser, only show them their own
# account in the admin
if not current_user.is_superuser:
return User.select().where(User.id==current_user.id)
# otherwise, show them all users
return User.select()
| Return type: | A SelectQuery that represents the list of objects to expose |
|---|
This method retrieves the object matching the given primary key. The implementation uses get_query() to retrieve the base list of objects, then queries within that for the given primary key.
| Return type: | The model instance with the given pk, raising a DoesNotExist in the event the model instance does not exist. |
|---|
Provides a useful extension point in the event you want to define custom fields or custom validation behavior.
| Parameters: | adding (boolean) – indicates whether adding a new instance or editing existing |
|---|---|
| Return type: | A wtf-turboduck Form subclass that will be used when adding or editing model instances in the admin. |
Allows you to specify a different form when adding new instances versus editing existing instances. The default implementation simply calls get_form().
Allows you to specify a different form when editing existing instances versus adding new instances. The default implementation simply calls get_form().
Provide a special form for use when filtering the list of objects in the model admin’s index/export views. This form is slightly different in that it is tailored for use when filtering the list of models.
| Return type: | A special Form instance (FilterForm) that will be used when filtering the list of objects in the index view. |
|---|
Method responsible for persisting changes to the database. Called by both the add and the edit views.
Here is an example from the default auth.User ModelAdmin, in which the password is displayed as a sha1, but if the user is adding or edits the existing password, it re-hashes:
def save_model(self, instance, form, adding=False):
orig_password = instance.password
user = super(UserAdmin, self).save_model(instance, form, adding)
if orig_password != form.password.data:
user.set_password(form.password.data)
user.save()
return user
| Parameters: |
|
|---|
Hook for specifying template overrides. Should return a dictionary containing view names as keys and template names as values. Possible choices for keys are:
class UserModelAdmin(ModelAdmin):
def get_template_overrides(self):
return {'index': 'users/admin/index_override.html'}
Useful as a hook for extending ModelAdmin functionality with additional urls.
Note
It is not necessary to decorate the views specified by this method since the Admin instance will handle this during registration and setup.
| Return type: | tuple of 2-tuples consisting of a mapping between url and view |
|---|
Since urls are namespaced, this function provides an easy way to get full urls to views provided by this ModelAdmin
Applies any filters specified by the user to the given query, returning metadata about the filters.
Returns a 4-tuple containing:
| Return type: | A tuple as described above |
|---|
Class that provides a simple interface for providing arbitrary extensions to the admin. These are displayed as “panels” on the admin dashboard with a customizable template. They may additionally, however, define any views and urls. These views will automatically be protected by the same authentication used throughout the admin area.
Some example use-cases for AdminPanels might be:
What template to use to render the panel in the admin dashboard, defaults to 'admin/panels/default.html'.
Useful as a hook for extending AdminPanel functionality with custom urls and views.
Note
It is not necessary to decorate the views specified by this method since the Admin instance will handle this during registration and setup.
| Return type: | Returns a tuple of 2-tuples mapping url to view |
|---|
Since urls are namespaced, this function provides an easy way to get full urls to views provided by this panel
| Parameters: | name – string representation of the view function whose url you want |
|---|---|
| Return type: | String representing url |
<!-- taken from example -->
<!-- will return something like /admin/notes/create/ -->
{{ url_for(panel.get_url_name('create')) }}
Return the template used to render this panel in the dashboard. By default simply returns the template stored under AdminPanel.template_name.
Return the context to be used when rendering the dashboard template.
| Return type: | Dictionary |
|---|
Render the panel template with the context – this is what gets displayed in the admin dashboard.
The class that provides methods for authenticating users and tracking users across requests. It also provides a model for persisting users to the database, though this can be customized.
The auth framework is used by the Admin and can also be integrated with the RestAPI.
Here is an example of how to use the Auth framework:
from flask import Flask
from flask_turboduck.auth import Auth
from flask_turboduck.db import Database
app = Flask(__name__)
db = Database(app)
# needed for authentication
auth = Auth(app, db)
# mark a view as requiring login
@app.route('/private/')
@auth.login_required
def private_timeline():
# get the currently-logged-in user
user = auth.get_logged_in_user()
Unlike the Admin or the RestAPI, there is no explicit setup() method call when using the Auth system. Creation of the auth blueprint and registration with the Flask app happen automatically during instantiation.
Note
A context processor is automatically registered that provides the currently logged-in user across all templates, available as “user”. If no user is logged in, the value of this will be None.
Note
A pre-request handler is automatically registered which attempts to retrieve the current logged-in user and store it on the global flask variable g.
| Parameters: |
|
|---|
The url to redirect to upon successful login in the event a ?next=<xxx> is not provided.
Note
Since this method relies on the session storage to track users across requests, this method must be called while within a RequestContext.
| Return type: | returns the currently logged-in User, or None if session is anonymous |
|---|
Function decorator that ensures a view is only accessible by authenticated users. If the user is not authed they are redirected to the login view.
Note
this decorator should be applied closest to the original view function
@app.route('/private/')
@auth.login_required
def private():
# this view is only accessible by logged-in users
return render_template('private.html')
| Parameters: | func – a view function to be marked as login-required |
|---|---|
| Return type: | if the user is logged in, return the view as normal, otherwise returns a redirect to the login page |
| Return type: | turboduck model to use for persisting user data and authentication |
|---|
Provide a ModelAdmin class suitable for use with the User model. Specifically addresses the need to re-hash passwords when changing them via the admin.
The default implementation includes an override of the ModelAdmin.save_model() method to intelligently hash passwords:
class UserAdmin(model_admin):
columns = ['username', 'email', 'active', 'admin']
def save_model(self, instance, form, adding=False):
orig_password = instance.password
user = super(UserAdmin, self).save_model(instance, form, adding)
if orig_password != form.password.data:
user.set_password(form.password.data)
user.save()
return user
| Parameters: | model_admin – subclass of ModelAdmin to use as the base class |
|---|---|
| Return type: | a subclass of ModelAdmin suitable for use with the User model |
A mapping of url to view. The default implementation provides views for login and logout only, but you might extend this to add registration and password change views.
Default implementation:
def get_urls(self):
return (
('/logout/', self.logout),
('/login/', self.login),
)
| Return type: | a tuple of 2-tuples mapping url to view function. |
|---|
| Return type: | a wtforms.Form subclass to use for retrieving any user info required for login |
|---|
Given the username and password, retrieve the user with the matching credentials if they exist. No exceptions should be raised by this method.
| Return type: | User model if successful, otherwise False |
|---|
Mark the given user as “logged-in”. In the default implementation, this entails storing data in the Session to indicate the successful login.
| Parameters: | user – User instance |
|---|
Mark the requesting user as logged-out
| Parameters: | user – User instance |
|---|
Provides default implementations for password hashing and validation. The auth framework requires two methods be implemented by the User model. A default implementation of these methods is provided by the BaseUser mixin.
Encrypts the given password and stores the encrypted version on the model. This method is useful when registering a new user and storing the password, or modifying the password when a user elects to change.
Verifies if the given plaintext password matches the encrypted version stored on the model. This method on the User model is called specifically by the Auth.authenticate() method.
| Return type: | Boolean |
|---|
The database wrapper provides integration between the turboduck ORM and flask. It reads database configuration information from the flask app configuration and manages connections across requests.
The db wrapper also provides a Model subclass which is configured to work with the database specified by the application’s config.
To configure the database specify a database engine and name:
DATABASE = {
'name': 'example.db',
'engine': 'turboduck.SqliteDatabase',
}
Here is an example of how you might use the database wrapper:
# instantiate the db wrapper
db = Database(app)
# start creating models
class Blog(db.Model):
# this model will automatically work with the database specified
# in the application's config.
| Parameters: | app – flask application to bind admin to |
|---|
Model subclass that works with the database specified by the app’s config
The RestAPI acts as a container for the various RestResource objects. By default it binds all resources to /api/<model-name>/. Much like the Admin, it is a centralized registry of resources.
Example of creating a RestAPI instance for a flask app:
from flask_turboduck.rest import RestAPI
from app import app # our project's Flask app
# instantiate our api wrapper
api = RestAPI(app)
# register a model with the API
api.register(SomeModel)
# configure URLs
api.setup()
Note
Like the flask admin, the RestAPI has a setup() method which must be called after all resources have been registered.
| Parameters: |
|
|---|
Register a model to expose via the API.
| Parameters: |
|
|---|
Register the API BluePrint and configure urls.
Warning
This must be called after registering your resources.
Class that determines how a turboduck Model is exposed by the Rest API. Provides a way of encapsulating model-specific configuration and behaviors. Provided when registering a model with the RestAPI instance (see RestAPI.register()).
Should not be instantiated directly in most cases. Instead should be “registered” with a RestAPI instance.
Example usage:
# instantiate our api wrapper, passing in a reference to the Flask app
api = RestAPI(app)
# create a RestResource subclass
class UserResource(RestResource):
exclude = ('password', 'email',)
# assume we have a "User" model, register it with the custom resource
api.register(User, UserResource)
Determines how many results to return for a given API query.
Note
Fewer results can be requested by specifying a limit, but paginate_by is the upper bound.
A list or tuple of fields to expose when serializing
A list or tuple of fields to not expose when serializing
A list of fields that cannot be used to filter API results
A list of fields that can be used to filter the API results
Allow filtering on related resources
A mapping of field name to resource class for handling of foreign-keys. When provided, foreign keys will be “nested”.
class UserResource(RestResource):
exclude = ('password', 'email')
class MessageResource(RestResource):
include_resources = {'user': UserResource} # 'user' is a foreign key field
/* messages without "include_resources" */
{
"content": "flask and turboduck, together at last!",
"pub_date": "2011-09-16 18:36:15",
"id": 1,
"user": 2
},
/* messages with "include_resources = {'user': UserResource} */
{
"content": "flask and turboduck, together at last!",
"pub_date": "2011-09-16 18:36:15",
"id": 1,
"user": {
"username": "coleifer",
"active": true,
"join_date": "2011-09-16 18:35:56",
"admin": false,
"id": 2
}
}
Recursively delete dependencies
Returns the list of objects to be exposed by the API. Provides an easy hook for restricting objects:
class UserResource(RestResource):
def get_query(self):
# only return "active" users
return self.model.select().where(active=True)
| Return type: | a SelectQuery containing the model instances to expose |
|---|
This method provides a hook for modifying outgoing data. The default implementation no-ops, but you could do any kind of munging here. The data returned by this method is passed to the serializer before being returned as a json response.
| Parameters: |
|
|---|---|
| Return type: | a dictionary of data to hand off |
Persist the instance to the database. The raw data supplied by the request is also available, but at the time this method is called the instance has already been updated and populated with the incoming data.
| Parameters: |
|
|---|---|
| Return type: | a saved instance |
A view that dispatches based on the HTTP verb to either:
| Return type: | Response |
|---|
A view that dispatches based on the HTTP verb to either:
| Return type: | Response |
|---|
Returns a serialized list of Model instances. These objects may be filtered, ordered, and/or paginated.
| Return type: | Response |
|---|
Returns a serialized Model instance.
| Return type: | Response |
|---|
Creates a new Model instance based on the deserialized POST body.
| Return type: | Response containing serialized new object |
|---|
Edits an existing Model instance, updating it with the deserialized PUT body.
| Return type: | Response containing serialized edited object |
|---|
Deletes an existing Model instance from the database.
| Return type: | Response indicating number of objects deleted, i.e. {'deleted': 1} |
|---|
| Return type: | URL-friendly name to expose this resource as, defaults to the model’s name |
|---|
A hook for pre-authorizing a GET request. By default returns True.
| Return type: | Boolean indicating whether to allow the request to continue |
|---|
A hook for pre-authorizing a POST request. By default returns True.
| Return type: | Boolean indicating whether to allow the request to continue |
|---|
A hook for pre-authorizing a PUT request. By default returns True.
| Return type: | Boolean indicating whether to allow the request to continue |
|---|
A hook for pre-authorizing a DELETE request. By default returns True.
| Return type: | Boolean indicating whether to allow the request to continue |
|---|
This subclass of RestResource allows only the “owner” of an object to make changes via the API. It works by verifying that the authenticated user matches the “owner” of the model instance, which is specified by setting owner_field.
Additionally, it sets the “owner” to the authenticated user whenever saving or creating new instances.
Field on the model to use to verify ownership of the given instance.
| Parameters: |
|
|---|---|
| Return type: | Boolean indicating whether the user can modify the object |
Mark the object as being owned by the provided user. The default implementation simply calls setattr.
| Parameters: |
|
|---|
Not to be confused with the auth.Authentication class, this class provides a single method, authorize, which is used to determine whether to allow a given request to the API.
| Parameters: | protected_methods – A list or tuple of HTTP verbs to require auth for |
|---|
This single method is called per-API-request.
| Return type: | Boolean indicating whether to allow the given request through or not |
|---|
Authenticates API requests by requiring the requesting user be a registered auth.User. Credentials are supplied using HTTP basic auth.
Example usage:
from auth import auth # import the Auth object used by our project
from flask_turboduck.rest import RestAPI, RestResource, UserAuthentication
# create an instance of UserAuthentication
user_auth = UserAuthentication(auth)
# instantiate our api wrapper, specifying user_auth as the default
api = RestAPI(app, default_auth=user_auth)
# create a special resource for users that excludes email and password
class UserResource(RestResource):
exclude = ('password', 'email',)
# register our models so they are exposed via /api/<model>/
api.register(User, UserResource) # specify the UserResource
# configure the urls
api.setup()
| Parameters: |
|
|---|
Verifies, using HTTP Basic auth, that the username and password match a valid auth.User model before allowing the request to continue.
| Return type: | Boolean indicating whether to allow the given request through or not |
|---|
Subclass of the UserAuthentication that further restricts which users are allowed through. The default implementation checks whether the requesting user is an “admin” by checking whether the admin attribute is set to True.
Example usage:
Authenticates API requests by requiring the requesting user be a registered auth.User. Credentials are supplied using HTTP basic auth.
Example usage:
from auth import auth # import the Auth object used by our project
from flask_turboduck.rest import RestAPI, RestResource, UserAuthentication, AdminAuthentication
# create an instance of UserAuthentication and AdminAuthentication
user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)
# instantiate our api wrapper, specifying user_auth as the default
api = RestAPI(app, default_auth=user_auth)
# create a special resource for users that excludes email and password
class UserResource(RestResource):
exclude = ('password', 'email',)
# register our models so they are exposed via /api/<model>/
api.register(SomeModel)
# specify the UserResource and require the requesting user be an admin
api.register(User, UserResource, auth=admin_auth)
# configure the urls
api.setup()
Verifies whether the requesting user is an administrator
| Parameters: | user – the auth.User instance of the requesting user |
|---|---|
| Return type: | Boolean indicating whether the user is an administrator |
Subclass that allows you to provide an API Key model to authenticate requests with.
Note
Must provide an API key model with at least the following two fields:
# example API key model
class APIKey(db.Model):
key = CharField()
secret = CharField()
user = ForeignKeyField(User)
# instantiating the auth
api_key_auth = APIKeyAuthentication(model=APIKey)
| Parameters: |
|
|---|
Provides a handy way of getting an object or 404ing if not found, useful for urls that match based on ID.
| Parameters: |
|
|---|
@app.route('/blog/<title>/')
def blog_detail(title):
blog = get_object_or_404(Blog.select().where(Blog.active==True), Blog.title==title)
return render_template('blog/detail.html', blog=blog)
Wraps the given query and handles pagination automatically. Pagination defaults to 20 but can be changed by passing in paginate_by=XX.
| Parameters: |
|
|---|
@app.route('/blog/')
def blog_list():
active = Blog.select().where(Blog.active==True)
return object_list('blog/index.html', active)
<!-- template -->
{% for blog in object_list %}
{# render the blog here #}
{% endfor %}
{% if page > 1 %}
<a href="./?page={{ page - 1 }}">Prev</a>
{% endif %}
{% if page < pagination.get_pages() %}
<a href="./?page={{ page + 1 }}">Next</a>
{% endif %}
| Return type: | a URL suitable for redirecting to |
|---|
Use a regular expression to make arbitrary string s URL-friendly
| Parameters: | s – any string to be slugified |
|---|---|
| Return type: | url-friendly version of string s |
A wrapper around a query (or model class) that handles pagination.
The URL variable used to store the current page
Example:
query = Blog.select().where(Blog.active==True)
pq = PaginatedQuery(query)
# assume url was /?page=3
obj_list = pq.get_list() # returns 3rd page of results
pq.get_page() # returns "3"
pq.get_pages() # returns total objects / objects-per-page
| Return type: | a list of objects for the request page |
|---|
| Return type: | an integer representing the currently requested page |
|---|
| Return type: | the number of pages in the entire result set |
|---|