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