# API

## Admin

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 `Auth` instance when being instantiated, which in turn requires a Flask app and a py:class:Database wrapper.

  Here is an example of how you might instantiate an Admin object:

      from flask import Flask

      from flask_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 – `Auth` instance which will provide authentication

    - blueprint_factory – an object that will create the `BluePrint` used by the admin

    - prefix – url to bind admin to, defaults to `/admin`

  register(model[, admin_class=ModelAdmin])

    Register a model to expose in the admin area. A `ModelAdmin` subclass can be provided along with the model, allowing for customization of the model’s display and behavior.

    Example usage:

        # will use the default ModelAdmin subclass to display model
        admin.register(BlogModel)

        class EntryAdmin(ModelAdmin):
            columns = ('title', 'blog', 'pub_date',)

        admin.register(EntryModel, EntryAdmin)

    Warning

    All models must be registered before calling `setup()`

    Parameters:

      - model – peewee model to expose via the admin

      - admin_class – `ModelAdmin` or subclass to use with given model

  register_panel(title, panel)

    Register a `AdminPanel` subclass for display in the admin dashboard.

    Example usage:

        class HelloWorldPanel(AdminPanel):
            template_name = 'admin/panels/hello.html'

            def get_context(self):
                return {
                    'message': 'Hello world',
                }

        admin.register_panel('Hello world', HelloWorldPanel)

    Warning

    All panels must be registered before calling `setup()`

    Parameters:

      - title – identifier for panel, example might be “Site Stats”

      - panel – subclass of `AdminPanel` to 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 `example/main.py` in the example application supplied with flask-peewee.

        # register all models, etc
        admin.register(...)

        # finish up initialization of the admin object
        admin.setup()

        if __name__ == '__main__':
            # run the WSGI application
            app.run()

    Note

    call `setup()` after registering your models and panels

  check_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:

        def check_user_permission(self, user):
            return user.admin

    Parameters:

      user – the currently logged-in user, exposed by the `Auth` instance

    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 returns `True` is 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 `Model` is exposed in the admin area. Provides a way of encapsulating model-specific configuration and behaviors. Provided when registering a model with the `Admin` instance (see `Admin.register()`).

  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.

        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

  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

  paginate_by = 20

    Number of records to display on index pages

  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

  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 `Auth` instance to determine the currently-logged-in user.

    Here’s an example showing how the query is restricted based on whether the given user is a “super user” or not:

        class UserAdmin(ModelAdmin):
            def get_query():
                # ask the auth system for the currently logged-in user
                current_user = self.auth.get_logged_in_user()

                # if they are not a superuser, only show them their own
                # account in the admin
                if not current_user.is_superuser:
                    return User.select().where(User.id==current_user.id)

                # otherwise, show them all users
                return User.select()

    Return type:

      A `SelectQuery` that represents the list of objects to expose

  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 `DoesNotExist` in 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 simply calls `get_form()`.

  get_edit_form()

    Allows you to specify a different form when editing existing instances versus adding new instances. The default implementation simply 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 an example from the default `auth.User` `ModelAdmin`, in which the password is displayed as a sha1, but if the user is adding or edits the existing password, it re-hashes:

        def save_model(self, instance, form, adding=False):
            orig_password = instance.password

            user = super(UserAdmin, self).save_model(instance, form, adding)

            if orig_password != form.password.data:
                user.set_password(form.password.data)
                user.save()

            return user

    Parameters:

      - 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

  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

        class UserModelAdmin(ModelAdmin):
            def get_template_overrides(self):
                return {'index': 'users/admin/index_override.html'}

  get_urls()

    Useful as a hook for extending `ModelAdmin` functionality with additional urls.

    Note

    It is not necessary to decorate the views specified by this method since the `Admin` instance will handle this during registration and setup.

    Return type:

      tuple of 2-tuples consisting of a mapping between url and view

  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 `Form` instance containing fields for filtering

    - filtered 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

