API¶
Admin¶
- class Admin(app, auth[, prefix[, name[, branding[, theme]]]])¶
Class used to expose an admin area at a certain url in your application. The Admin object implements a flask blueprint and is 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
Authinstance 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_peewee.admin import Admin from flask_peewee.auth import Auth from flask_peewee.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:
app – flask application to bind admin to
auth –
Authinstance which will provide authenticationprefix – url to bind admin to, defaults to
/adminname – name of the admin blueprint, defaults to
adminbranding – display name shown in the navbar and page titles
theme – name of an admin theme stylesheet.
'<theme>'loadsstatic/css/admin-<theme>.csson top of the baseadmin.css, e.g.theme='crisp'. Defaults toNone, which serves the base stylesheet only. For full control (e.g. a stylesheet hosted outside the admin’s static folder), override thetheme_cssblock inadmin/base.htmlinstead.
- register(model[, admin_class=ModelAdmin])¶
Register a model to expose in the admin area. A
ModelAdminsubclass 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:
model – peewee model to expose via the admin
admin_class –
ModelAdminor subclass to use with given model
- register_panel(title, panel, *args, **kwargs)¶
Register a
AdminPanelsubclass for display in the admin dashboard. Extra arguments are passed through to the panel’s constructor.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:
title – identifier for panel, example might be “Site Stats”
panel – subclass of
AdminPanelto display
- setup()¶
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
main.pyin the example application supplied with flask-peewee.# register all models, etc admin.register(BlogModel) # 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_user_permission(user)¶
Check whether the given user has permission to access the admin area. The default implementation checks whether the
adminfield is set, but you can provide your own logic.This method 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
Authinstance- Return type:
Boolean
- auth_required(func)¶
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 returnsTrueis the actual view function called.
- get_urls()¶
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.
Exposing Models with the ModelAdmin¶
- class ModelAdmin¶
Class that determines how a peewee
Modelis exposed in the admin area. Provides a way of encapsulating model-specific configuration and behaviors. Provided when registering a model with theAdmininstance (seeAdmin.register()).- columns¶
List or tuple of columns should be displayed in the list index. By default if no columns are specified the
Model’s__str__()will be used.Note
Valid values for columns are the following:
field on a model
attribute on a model instance
callable on a model instance (called with no parameters)
method on the
ModelAdmin(called with the model instance), which takes precedence over a model field of the same name
If a column is a model field, it will be sortable.
class EntryAdmin(ModelAdmin): columns = ['title', 'pub_date', 'blog']
- filter_exclude¶
Exclude certain fields from being exposed as filters. Related fields can be excluded using “__” notation, e.g.
user__password
- filter_fields¶
Only allow filtering on the given fields
- max_filter_depth = 3
How many foreign-key hops the filter and export field trees may traverse into related models
- search_fields¶
Char/text field names for the quick-search box, with
__traversal into related models. Empty (the default) hides the search box
- foreign_key_lookups¶
Mapping of foreign-key field name to the related field to search and display on, e.g.
{'user': 'username'}. Replaces the plain<select>with a paginated type-ahead picker
- export_fields¶
Whitelist of field names that may be exported
- export_exclude¶
Blacklist of field names withheld from export. Related models are restricted by their own registered ModelAdmin’s settings
- exclude¶
A list of field names to exclude from the “add” and “edit” forms
- fields¶
Only display the given fields on the “add” and “edit” form
- field_args = None
Per-field keyword arguments passed through to wtf-peewee’s
model_form, e.g.{'content': {'label': 'Body'}}. See Admin Interface for form customization recipes.
- readonly_fields¶
List or tuple of field names to display without editing. Readonly fields are removed from the generated form entirely, so they can never be posted. The edit page renders them as inert values and the add page omits them.
- fieldsets¶
List of
(label, options)tuples grouping the add and edit forms into sections, rendered in order.optionsis a dict with afieldslist and an optionalcollapsedflag. ANonelabel renders an unlabeled section, and fields missing from every section render in a trailing unlabeled one.
- paginate_by = 20
Number of records to display on index pages
- paginate_count = True
Set to
Falseto skipCOUNT()queries on huge tables. The list view then paginates with previous/next links alone, and the dashboard and tab record counts are hidden
- filter_paginate_by = 15
Default pagination when filtering in a modal dialog
- delete_collect_objects = True
Collect and display a list of “dependencies” when deleting
- delete_recursive = True
Delete “dependencies” recursively
- can_add = True
Allow new instances to be added through the admin
- can_edit = True
Allow instances to be edited through the admin
- can_delete = True
Allow instances to be deleted through the admin
- get_query()¶
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.requestobject or use theAuthinstance 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(self): # ask the auth system for the currently logged-in user current_user = self.admin.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
SelectQuerythat represents the list of objects to expose
- get_object(pk)¶
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
DoesNotExistin the event the model instance does not exist.
- get_form([adding=False])¶
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-peewee Form subclass that will be used when adding or editing model instances in the admin.
- get_add_form()¶
Allows you to specify a different form when adding new instances versus editing existing instances. The default implementation calls
get_form().
- get_edit_form(instance)¶
Allows you to specify a different form when editing existing instances versus adding new instances. Receives the instance being edited. The default implementation calls
get_form().
- get_filter_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.
- save_model(instance, form, adding=False)¶
Method responsible for persisting changes to the database. Called by both the add and the edit views.
Here is the implementation from the default
auth.UserModelAdmin, which re-hashes a changed password before the single save so the raw password is never written to the database:def save_model(self, instance, form, adding=False): orig_password = instance.password form.populate_obj(instance) if form.password.data != orig_password: instance.set_password(form.password.data) instance.save(force_insert=adding) return instance
- Parameters:
instance – an unsaved model instance
form – a validated form instance
adding – boolean to indicate whether we are adding a new instance or saving an existing
- check_add(user)¶
Returns whether
usermay add instances, checkingcan_addby default. Denials abort the add view with a 403, and the templates hide the corresponding links.- Return type:
boolean
- check_edit(user)¶
Returns whether
usermay edit instances, checkingcan_editby default. Checked in the edit view before the row is fetched. Override for user-aware rules:class PageAdmin(ModelAdmin): def check_edit(self, user): return user.username == 'admin'
- Return type:
boolean
- check_delete(user)¶
Returns whether
usermay delete instances, checkingcan_deleteby default. Enforced in the delete views and in the index delete action.- Return type:
boolean
- get_template_overrides()¶
Hook for specifying template overrides. Should return a dictionary containing view names as keys and template names as values. Possible choices for keys are:
index
add
edit
delete
action_confirm
export
class UserModelAdmin(ModelAdmin): def get_template_overrides(self): return {'index': 'users/admin/index_override.html'}
- get_urls()¶
Useful as a hook for extending
ModelAdminfunctionality with additional urls.Note
It is not necessary to decorate the views specified by this method since the
Admininstance will handle this during registration and setup.- Return type:
tuple of 2-tuples consisting of a mapping between url and view
- get_url_name(name)¶
Since urls are namespaced, this function provides an easy way to get full urls to views provided by this ModelAdmin
- process_filters(query)¶
Applies any filters specified by the user to the given query, returning metadata about the filters.
Returns a 4-tuple containing:
special
Forminstance containing fields for filteringfiltered query
a list containing the currently selected filters
a tree-structure containing the fields available for filtering (
FieldTreeNode)
- Return type:
A tuple as described above
Bulk actions with Action¶
- class Action([name=None[, description=None[, confirm=False[, form_class=None]]]])¶
A custom bulk operation offered in the list view’s “With selected…” dropdown. Subclass it, implement
callback(), and list an instance inModelAdmin.actions. See Admin Interface for worked examples.- Parameters:
name – dropdown label, defaults to the class name minus the “Action” suffix
description – heading shown on the confirmation page and in the success message, defaults to a title-cased version of
nameconfirm – when
True, run the callback only after the user approves a confirmation page listing the selected rowsform_class – a wtforms form class to render on the confirmation page. Setting it implies confirmation.
- callback(id_list[, form])¶
Perform the action on the selected rows. Receives the primary keys the user checked, restricted to those matching
ModelAdmin.get_query(). Whenform_classis set, the validated form is passed as a second argument.If the return value is a flask
Response, it is sent to the user as-is. Any other return value redirects back to the list view.
Extending admin functionality using AdminPanel¶
- class AdminPanel¶
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. See Admin Interface for example use-cases and a worked panel.
- template_name¶
What template to use to render the panel in the admin dashboard, defaults to
'admin/panels/default.html'.
- get_urls()¶
Useful as a hook for extending
AdminPanelfunctionality with custom urls and views.Note
It is not necessary to decorate the views specified by this method since the
Admininstance will handle this during registration and setup.- Return type:
Returns a tuple of 2-tuples mapping url to view
- get_url_name(name)¶
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')) }}
- get_template_name()¶
Return the template used to render this panel in the dashboard. By default returns the template stored under
AdminPanel.template_name.
- get_context()¶
Return the context to be used when rendering the dashboard template.
- Return type:
Dictionary
- render()¶
Render the panel template with the context. This is what gets displayed in the admin dashboard.
flask_peewee.panels ships one ready-made subclass.
- class RecentRowsPanel(admin, title, model[, columns[, limit[, order_by]]])¶
Display the newest rows of
model. See Admin Interface.
Auth¶
- class Auth(app, db[, user_model[, prefix[, name[, clear_session[, default_next_url[, db_table[, reset]]]]]]])¶
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
Adminand can also be integrated with theRestAPI.Here is an example of how to use the Auth framework:
from flask import Flask from flask_peewee.auth import Auth from flask_peewee.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
Adminor theRestAPI, there is no explicitsetup()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:
app – flask application to bind admin to
db –
Databasedatabase wrapper for flask appuser_model –
Usermodel to useprefix – url to bind authentication views to, defaults to
/accountsname – name of the auth blueprint, defaults to
authclear_session – wipe the entire session on logout, rather than just the auth keys
default_next_url – where to redirect after login or logout when no
?next=is given, defaults to/db_table – table name for the default
Usermodel (useris a reserved word in postgres)reset – enable the
/forgot/and/reset/<token>/password reset views (requires overridingAuth.send_reset_email())
- default_next_url = '/'
The url to redirect to upon successful login in the event a
?next=<xxx>is not provided.
- reset_token_max_age = 3600
Number of seconds a password reset token remains valid.
- get_logged_in_user()¶
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, orNoneif session is anonymous
- login_required(func)¶
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
- get_user_model()¶
- Return type:
Peewee model to use for persisting user data and authentication
- get_model_admin([model_admin=None])¶
Provide a
ModelAdminclass suitable for use with the User model. Specifically addresses the need to re-hash passwords when changing them via the admin.The default implementation overrides
ModelAdmin.save_model()to hash a changed password before the save:class UserAdmin(model_admin): columns = ['username', 'email', 'active', 'admin'] export_exclude = ('password',) def save_model(self, instance, form, adding=False): orig_password = instance.password form.populate_obj(instance) if form.password.data != orig_password: instance.set_password(form.password.data) instance.save(force_insert=adding) return instance
passwordis added to theexport_excludeof themodel_adminpassed in, along with thesession_fieldwhen one is configured. Itscolumnsare used as-is.- Parameters:
model_admin – subclass of
ModelAdminto use as the base class- Return type:
a subclass of
ModelAdminsuitable for use with theUsermodel
- get_urls()¶
A mapping of url to view. The default implementation provides views for login and logout, plus the forgot and reset views when password reset is enabled. You might extend this to add registration or password change views.
Default implementation:
def get_urls(self): urls = ( ('/logout/', self.logout), ('/login/', self.login), ) if self.reset_enabled: urls += ( ('/forgot/', self.forgot), ('/reset/<token>/', self.reset), ) return urls
- Return type:
a tuple of 2-tuples mapping url to view function.
- get_login_form()¶
- Return type:
a
wtforms.Formsubclass to use for retrieving any user info required for login
- get_forgot_form()¶
- Return type:
a
wtforms.Formsubclass used by the forgot view to collect the email address
- get_reset_form()¶
- Return type:
a
wtforms.Formsubclass used by the reset view to collect the new password
- authenticate(username, password)¶
Given the
usernameandpassword, retrieve the user with the matching credentials if they exist. No exceptions should be raised by this method.- Return type:
Usermodel if successful, otherwiseFalse
- login_user(user)¶
Mark the given user as “logged-in”. In the default implementation, this entails storing data in the
Sessionto indicate the successful login.- Parameters:
user –
Userinstance
- logout_user()¶
Mark the requesting user as logged-out, removing the auth keys from the session (or the whole session with
clear_session)
- get_reset_user(form)¶
Find the user a reset link should be sent to. The default implementation matches the submitted email address against active users.
- Parameters:
form – the validated forgot-password form
- Return type:
Userinstance, orNoneif no active user matched
- make_reset_token(user)¶
Create a signed reset token for the given user. The token embeds the user’s primary key and is bound to their current password hash, so changing the password invalidates outstanding tokens.
- Parameters:
user –
Userinstance- Return type:
url-safe token string
- send_reset_email(user, reset_url)¶
Deliver the reset link to the user. The default implementation raises
NotImplementedError, so enablingreset=Truemeans overriding this method.- Parameters:
user –
Userinstance the reset was requested forreset_url – absolute url containing the signed reset token
- parse_reset_token(token)¶
Validate a token produced by
Auth.make_reset_token().- Return type:
the matching active
User, orNoneif the token is invalid, expired, or issued before a password change
The BaseUser mixin¶
- class BaseUser¶
Provides default implementations for password hashing and validation. The auth framework requires two methods be implemented by the
Usermodel. A default implementation of these methods is provided by theBaseUsermixin.- set_password(password)¶
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.
- check_password(password)¶
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
Database¶
- class Database([app=None[, database=None]])¶
The database wrapper provides integration between the peewee ORM and flask. It reads database configuration information from the flask app configuration and manages connections across requests.
The db wrapper also provides a
Modelsubclass which is configured to work with the database specified by the application’s config.- Parameters:
app – a
Flaskinstance orNone(for deferred initialization).database – a peewee database instance or
None. If None then the database can be configured via theapp.configsettings.
To configure the database specify a database engine and name:
DATABASE = { 'name': 'example.db', 'engine': 'peewee.SqliteDatabase', }
The database may also be given as a connection URL, using any scheme
playhouse.db_urlunderstands, or as a pre-configured peewee database instance (aProxyworks too):DATABASE = 'sqlite:///example.db' DATABASE = PostgresqlDatabase('app', user='postgres')
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. name = CharField()
Here is how to defer initialization via
init_app:db = Database() class Blog(db.Model): name = CharField() # ... # Some time later, we can initialize the database wrapper. app = Flask(__name__) app.config.update(DATABASE={'engine': 'peewee.SqliteDatabase', 'name': 'example.db'}) db.init_app(app) # Alternately, we can specify the peewee database instance directly: app = Flask(__name__) sqlite_db = SqliteDatabase('example.db') db.init_app(app, sqlite_db)
- init_app(app[, database=None])¶
- Parameters:
app – a
Flaskinstance.database – a peewee database instance or
None. If None then the database will be configured via theapp.configsettings.
Initialize the Database wrapper with a Flask app you intend to use, optionally specifying a Peewee database instance. If
databaseis None then the database will be loaded fromapp.config.
- get_models()¶
Returns every model subclassing
Model, including subclasses of subclasses. The CLI uses this for table creation and schema diffs.- Return type:
list of Model classes
- Model¶
Model subclass that works with the database specified by the app’s config
REST API¶
- class RestAPI(app[, prefix='/api'[, default_auth=None[, name='api']]])¶
The
RestAPIholds theRestResourceobjects. By default it binds all resources to/api/<model-name>/. Much like theAdmin, it is a centralized registry of resources.Example of creating a
RestAPIinstance for a flask app:from flask_peewee.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
RestAPIhas asetup()method which must be called after all resources have been registered.- Parameters:
app – flask application to bind API to
prefix – url to serve REST API from
default_auth – default
Authenticationtype to use with registered resourcesname – the name for the API blueprint
- register(model[, provider=RestResource[, auth=None[, allowed_methods=None]]])¶
Register a model to expose via the API.
- Parameters:
model –
Modelto expose via APIprovider – subclass of
RestResourceto use for this modelauth – authentication type to use for this resource, falling back to
RestAPI.default_authallowed_methods –
listof HTTP verbs to allow, defaults to['GET', 'POST', 'PUT', 'PATCH', 'DELETE']
- setup()¶
Register the API
BluePrintand configure urls.Warning
This must be called after registering your resources.
RESTful Resources and their subclasses¶
- class RestResource(rest_api, model, authentication[, allowed_methods=None])¶
Class that determines how a peewee
Modelis exposed by the Rest API. Provides a way of encapsulating model-specific configuration and behaviors. Provided when registering a model with theRestAPIinstance (seeRestAPI.register()).Should not be instantiated directly in most cases. Instead should be “registered” with a
RestAPIinstance.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)
- paginate_by = 20
The default page size for a given API query.
Note
A different page size can be requested by specifying a
limit.paginate_byis only the default, not a maximum. Usemax_paginate_byto cap what a client may request.
- max_paginate_by = None
When set, caps the page size a client may request with
limit.
- fields = None
A list or tuple of fields to expose when serializing
- exclude = None
A list or tuple of fields to omit when serializing
- filter_exclude¶
A list of fields that may never be used to filter API results
- filter_fields¶
A list of fields that can be used to filter the API results
- filter_recursive = False
Make every column of a related model filterable through its foreign key. Off by default, since a filter reveals a column’s value even when the column is not serialized. List related columns explicitly (
user__username) instead
- max_filter_depth = 3
How many foreign-key hops filtering may traverse into related models
- readonly_fields = None
A list or tuple of field names that clients may never write. They are stripped from incoming
POST/PUTpayloads at every level, protecting against mass assignment. The primary key is always read-only.
- reject_unknown_fields = False
When
True, a write payload containing unrecognized keys is rejected with a 400 listing them, instead of the keys being silently ignored. Read-only fields are stripped, not rejected, and a foreign key may be written by field name or column name (user/user_id).
- reject_unknown_filters = False
When
True, a query-string filter that matches no filterable field is rejected with a 400 naming it, instead of being silently ignored. Stray non-filter query parameters get the same 400, so enable this only for APIs whose clients send clean query strings.
- include_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 peewee, together at last!", "pub_date": "2026-09-16T18:36:15", "id": 1, "user": 2 }, /* messages with "include_resources = {'user': UserResource} */ { "content": "flask and peewee, together at last!", "pub_date": "2026-09-16T18:36:15", "id": 1, "user": { "username": "coleifer", "active": true, "join_date": "2026-09-16T18:35:56", "admin": false, "id": 2 } }
- nested_writes = True
Whether a nested object in a write payload may create or update the related row. When
Falsea nested object is ignored, though the foreign key may still be assigned by bare id.
- allow_bulk = False
When
True, POST also accepts a JSON list of objects, created in one transaction. An object that fails validation rolls the whole batch back with a 400 naming its index.
- max_bulk = 100
Maximum number of objects accepted in one bulk POST.
- delete_recursive = True
Recursively delete dependencies
- get_query()¶
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(self.model.active == True)
- Return type:
a
SelectQuerycontaining the model instances to expose
- prepare_data(obj, data)¶
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:
obj – the object being serialized
data – the dictionary representation of a model returned by the
Serializer
- Return type:
a dictionary of data to hand off
- save_object(instance, raw_data)¶
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:
instance –
Modelinstance that has already been updated with the incomingraw_dataraw_data – data provided in the request
- Return type:
a saved instance
- api_list()¶
A view that dispatches based on the HTTP verb to either:
GET:
object_list()POST:
create()
- Return type:
Response
- api_detail(pk)¶
A view that dispatches based on the HTTP verb to either:
GET:
object_detail()PUT, PATCH or POST:
edit()DELETE:
delete()
POST /<pk>/delete/is also accepted as an alias for DELETE, for clients that cannot issue PUT or DELETE requests.- Return type:
Response
- object_list()¶
Returns a serialized list of
Modelinstances. These objects may be filtered, ordered, and/or paginated.- Return type:
Response
- object_detail()¶
Returns a serialized
Modelinstance.- Return type:
Response
- create()¶
Creates a new
Modelinstance based on the deserialized POST body.- Return type:
Responsecontaining serialized new object
- edit()¶
Edits an existing
Modelinstance, updating it with the deserialized PUT or PATCH body.- Return type:
Responsecontaining serialized edited object
- delete()¶
Deletes an existing
Modelinstance from the database.- Return type:
Responseindicating number of objects deleted, i.e.{'deleted': 1}
- get_api_name()¶
- Return type:
URL-friendly name to expose this resource as, defaults to the model’s name
- get_urls()¶
The url patterns the resource exposes, as a tuple of 2-tuples mapping url fragment to view. Extend to add custom endpoints alongside the standard list and detail views (see REST API).
- check_get([obj=None])¶
A hook for pre-authorizing a GET request. By default returns
True.- Return type:
Boolean indicating whether to allow the request to continue
- check_post([obj=None])¶
A hook for pre-authorizing a POST request. By default returns
True.objis provided when the POST addresses an existing object (a detail-url edit or a nested write), and isNonefor a create.- Return type:
Boolean indicating whether to allow the request to continue
- check_put(obj)¶
A hook for pre-authorizing a PUT request. By default returns
True.- Return type:
Boolean indicating whether to allow the request to continue
- check_patch(obj)¶
A hook for pre-authorizing a PATCH request. Delegates to
check_put(), so overriding that covers both.- Return type:
Boolean indicating whether to allow the request to continue
- check_delete(obj)¶
A hook for pre-authorizing a DELETE request. By default returns
True.- Return type:
Boolean indicating whether to allow the request to continue
- class RestrictOwnerResource(RestResource)¶
This subclass of
RestResourceallows 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 settingowner_field.Additionally, it sets the “owner” to the authenticated user whenever saving or creating new instances.
- owner_field = 'user'
Field on the model to use to verify ownership of the given instance.
- validate_owner(user, obj)¶
- Parameters:
user – an authenticated
Userinstanceobj – the
Modelinstance being accessed via the API
- Return type:
Boolean indicating whether the user can modify the object
- set_owner(obj, user)¶
Mark the object as being owned by the provided user. The default implementation calls
setattr.- Parameters:
obj – the
Modelinstance being accessed via the APIuser – an authenticated
Userinstance
Authenticating requests to the API¶
- class Authentication([protected_methods=None])¶
Not to be confused with the
Authclass inflask_peewee.auth, 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
- authorize()¶
This single method is called per-API-request.
- Return type:
Boolean indicating whether to allow the given request through or not
- class UserAuthentication(auth[, protected_methods=None])¶
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_peewee.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:
auth – an Authentication instance
protected_methods – A list or tuple of HTTP verbs to require auth for
- authorize()¶
Verifies, using HTTP Basic auth, that the username and password match a valid
auth.Usermodel before allowing the request to continue.- Return type:
Boolean indicating whether to allow the given request through or not
- class AdminAuthentication(auth[, protected_methods=None])¶
Subclass of the
UserAuthenticationthat 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 toTrue.Example usage:
from auth import auth # import the Auth object used by our project from flask_peewee.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()
- verify_user(user)¶
Verifies whether the requesting user is an administrator
- Parameters:
user – the
auth.Userinstance of the requesting user- Return type:
Boolean indicating whether the user is an administrator
- class APIKeyAuthentication(model, protected_methods=None)¶
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:
key
secret
# 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:
model – a
Database.Modelsubclass to persist API keys.protected_methods – A list or tuple of HTTP verbs to require auth for
- class BearerAuthentication(model[, protected_methods=None])¶
Authenticates requests by a token in the
Authorization: Bearer <token>header, looked up inmodel’stokenfield. The matched row is stored ong.api_key. See REST API for examples.- Parameters:
model – model persisting the tokens
protected_methods – A list or tuple of HTTP verbs to require auth for
- token_field = 'token'
Name of the column holding the token.
- get_key(token)¶
Look the token up and return the matching row, or
None. SeeHashedBearerAuthenticationfor tokens hashed at rest.
- class UserBearerAuthentication(model[, protected_methods=None])¶
BearerAuthenticationthat resolves the token to a user and setsg.user, so it works withRestrictOwnerResource. The token model carries a foreign key to the user inuser_field.- user_field = 'user'
Name of the token model’s foreign key to the user. Set to
Nonewhen the token lives on the user model itself.
- class HashedBearerAuthentication(model[, protected_methods=None])¶
BearerAuthenticationfor tokens stored hashed at rest, as created bymake_token_model(). The presented token is hashed with sha256 and looked up in thetoken_hashcolumn, skipping revoked and expired rows. The matching row is stored ong.api_key, andg.useris set to the row’s user when the model has a user foreign key.
- make_token_model(db, user_model=None, db_table='api_token')¶
Create an
ApiTokenmodel bound to the givenDatabasewrapper, withtoken_hash,created,expiresandrevokedcolumns, plus a foreign key touser_modelwhen one is given. Itscreate_token(**kwargs)classmethod generates a token, stores only the sha256 hash (passingkwargsthrough tocreate()), and returns(instance, raw_token).
- ALL_METHODS¶
('GET', 'POST', 'PUT', 'PATCH', 'DELETE'). Pass asprotected_methodsto require authentication on reads as well as writes.
Utilities¶
- get_object_or_404(query_or_model, *query)¶
Provides a handy way of getting an object or 404ing if not found, useful for urls that match based on ID.
- Parameters:
query_or_model – a query or model to filter using the given expressions
query – a list of query expressions
@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)
- object_list(template_name, qr[, var_name='object_list'[, **kwargs]])¶
Wraps the given query and handles pagination automatically. Pagination defaults to
20but can be changed by passing inpaginate_by=XX.- Parameters:
template_name – template to render
qr – a select query
var_name – the template variable name to use for the paginated query
kwargs – arbitrary context to pass in to the template
@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 %}
- get_next()¶
- Return type:
a URL suitable for redirecting to
- slugify(s)¶
Use a regular expression to make arbitrary string
sURL-friendly- Parameters:
s – any string to be slugified
- Return type:
url-friendly version of string
s
- class PaginatedQuery(query_or_model, paginate_by[, use_count=True])¶
A wrapper around a query (or model class) that handles pagination. Pass
use_count=Falseto skip counting.get_list()then fetches one extra row and setshas_nextinstead.- page_var = 'page'
The URL variable used to store the current page
- has_next¶
Whether rows remain beyond the current page. Set by
get_list()whenuse_count=False
- max_page = 1000000
Upper bound on the requested page when
use_count=Falseand there is no page count to clamp to
Example:
query = Blog.select().where(Blog.active==True) pq = PaginatedQuery(query, 20) # 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
- get_list()¶
- Return type:
a list of objects for the request page
- get_page()¶
Clamped to the last page, so an out-of-range
pagedoes not overflow the query’sOFFSET.- Return type:
an integer representing the currently requested page
- get_pages()¶
- Return type:
the number of pages in the entire result set