Debian Codegraph @

docs/api.rst

raw
1 .. _api:
2
3 API
4 ===
5
6 Admin
7 -----
8
9 .. py:class:: Admin(app, auth[, prefix[, name[, branding[, theme]]]])
10
11 Class used to expose an admin area at a certain url in your application. The
12 Admin object implements a flask blueprint and acts as the central registry
13 for models and panels you wish to expose in the admin.
14
15 The Admin object coordinates the registration of models and panels and provides
16 a method for ensuring a user has permission to access the admin area.
17
18 The Admin object requires an :py:class:`Auth` instance when being instantiated,
19 which in turn requires a Flask app and a py:class:`Database` wrapper.
20
21 Here is an example of how you might instantiate an Admin object:
22
23 .. code-block:: python
24
25 from flask import Flask
26
27 from flask_peewee.admin import Admin
28 from flask_peewee.auth import Auth
29 from flask_peewee.db import Database
30
31 app = Flask(__name__)
32 db = Database(app)
33
34 # needed for authentication
35 auth = Auth(app, db)
36
37 # instantiate the Admin object for our project
38 admin = Admin(app, auth)
39
40 :param app: flask application to bind admin to
41 :param auth: :py:class:`Auth` instance which will provide authentication
42 :param prefix: url to bind admin to, defaults to ``/admin``
43 :param name: name of the admin blueprint, defaults to ``admin``
44 :param branding: display name shown in the navbar and page titles
45 :param theme: name of an admin theme stylesheet; ``'<theme>'`` loads
46 ``static/css/admin-<theme>.css`` on top of the base ``admin.css``,
47 e.g. ``theme='crisp'``. Defaults to ``None``, which serves the base
48 stylesheet only. For full control (e.g. a stylesheet hosted outside
49 the admin's static folder), override the ``theme_css`` block in
50 ``admin/base.html`` instead.
51
52 .. py:method:: register(model[, admin_class=ModelAdmin])
53
54 Register a model to expose in the admin area. A :py:class:`ModelAdmin`
55 subclass can be provided along with the model, allowing for customization
56 of the model's display and behavior.
57
58 Example usage:
59
60 .. code-block:: python
61
62 # will use the default ModelAdmin subclass to display model
63 admin.register(BlogModel)
64
65 class EntryAdmin(ModelAdmin):
66 columns = ('title', 'blog', 'pub_date',)
67
68 admin.register(EntryModel, EntryAdmin)
69
70 .. warning:: All models must be registered before calling :py:meth:`~Admin.setup`
71
72 :param model: peewee model to expose via the admin
73 :param admin_class: :py:class:`ModelAdmin` or subclass to use with given model
74
75 .. py:method:: register_panel(title, panel)
76
77 Register a :py:class:`AdminPanel` subclass for display in the admin dashboard.
78
79 Example usage:
80
81 .. code-block:: python
82
83 class HelloWorldPanel(AdminPanel):
84 template_name = 'admin/panels/hello.html'
85
86 def get_context(self):
87 return {
88 'message': 'Hello world',
89 }
90
91 admin.register_panel('Hello world', HelloWorldPanel)
92
93 .. warning:: All panels must be registered before calling :py:meth:`~Admin.setup`
94
95 :param title: identifier for panel, example might be "Site Stats"
96 :param panel: subclass of :py:class:`AdminPanel` to display
97
98 .. py:method:: setup()
99
100 Configures urls for models and panels, then registers blueprint with the
101 Flask application. Use this method when you have finished registering
102 all the models and panels with the admin object, but before starting
103 the WSGI application. For a sample implementation, check out ``main.py``
104 in the `example application
105 <https://github.com/coleifer/flask-peewee/tree/master/example>`_ supplied
106 with flask-peewee.
107
108 .. code-block:: python
109
110 # register all models, etc
111 admin.register(...)
112
113 # finish up initialization of the admin object
114 admin.setup()
115
116 if __name__ == '__main__':
117 # run the WSGI application
118 app.run()
119
120 .. note::
121 call ``setup()`` **after** registering your models and panels
122
123 .. py:method:: check_user_permission(user)
124
125 Check whether the given user has permission to access to the admin area. The
126 default implementation simply checks whether the ``admin`` field is checked,
127 but you can provide your own logic.
128
129 This method simply controls access to the admin area as a whole. In the
130 event the user is **not** permitted to access the admin (this function
131 returns ``False``), they will receive a HTTP Response Forbidden (403).
132
133 Default implementation:
134
135 .. code-block:: python
136
137 def check_user_permission(self, user):
138 return user.admin
139
140 :param user: the currently logged-in user, exposed by the :py:class:`Auth` instance
141 :rtype: Boolean
142
143 .. py:method:: auth_required(func)
144
145 Decorator that ensures the requesting user has permission. The implementation
146 first checks whether the requesting user is logged in, and if not redirects
147 to the login view. If the user *is* logged in, it calls :py:meth:`~Admin.check_user_permission`.
148 Only if this call returns ``True`` is the actual view function called.
149
150 .. py:method:: get_urls()
151
152 Get a tuple of 2-tuples mapping urls to view functions that will be
153 exposed by the admin. The default implementation looks like this:
154
155 .. code-block:: python
156
157 def get_urls(self):
158 return (
159 ('/', self.auth_required(self.index)),
160 )
161
162 This method provides an extension point for providing any additional
163 "global" urls you would like to expose.
164
165 .. note:: Remember to decorate any additional urls you might add
166 with :py:meth:`~Admin.auth_required` to ensure they are not accessible
167 by unauthenticated users.
168
169
170 Exposing Models with the ModelAdmin
171 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
172
173 .. py:class:: ModelAdmin
174
175 Class that determines how a peewee ``Model`` is exposed in the admin area. Provides
176 a way of encapsulating model-specific configuration and behaviors. Provided
177 when registering a model with the :py:class:`Admin` instance (see :py:meth:`Admin.register`).
178
179 .. py:attribute:: columns
180
181 List or tuple of columns should be displayed in the list index. By default if no
182 columns are specified the ``Model``'s ``__str__()`` will be used.
183
184 .. note::
185
186 Valid values for columns are the following:
187
188 * field on a model
189 * attribute on a model instance
190 * callable on a model instance (called with no parameters)
191
192 If a column is a model field, it will be sortable.
193
194 .. code-block:: python
195
196 class EntryAdmin(ModelAdmin):
197 columns = ['title', 'pub_date', 'blog']
198
199 .. py:attribute:: filter_exclude
200
201 Exclude certain fields from being exposed as filters. Related fields can
202 be excluded using "__" notation, e.g. ``user__password``
203
204 .. py:attribute:: filter_fields
205
206 Only allow filtering on the given fields
207
208 .. py:attribute:: exclude
209
210 A list of field names to exclude from the "add" and "edit" forms
211
212 .. py:attribute:: fields
213
214 Only display the given fields on the "add" and "edit" form
215
216 .. py:attribute:: paginate_by = 20
217
218 Number of records to display on index pages
219
220 .. py:attribute:: filter_paginate_by = 15
221
222 Default pagination when filtering in a modal dialog
223
224 .. py:attribute:: delete_collect_objects = True
225
226 Collect and display a list of "dependencies" when deleting
227
228 .. py:attribute:: delete_recursive = True
229
230 Delete "dependencies" recursively
231
232 .. py:method:: get_query()
233
234 Determines the list of objects that will be exposed in the admin. By
235 default this will be all objects, but you can use this method to further
236 restrict the query.
237
238 This method is called within the context of a request, so you can access
239 the ``Flask.request`` object or use the :py:class:`Auth` instance to
240 determine the currently-logged-in user.
241
242 Here's an example showing how the query is restricted based on whether
243 the given user is a "super user" or not:
244
245 .. code-block:: python
246
247 class UserAdmin(ModelAdmin):
248 def get_query():
249 # ask the auth system for the currently logged-in user
250 current_user = self.auth.get_logged_in_user()
251
252 # if they are not a superuser, only show them their own
253 # account in the admin
254 if not current_user.is_superuser:
255 return User.select().where(User.id==current_user.id)
256
257 # otherwise, show them all users
258 return User.select()
259
260 :rtype: A ``SelectQuery`` that represents the list of objects to expose
261
262 .. py:method:: get_object(pk)
263
264 This method retrieves the object matching the given primary key. The
265 implementation uses :py:meth:`~ModelAdmin.get_query` to retrieve the
266 base list of objects, then queries within that for the given primary key.
267
268 :rtype: The model instance with the given pk, raising a ``DoesNotExist``
269 in the event the model instance does not exist.
270
271 .. py:method:: get_form([adding=False])
272
273 Provides a useful extension point in the event you want to define custom
274 fields or custom validation behavior.
275
276 :param boolean adding: indicates whether adding a new instance or editing existing
277 :rtype: A `wtf-peewee <https://github.com/coleifer/wtf-peewee>`_ Form subclass that
278 will be used when adding or editing model instances in the admin.
279
280 .. py:method:: get_add_form()
281
282 Allows you to specify a different form when adding new instances versus
283 editing existing instances. The default implementation simply calls
284 :py:meth:`~ModelAdmin.get_form`.
285
286 .. py:method:: get_edit_form()
287
288 Allows you to specify a different form when editing existing instances versus
289 adding new instances. The default implementation simply calls
290 :py:meth:`~ModelAdmin.get_form`.
291
292 .. py:method:: get_filter_form()
293
294 Provide a special form for use when filtering the list of objects in the model admin's
295 index/export views. This form is slightly different in that it is tailored for use
296 when filtering the list of models.
297
298 :rtype: A special Form instance (:py:class:`FilterForm`) that will be used
299 when filtering the list of objects in the index view.
300
301 .. py:method:: save_model(instance, form, adding=False)
302
303 Method responsible for persisting changes to the database. Called by both
304 the add and the edit views.
305
306 Here is an example from the default ``auth.User`` :py:class:`ModelAdmin`,
307 in which the password is displayed as a sha1, but if the user is adding
308 or edits the existing password, it re-hashes:
309
310 .. code-block:: python
311
312 def save_model(self, instance, form, adding=False):
313 orig_password = instance.password
314
315 user = super(UserAdmin, self).save_model(instance, form, adding)
316
317 if orig_password != form.password.data:
318 user.set_password(form.password.data)
319 user.save()
320
321 return user
322
323 :param instance: an unsaved model instance
324 :param form: a validated form instance
325 :param adding: boolean to indicate whether we are adding a new instance
326 or saving an existing
327
328 .. py:method:: get_template_overrides()
329
330 Hook for specifying template overrides. Should return a dictionary containing
331 view names as keys and template names as values. Possible choices for keys are:
332
333 * index
334 * add
335 * edit
336 * delete
337 * export
338
339 .. code-block:: python
340
341 class UserModelAdmin(ModelAdmin):
342 def get_template_overrides(self):
343 return {'index': 'users/admin/index_override.html'}
344
345 .. py:method:: get_urls()
346
347 Useful as a hook for extending :py:class:`ModelAdmin` functionality
348 with additional urls.
349
350 .. note::
351 It is not necessary to decorate the views specified by this method
352 since the :py:class:`Admin` instance will handle this during registration
353 and setup.
354
355 :rtype: tuple of 2-tuples consisting of a mapping between url and view
356
357 .. py:method:: get_url_name(name)
358
359 Since urls are namespaced, this function provides an easy way to get
360 full urls to views provided by this ModelAdmin
361
362 .. py:method:: process_filters(query)
363
364 Applies any filters specified by the user to the given query, returning
365 metadata about the filters.
366
367 Returns a 4-tuple containing:
368
369 * special ``Form`` instance containing fields for filtering
370 * filtered query
371 * a list containing the currently selected filters
372 * a tree-structure containing the fields available for filtering (:py:class:`FieldTreeNode`)
373
374 :rtype: A tuple as described above
375
376
377 Extending admin functionality using AdminPanel
378 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
379
380 .. py:class:: AdminPanel
381
382 Class that provides a simple interface for providing arbitrary extensions to
383 the admin. These are displayed as "panels" on the admin dashboard with a customizable
384 template. They may additionally, however, define any views and urls. These
385 views will automatically be protected by the same authentication used throughout
386 the admin area.
387
388 Some example use-cases for AdminPanels might be:
389
390 * Display some at-a-glance functionality in the dashboard, like stats on new
391 user signups.
392 * Provide a set of views that should only be visible to site administrators,
393 for example a mailing-list app.
394 * Control global site settings, turn on and off features, etc.
395
396 .. py:attribute:: template_name
397
398 What template to use to render the panel in the admin dashboard, defaults
399 to ``'admin/panels/default.html'``.
400
401 .. py:method:: get_urls()
402
403 Useful as a hook for extending :py:class:`AdminPanel` functionality
404 with custom urls and views.
405
406 .. note::
407 It is not necessary to decorate the views specified by this method
408 since the :py:class:`Admin` instance will handle this during registration
409 and setup.
410
411 :rtype: Returns a tuple of 2-tuples mapping url to view
412
413 .. py:method:: get_url_name(name)
414
415 Since urls are namespaced, this function provides an easy way to get
416 full urls to views provided by this panel
417
418 :param name: string representation of the view function whose url you want
419 :rtype: String representing url
420
421 .. code-block:: html
422
423 <!-- taken from example -->
424 <!-- will return something like /admin/notes/create/ -->
425 {{ url_for(panel.get_url_name('create')) }}
426
427 .. py:method:: get_template_name()
428
429 Return the template used to render this panel in the dashboard. By default
430 simply returns the template stored under :py:attr:`AdminPanel.template_name`.
431
432 .. py:method:: get_context()
433
434 Return the context to be used when rendering the dashboard template.
435
436 :rtype: Dictionary
437
438 .. py:method:: render()
439
440 Render the panel template with the context -- this is what gets displayed
441 in the admin dashboard.
442
443
444 Auth
445 ----
446
447 .. py:class:: Auth(app, db[, user_model=None[, prefix='/accounts']], db_table='user')
448
449 The class that provides methods for authenticating users and tracking
450 users across requests. It also provides a model for persisting users to
451 the database, though this can be customized.
452
453 The auth framework is used by the :py:class:`Admin` and can also be integrated
454 with the :py:class:`RestAPI`.
455
456 Here is an example of how to use the Auth framework:
457
458 .. code-block:: python
459
460 from flask import Flask
461
462 from flask_peewee.auth import Auth
463 from flask_peewee.db import Database
464
465 app = Flask(__name__)
466 db = Database(app)
467
468 # needed for authentication
469 auth = Auth(app, db)
470
471 # mark a view as requiring login
472 @app.route('/private/')
473 @auth.login_required
474 def private_timeline():
475 # get the currently-logged-in user
476 user = auth.get_logged_in_user()
477
478 Unlike the :py:class:`Admin` or the :py:class:`RestAPI`, there is no explicit
479 ``setup()`` method call when using the Auth system. Creation of the auth
480 blueprint and registration with the Flask app happen automatically during
481 instantiation.
482
483 .. note:: A context processor is automatically registered that provides
484 the currently logged-in user across all templates, available as "user".
485 If no user is logged in, the value of this will be ``None``.
486
487 .. note:: A pre-request handler is automatically registered which attempts
488 to retrieve the current logged-in user and store it on the global flask
489 variable ``g``.
490
491 :param app: flask application to bind admin to
492 :param db: :py:class:`Database` database wrapper for flask app
493 :param user_model: ``User`` model to use
494 :param prefix: url to bind authentication views to, defaults to /accounts/
495 :param db_table: Create db table using db_table name. ``user`` is reserved keyword in postgres.
496
497 .. py:attribute:: default_next_url = '/'
498
499 The url to redirect to upon successful login in the event a ``?next=<xxx>``
500 is not provided.
501
502 .. py:method:: get_logged_in_user()
503
504 .. note:: Since this method relies on the session storage to
505 track users across requests, this method must be called while
506 within a ``RequestContext``.
507
508 :rtype: returns the currently logged-in ``User``, or ``None`` if session is anonymous
509
510 .. py:method:: login_required(func)
511
512 Function decorator that ensures a view is only accessible by authenticated
513 users. If the user is not authed they are redirected to the login view.
514
515 .. note:: this decorator should be applied closest to the original view function
516
517 .. code-block:: python
518
519 @app.route('/private/')
520 @auth.login_required
521 def private():
522 # this view is only accessible by logged-in users
523 return render_template('private.html')
524
525 :param func: a view function to be marked as login-required
526 :rtype: if the user is logged in, return the view as normal, otherwise
527 returns a redirect to the login page
528
529 .. py:method:: get_user_model()
530
531 :rtype: Peewee model to use for persisting user data and authentication
532
533 .. py:method:: get_model_admin([model_admin=None])
534
535 Provide a :py:class:`ModelAdmin` class suitable for use with the User
536 model. Specifically addresses the need to re-hash passwords when changing
537 them via the admin.
538
539 The default implementation includes an override of the :py:meth:`ModelAdmin.save_model`
540 method to intelligently hash passwords:
541
542 .. code-block:: python
543
544 class UserAdmin(model_admin):
545 columns = ['username', 'email', 'active', 'admin']
546
547 def save_model(self, instance, form, adding=False):
548 orig_password = instance.password
549
550 user = super(UserAdmin, self).save_model(instance, form, adding)
551
552 if orig_password != form.password.data:
553 user.set_password(form.password.data)
554 user.save()
555
556 return user
557
558 :param model_admin: subclass of :py:class:`ModelAdmin` to use as the base class
559 :rtype: a subclass of :py:class:`ModelAdmin` suitable for use with the ``User`` model
560
561 .. py:method:: get_urls()
562
563 A mapping of url to view. The default implementation provides views for
564 login and logout only, but you might extend this to add registration and
565 password change views.
566
567 Default implementation:
568
569 .. code-block:: python
570
571 def get_urls(self):
572 return (
573 ('/logout/', self.logout),
574 ('/login/', self.login),
575 )
576
577 :rtype: a tuple of 2-tuples mapping url to view function.
578
579 .. py:method:: get_login_form()
580
581 :rtype: a ``wtforms.Form`` subclass to use for retrieving any user info required for login
582
583 .. py:method:: authenticate(username, password)
584
585 Given the ``username`` and ``password``, retrieve the user with the matching
586 credentials if they exist. No exceptions should be raised by this method.
587
588 :rtype: ``User`` model if successful, otherwise ``False``
589
590 .. py:method:: login_user(user)
591
592 Mark the given user as "logged-in". In the default implementation, this
593 entails storing data in the ``Session`` to indicate the successful login.
594
595 :param user: ``User`` instance
596
597 .. py:method:: logout_user(user)
598
599 Mark the requesting user as logged-out
600
601 :param user: ``User`` instance
602
603
604 The BaseUser mixin
605 ^^^^^^^^^^^^^^^^^^
606
607 .. py:class:: BaseUser()
608
609 Provides default implementations for password hashing and validation. The
610 auth framework requires two methods be implemented by the ``User`` model. A
611 default implementation of these methods is provided by the ``BaseUser`` mixin.
612
613 .. py:method:: set_password(password)
614
615 Encrypts the given password and stores the encrypted version on the model.
616 This method is useful when registering a new user and storing the password,
617 or modifying the password when a user elects to change.
618
619 .. py:method:: check_password(password)
620
621 Verifies if the given plaintext password matches the encrypted version stored
622 on the model. This method on the User model is called specifically by
623 the :py:meth:`Auth.authenticate` method.
624
625 :rtype: Boolean
626
627
628 Database
629 --------
630
631 .. py:class:: Database([app=None[, database=None]])
632
633 The database wrapper provides integration between the peewee ORM and flask.
634 It reads database configuration information from the flask app configuration
635 and manages connections across requests.
636
637 The db wrapper also provides a ``Model`` subclass which is configured to work
638 with the database specified by the application's config.
639
640 :param app: a ``Flask`` instance or ``None`` (for deferred initialization).
641 :param db: a peewee database instance or ``None``. If None then the
642 database can be configured via the ``app.config`` settings.
643
644 To configure the database specify a database engine and name:
645
646 .. code-block:: python
647
648 DATABASE = {
649 'name': 'example.db',
650 'engine': 'peewee.SqliteDatabase',
651 }
652
653 Here is an example of how you might use the database wrapper:
654
655 .. code-block:: python
656
657 # instantiate the db wrapper
658 db = Database(app)
659
660 # start creating models
661 class Blog(db.Model):
662 # this model will automatically work with the database specified
663 # in the application's config.
664 name = CharField()
665
666 Here is how to defer initialization via ``init_app``:
667
668 .. code-block:: python
669
670 db = Database()
671
672 class Blog(db.Model):
673 name = CharField() # ...
674
675 # Some time later, we can initialize the database wrapper.
676 app = Flask(__name__)
677 app.config.update(DATABASE={'engine': 'peewee.SqliteDatabase',
678 'name': 'example.db'})
679 db.init_app(app)
680
681 # Alternately, we can specify the peewee database instance directly:
682 app = Flask(__name__)
683 sqlite_db = SqliteDatabase('example.db')
684 db.init_app(app, sqlite_db)
685
686 .. py:method:: init_app([app=None[, database=None]])
687
688 :param app: a ``Flask`` instance.
689 :param db: a peewee database instance or ``None``. If None then the
690 database will be configured via the ``app.config`` settings.
691
692 Initialize the Database wrapper with a Flask app you intend to use,
693 optionally specifying a Peewee database instance. If ``database`` is
694 None then the database will be loaded from ``app.config``.
695
696 .. py:attribute:: Model
697
698 Model subclass that works with the database specified by the app's config
699
700
701 REST API
702 --------
703
704 .. py:class:: RestAPI(app[, prefix='/api'[, default_auth=None[, name='api']]])
705
706 The :py:class:`RestAPI` acts as a container for the various :py:class:`RestResource`
707 objects. By default it binds all resources to ``/api/<model-name>/``. Much like
708 the :py:class:`Admin`, it is a centralized registry of resources.
709
710 Example of creating a ``RestAPI`` instance for a flask app:
711
712 .. code-block:: python
713
714 from flask_peewee.rest import RestAPI
715
716 from app import app # our project's Flask app
717
718 # instantiate our api wrapper
719 api = RestAPI(app)
720
721 # register a model with the API
722 api.register(SomeModel)
723
724 # configure URLs
725 api.setup()
726
727 .. note:: Like the flask admin, the ``RestAPI`` has a ``setup()`` method which
728 must be called after all resources have been registered.
729
730 :param app: flask application to bind API to
731 :param prefix: url to serve REST API from
732 :param default_auth: default :py:class:`Authentication` type to use with registered resources
733 :param name: the name for the API blueprint
734
735 .. py:method:: register(model[, provider=RestResource[, auth=None[, allowed_methods=None]]])
736
737 Register a model to expose via the API.
738
739 :param model: ``Model`` to expose via API
740 :param provider: subclass of :py:class:`RestResource` to use for this model
741 :param auth: authentication type to use for this resource, falling back to :py:attr:`RestAPI.default_auth`
742 :param allowed_methods: ``list`` of HTTP verbs to allow, defaults to ``['GET', 'POST', 'PUT', 'DELETE']``
743
744 .. py:method:: setup()
745
746 Register the API ``BluePrint`` and configure urls.
747
748 .. warning:: This must be called **after** registering your resources.
749
750
751 RESTful Resources and their subclasses
752 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
753
754 .. py:class:: RestResource(rest_api, model, authentication[, allowed_methods=None])
755
756 Class that determines how a peewee ``Model`` is exposed by the Rest API. Provides
757 a way of encapsulating model-specific configuration and behaviors. Provided
758 when registering a model with the :py:class:`RestAPI` instance (see :py:meth:`RestAPI.register`).
759
760 Should not be instantiated directly in most cases. Instead should be "registered" with
761 a ``RestAPI`` instance.
762
763 Example usage:
764
765 .. code-block:: python
766
767 # instantiate our api wrapper, passing in a reference to the Flask app
768 api = RestAPI(app)
769
770 # create a RestResource subclass
771 class UserResource(RestResource):
772 exclude = ('password', 'email',)
773
774 # assume we have a "User" model, register it with the custom resource
775 api.register(User, UserResource)
776
777 .. py:attribute:: paginate_by = 20
778
779 Determines how many results to return for a given API query.
780
781 .. note:: *Fewer* results can be requested by specifying a ``limit``,
782 but ``paginate_by`` is the upper bound.
783
784 .. py:attribute:: fields = None
785
786 A list or tuple of fields to expose when serializing
787
788 .. py:attribute:: exclude = None
789
790 A list or tuple of fields to **not** expose when serializing
791
792 .. py:attribute:: filter_exclude
793
794 A list of fields that **cannot** be used to filter API results
795
796 .. py:attribute:: filter_fields
797
798 A list of fields that can be used to filter the API results
799
800 .. py:attribute:: filter_recursive = True
801
802 Allow filtering on related resources
803
804 .. py:attribute:: include_resources
805
806 A mapping of field name to resource class for handling of foreign-keys.
807 When provided, foreign keys will be "nested".
808
809 .. code-block:: python
810
811 class UserResource(RestResource):
812 exclude = ('password', 'email')
813
814 class MessageResource(RestResource):
815 include_resources = {'user': UserResource} # 'user' is a foreign key field
816
817 .. code-block:: javascript
818
819 /* messages without "include_resources" */
820 {
821 "content": "flask and peewee, together at last!",
822 "pub_date": "2026-09-16 18:36:15",
823 "id": 1,
824 "user": 2
825 },
826
827 /* messages with "include_resources = {'user': UserResource} */
828 {
829 "content": "flask and peewee, together at last!",
830 "pub_date": "2026-09-16 18:36:15",
831 "id": 1,
832 "user": {
833 "username": "coleifer",
834 "active": true,
835 "join_date": "2026-09-16 18:35:56",
836 "admin": false,
837 "id": 2
838 }
839 }
840
841 .. py:attribute:: delete_recursive = True
842
843 Recursively delete dependencies
844
845 .. py:method:: get_query()
846
847 Returns the list of objects to be exposed by the API. Provides an easy
848 hook for restricting objects:
849
850 .. code-block:: python
851
852 class UserResource(RestResource):
853 def get_query(self):
854 # only return "active" users
855 return self.model.select().where(active=True)
856
857 :rtype: a ``SelectQuery`` containing the model instances to expose
858
859 .. py:method:: prepare_data(obj, data)
860
861 This method provides a hook for modifying outgoing data. The default
862 implementation no-ops, but you could do any kind of munging here. The
863 data returned by this method is passed to the serializer before being
864 returned as a json response.
865
866 :param obj: the object being serialized
867 :param data: the dictionary representation of a model returned by the ``Serializer``
868 :rtype: a dictionary of data to hand off
869
870 .. py:method:: save_object(instance, raw_data)
871
872 Persist the instance to the database. The raw data supplied by the request
873 is also available, but at the time this method is called the instance has
874 already been updated and populated with the incoming data.
875
876 :param instance: ``Model`` instance that has already been updated with the incoming ``raw_data``
877 :param raw_data: data provided in the request
878 :rtype: a saved instance
879
880 .. py:method:: api_list()
881
882 A view that dispatches based on the HTTP verb to either:
883
884 * GET: :py:meth:`~RestResource.object_list`
885 * POST: :py:meth:`~RestResource.create`
886
887 :rtype: ``Response``
888
889 .. py:method:: api_detail(pk)
890
891 A view that dispatches based on the HTTP verb to either:
892
893 * GET: :py:meth:`~RestResource.object_detail`
894 * PUT: :py:meth:`~RestResource.edit`
895 * DELETE: :py:meth:`~RestResource.delete`
896
897 :rtype: ``Response``
898
899 .. py:method:: object_list()
900
901 Returns a serialized list of ``Model`` instances. These objects may be
902 filtered, ordered, and/or paginated.
903
904 :rtype: ``Response``
905
906 .. py:method:: object_detail()
907
908 Returns a serialized ``Model`` instance.
909
910 :rtype: ``Response``
911
912 .. py:method:: create()
913
914 Creates a new ``Model`` instance based on the deserialized POST body.
915
916 :rtype: ``Response`` containing serialized new object
917
918 .. py:method:: edit()
919
920 Edits an existing ``Model`` instance, updating it with the deserialized PUT body.
921
922 :rtype: ``Response`` containing serialized edited object
923
924 .. py:method:: delete()
925
926 Deletes an existing ``Model`` instance from the database.
927
928 :rtype: ``Response`` indicating number of objects deleted, i.e. ``{'deleted': 1}``
929
930 .. py:method:: get_api_name()
931
932 :rtype: URL-friendly name to expose this resource as, defaults to the model's name
933
934 .. py:method:: check_get([obj=None])
935
936 A hook for pre-authorizing a GET request. By default returns ``True``.
937
938 :rtype: Boolean indicating whether to allow the request to continue
939
940 .. py:method:: check_post()
941
942 A hook for pre-authorizing a POST request. By default returns ``True``.
943
944 :rtype: Boolean indicating whether to allow the request to continue
945
946 .. py:method:: check_put(obj)
947
948 A hook for pre-authorizing a PUT request. By default returns ``True``.
949
950 :rtype: Boolean indicating whether to allow the request to continue
951
952 .. py:method:: check_delete(obj)
953
954 A hook for pre-authorizing a DELETE request. By default returns ``True``.
955
956 :rtype: Boolean indicating whether to allow the request to continue
957
958
959 .. py:class:: RestrictOwnerResource(RestResource)
960
961 This subclass of :py:class:`RestResource` allows only the "owner" of an object
962 to make changes via the API. It works by verifying that the authenticated user
963 matches the "owner" of the model instance, which is specified by setting :py:attr:`~RestrictOwnerResource.owner_field`.
964
965 Additionally, it sets the "owner" to the authenticated user whenever saving
966 or creating new instances.
967
968 .. py:attribute:: owner_field = 'user'
969
970 Field on the model to use to verify ownership of the given instance.
971
972 .. py:method:: validate_owner(user, obj)
973
974 :param user: an authenticated ``User`` instance
975 :param obj: the ``Model`` instance being accessed via the API
976 :rtype: Boolean indicating whether the user can modify the object
977
978 .. py:method:: set_owner(obj, user)
979
980 Mark the object as being owned by the provided user. The default implementation
981 simply calls ``setattr``.
982
983 :param obj: the ``Model`` instance being accessed via the API
984 :param user: an authenticated ``User`` instance
985
986
987 Authenticating requests to the API
988 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
989
990 .. py:class:: Authentication([protected_methods=None])
991
992 Not to be confused with the ``auth.Authentication`` class, this class provides
993 a single method, ``authorize``, which is used to determine whether to allow
994 a given request to the API.
995
996 :param protected_methods: A list or tuple of HTTP verbs to require auth for
997
998 .. py:method:: authorize()
999
1000 This single method is called per-API-request.
1001
1002 :rtype: Boolean indicating whether to allow the given request through or not
1003
1004
1005 .. py:class:: UserAuthentication(auth[, protected_methods=None])
1006
1007 Authenticates API requests by requiring the requesting user be a registered
1008 ``auth.User``. Credentials are supplied using HTTP basic auth.
1009
1010 Example usage:
1011
1012 .. code-block:: python
1013
1014 from auth import auth # import the Auth object used by our project
1015
1016 from flask_peewee.rest import RestAPI, RestResource, UserAuthentication
1017
1018 # create an instance of UserAuthentication
1019 user_auth = UserAuthentication(auth)
1020
1021 # instantiate our api wrapper, specifying user_auth as the default
1022 api = RestAPI(app, default_auth=user_auth)
1023
1024 # create a special resource for users that excludes email and password
1025 class UserResource(RestResource):
1026 exclude = ('password', 'email',)
1027
1028 # register our models so they are exposed via /api/<model>/
1029 api.register(User, UserResource) # specify the UserResource
1030
1031 # configure the urls
1032 api.setup()
1033
1034
1035 :param auth: an :ref:`authentication` instance
1036 :param protected_methods: A list or tuple of HTTP verbs to require auth for
1037
1038 .. py:method:: authorize()
1039
1040 Verifies, using HTTP Basic auth, that the username and password match a
1041 valid ``auth.User`` model before allowing the request to continue.
1042
1043 :rtype: Boolean indicating whether to allow the given request through or not
1044
1045
1046 .. py:class:: AdminAuthentication(auth[, protected_methods=None])
1047
1048 Subclass of the :py:class:`UserAuthentication` that further restricts which
1049 users are allowed through. The default implementation checks whether the
1050 requesting user is an "admin" by checking whether the admin attribute is set
1051 to ``True``.
1052
1053 Example usage:
1054
1055 .. code-block:: python
1056
1057 Authenticates API requests by requiring the requesting user be a registered
1058 ``auth.User``. Credentials are supplied using HTTP basic auth.
1059
1060 Example usage:
1061
1062 .. code-block:: python
1063
1064 from auth import auth # import the Auth object used by our project
1065
1066 from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, AdminAuthentication
1067
1068 # create an instance of UserAuthentication and AdminAuthentication
1069 user_auth = UserAuthentication(auth)
1070 admin_auth = AdminAuthentication(auth)
1071
1072 # instantiate our api wrapper, specifying user_auth as the default
1073 api = RestAPI(app, default_auth=user_auth)
1074
1075 # create a special resource for users that excludes email and password
1076 class UserResource(RestResource):
1077 exclude = ('password', 'email',)
1078
1079 # register our models so they are exposed via /api/<model>/
1080 api.register(SomeModel)
1081
1082 # specify the UserResource and require the requesting user be an admin
1083 api.register(User, UserResource, auth=admin_auth)
1084
1085 # configure the urls
1086 api.setup()
1087
1088 .. py:method:: verify_user(user)
1089
1090 Verifies whether the requesting user is an administrator
1091
1092 :param user: the ``auth.User`` instance of the requesting user
1093 :rtype: Boolean indicating whether the user is an administrator
1094
1095
1096 .. py:class:: APIKeyAuthentication(model, protected_methods=None)
1097
1098 Subclass that allows you to provide an API Key model to authenticate requests
1099 with.
1100
1101 .. note:: Must provide an API key model with at least the following two
1102 fields:
1103
1104 * key
1105 * secret
1106
1107
1108 .. code-block:: python
1109
1110 # example API key model
1111 class APIKey(db.Model):
1112 key = CharField()
1113 secret = CharField()
1114 user = ForeignKeyField(User)
1115
1116 # instantiating the auth
1117 api_key_auth = APIKeyAuthentication(model=APIKey)
1118
1119 :param model: a :py:class:`Database.Model` subclass to persist API keys.
1120 :param protected_methods: A list or tuple of HTTP verbs to require auth for
1121
1122
1123 Utilities
1124 ---------
1125
1126 .. py:function:: get_object_or_404(query_or_model, *query)
1127
1128 Provides a handy way of getting an object or 404ing if not found, useful
1129 for urls that match based on ID.
1130
1131 :param query_or_model: a query or model to filter using the given expressions
1132 :param query: a list of query expressions
1133
1134 .. code-block:: python
1135
1136 @app.route('/blog/<title>/')
1137 def blog_detail(title):
1138 blog = get_object_or_404(Blog.select().where(Blog.active==True), Blog.title==title)
1139 return render_template('blog/detail.html', blog=blog)
1140
1141 .. py:function:: object_list(template_name, qr[, var_name='object_list'[, **kwargs]])
1142
1143 Wraps the given query and handles pagination automatically. Pagination defaults to ``20``
1144 but can be changed by passing in ``paginate_by=XX``.
1145
1146 :param template_name: template to render
1147 :param qr: a select query
1148 :param var_name: the template variable name to use for the paginated query
1149 :param kwargs: arbitrary context to pass in to the template
1150
1151 .. code-block:: python
1152
1153 @app.route('/blog/')
1154 def blog_list():
1155 active = Blog.select().where(Blog.active==True)
1156 return object_list('blog/index.html', active)
1157
1158 .. code-block:: jinja
1159
1160 <!-- template -->
1161 {% for blog in object_list %}
1162 {# render the blog here #}
1163 {% endfor %}
1164
1165 {% if page > 1 %}
1166 <a href="./?page={{ page - 1 }}">Prev</a>
1167 {% endif %}
1168 {% if page < pagination.get_pages() %}
1169 <a href="./?page={{ page + 1 }}">Next</a>
1170 {% endif %}
1171
1172 .. py:function:: get_next()
1173
1174 :rtype: a URL suitable for redirecting to
1175
1176 .. py:function:: slugify(s)
1177
1178 Use a regular expression to make arbitrary string ``s`` URL-friendly
1179
1180 :param s: any string to be slugified
1181 :rtype: url-friendly version of string ``s``
1182
1183 .. py:class:: PaginatedQuery(query_or_model, paginate_by)
1184
1185 A wrapper around a query (or model class) that handles pagination.
1186
1187 .. py:attribute:: page_var = 'page'
1188
1189 The URL variable used to store the current page
1190
1191 Example:
1192
1193 .. code-block:: python
1194
1195 query = Blog.select().where(Blog.active==True)
1196 pq = PaginatedQuery(query)
1197
1198 # assume url was /?page=3
1199 obj_list = pq.get_list() # returns 3rd page of results
1200
1201 pq.get_page() # returns "3"
1202
1203 pq.get_pages() # returns total objects / objects-per-page
1204
1205 .. py:method:: get_list()
1206
1207 :rtype: a list of objects for the request page
1208
1209 .. py:method:: get_page()
1210
1211 :rtype: an integer representing the currently requested page
1212
1213 .. py:method:: get_pages()
1214
1215 :rtype: the number of pages in the entire result set