### 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.

  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.

  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 `AdminPanel` functionality with custom urls and views.

    Note

    It is not necessary to decorate the views specified by this method since the `Admin` instance will handle this during registration and setup.

    Return type:

      Returns a tuple of 2-tuples mapping url to view

  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 simply 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.

## Auth

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 `Admin` and can also be integrated with the `RestAPI`.

  Here is an example of how to use the Auth framework:

      from flask import Flask

      from flask_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 `Admin` or the `RestAPI`, there is no explicit `setup()` method call when using the Auth system. Creation of the auth blueprint and registration with the Flask app happen automatically during instantiation.

  Note

  A context processor is automatically registered that provides the currently logged-in user across all templates, available as “user”. If no user is logged in, the value of this will be `None`.

  Note

  A pre-request handler is automatically registered which attempts to retrieve the current logged-in user and store it on the global flask variable `g`.

  Parameters:

    - app – flask application to bind admin to

    - db – `Database` database wrapper for flask app

    - user_model – `User` model to use

    - prefix – url to bind authentication views to, defaults to /accounts/

    - db_table – Create db table using db_table name. `user` is reserved keyword in postgres.

  default_next_url = 'homepage'

    The url to redirect to upon successful login in the event a `?next=<xxx>` is not provided.

  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`, or `None` if 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 `ModelAdmin` class suitable for use with the User model. Specifically addresses the need to re-hash passwords when changing them via the admin.

    The default implementation includes an override of the `ModelAdmin.save_model()` method to intelligently hash passwords:

        class UserAdmin(model_admin):
            columns = ['username', 'email', 'active', 'admin']

            def save_model(self, instance, form, adding=False):
                orig_password = instance.password

                user = super(UserAdmin, self).save_model(instance, form, adding)

                if orig_password != form.password.data:
                    user.set_password(form.password.data)
                    user.save()

                return user

    Parameters:

      model_admin – subclass of `ModelAdmin` to use as the base class

    Return type:

      a subclass of `ModelAdmin` suitable for use with the `User` model

  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:

        def get_urls(self):
            return (
                ('/logout/', self.logout),
                ('/login/', self.login),
            )

    Return type:

      a tuple of 2-tuples mapping url to view function.

  get_login_form()
    Return type:

      a `wtforms.Form` subclass to use for retrieving any user info required for login

  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.

    Return type:

      `User` model if successful, otherwise `False`

  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.

    Parameters:

      user – `User` instance

  logout_user(user)

    Mark the requesting user as logged-out

    Parameters:

      user – `User` instance

### The BaseUser mixin

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.

  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 `Model` subclass which is configured to work with the database specified by the application’s config.

  Parameters:

    - app – a `Flask` instance or `None` (for deferred initialization).

    - 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:

      DATABASE = {
          'name': 'example.db',
          'engine': 'peewee.SqliteDatabase',
      }

  Here is an example of how you might use the database wrapper:

      # instantiate the db wrapper
      db = Database(app)

      # start creating models
      class Blog(db.Model):
          # this model will automatically work with the database specified
          # in the application's config.

  Here is how to defer initialization via `init_app`:

      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)

  init_app([app=None[, database=None]])
    Parameters:

      - app – a `Flask` instance.

      - 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`.

  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 `RestAPI` acts as a container for the various `RestResource` objects. By default it binds all resources to `/api/<model-name>/`. Much like the `Admin`, it is a centralized registry of resources.

  Example of creating a `RestAPI` instance for a flask app:

      from flask_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.

  Parameters:

    - app – flask application to bind API to

    - prefix – url to serve REST API from

    - default_auth – default `Authentication` type to use with registered resources

    - name – 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 – `Model` to expose via API

      - provider – subclass of `RestResource` to use for this model

      - auth – authentication type to use for this resource, falling back to `RestAPI.default_auth`

      - allowed_methods – `list` of HTTP verbs to allow, defaults to `['GET', 'POST', 'PUT', 'DELETE']`

  setup()

    Register the API `BluePrint` and 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 `Model` is exposed by the Rest API. Provides a way of encapsulating model-specific configuration and behaviors. Provided when registering a model with the `RestAPI` instance (see `RestAPI.register()`).

  Should not be instantiated directly in most cases. Instead should be “registered” with a `RestAPI` instance.

  Example usage:

      # instantiate our api wrapper, passing in a reference to the Flask app
      api = RestAPI(app)

      # create a RestResource subclass
      class UserResource(RestResource):
          exclude = ('password', 'email',)

      # assume we have a "User" model, register it with the custom resource
      api.register(User, UserResource)

  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.

  fields = None

    A list or tuple of fields to expose when serializing

  exclude = None

    A list or tuple of fields to not expose when serializing

  filter_exclude

    A list of fields that cannot be used to filter API results

  filter_fields

    A list of fields that can be used to filter the API results

  filter_recursive = True

    Allow filtering on related resources

  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": "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
          }
        }

  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(active=True)

    Return type:

      a `SelectQuery` containing 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 – `Model` instance that has already been updated with the incoming `raw_data`

      - raw_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: `edit()`

    - DELETE: `delete()`

    Return type:

      `Response`

  object_list()

    Returns a serialized list of `Model` instances. These objects may be filtered, ordered, and/or paginated.

    Return type:

      `Response`

  object_detail()

    Returns a serialized `Model` instance.

    Return type:

      `Response`

  create()

    Creates a new `Model` instance based on the deserialized POST body.

    Return type:

      `Response` containing serialized new object

  edit()

    Edits an existing `Model` instance, updating it with the deserialized PUT body.

    Return type:

      `Response` containing serialized edited object

  delete()

    Deletes an existing `Model` instance from the database.

    Return type:

      `Response` indicating 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

  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()

    A hook for pre-authorizing a POST request. By default returns `True`.

    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_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 `RestResource` allows only the “owner” of an object to make changes via the API. It works by verifying that the authenticated user matches the “owner” of the model instance, which is specified by setting `owner_field`.

  Additionally, it sets the “owner” to the authenticated user whenever saving or creating new instances.

  owner_field = 'user'

    Field on the model to use to verify ownership of the given instance.

  validate_owner(user, obj)
    Parameters:

      - user – an authenticated `User` instance

      - obj – the `Model` instance 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 simply calls `setattr`.

    Parameters:

      - obj – the `Model` instance being accessed via the API

      - user – an authenticated `User` instance

### Authenticating requests to the API

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.

  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.User` model 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 `UserAuthentication` that further restricts which users are allowed through. The default implementation checks whether the requesting user is an “admin” by checking whether the admin attribute is set to `True`.

  Example usage:

  Authenticates API requests by requiring the requesting user be a registered `auth.User`. Credentials are supplied using HTTP basic auth.

  Example usage:

      from auth import auth # import the Auth object used by our project

      from flask_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.User` instance 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.Model` subclass to persist API keys.

    - protected_methods – A list or tuple of HTTP verbs to require auth for

## 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 `20` but can be changed by passing in `paginate_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 `s` URL-friendly

  Parameters:

    s – any string to be slugified

  Return type:

    url-friendly version of string `s`

class PaginatedQuery(query_or_model, paginate_by)

  A wrapper around a query (or model class) that handles pagination.

  page_var = 'page'

    The URL variable used to store the current page

  Example:

      query = Blog.select().where(Blog.active==True)
      pq = PaginatedQuery(query)

      # assume url was /?page=3
      obj_list = pq.get_list()  # returns 3rd page of results

      pq.get_page() # returns "3"

      pq.get_pages() # returns total objects / objects-per-page

  get_list()
    Return type:

      a list of objects for the request page

  get_page()
    Return type:

      an integer representing the currently requested page

  get_pages()
    Return type:

      the number of pages in the entire result set