Download Flask-Peewee REST API Documentation: Creating an Authentication System and more Schemes and Mind Maps Network Programming in PDF only on Docsity!
flask-peewee Documentation
Release 0.6.
charles leifer
Apr 16, 2022
- 1 Installing
- 2 Getting Started
- 2.1 Creating a flask app
- 2.2 Creating a simple model
- 2.3 Setting up a simple base template
- 2.4 Adding users to the site
- 2.5 Managing content using the admin area
- 2.6 Exposing content using a REST API
- 3 Database Wrapper
- 4 Admin Interface
- 4.1 Getting started
- 4.2 Customizing how models are displayed
- 4.3 Nicer display for Foreign Key fields
- 4.4 Creating admin panels
- 4.5 Handling File Uploads
- 5 Authentication
- 5.1 Getting started
- 5.2 Marking areas of the site as login required
- 5.3 Retrieving the current user
- 5.4 Accessing the user in the templates
- 5.5 Using a custom “User” model
- 6 REST Api
- 6.1 Getting started with the API
- 6.2 Creating a RestAPI
- 6.3 Customizing what is returned
- 6.4 Allowing users to post objects
- 6.5 Restricting API access on a per-model basis
- 6.6 Locking down a resource
- 6.7 Filtering records and querying
- 6.8 Sorting results
- 6.9 Limiting results and pagination
- 7 Utilities
- 7.1 Getting objects
- 7.2 Misc
- 8 Using gevent
- 8.1 Database configuration
- 8.2 Monkey-patch the thread module
- 8.3 Rationale
- 9 API
- 9.1 Admin
- 9.2 Auth
- 9.3 Database
- 9.4 REST API
- 9.5 Utilities
- 10 Indices and tables
- Index
flask-peewee Documentation, Release 0.6.
Warning: I’m sorry to announce that flask-peewee will now be in maintenance-only mode. This decision is
motivated by a number of factors:
- Flask-Admin provides a superior admin interface and has support for peewee models.
- Flask-Security and Flask-Login both provide authentication functionality, and work well with Peewee.
- Most importantly, though, I do not find myself wanting to work on flask-peewee.
I plan on rewriting the Database and REST API portions of flask-peewee and repackaging them as a new
library, but flask-peewee as it stands currently will be in maintenance-only mode.
Welcome to the flask-peewee documentation!
provides a layer of integration between the flask web framework and the peewee orm.
Contents:
Contents 1
CHAPTER 1
Installing
flask-peewee can be installed very easily using pip.
pip install flask-peewee
If you do not have the dependencies installed already, pip will install them for you, but for reference they are:
- flask
- peewee
- wtforms
- wtf-peewee
- python 2.5 or greater
1.1 Using git
If you want to run the very latest, feel free to pull down the repo from github and install by hand.
git clone https://github.com/coleifer/flask-peewee.git cd flask-peewee python setup.py install
You can run the tests using the test-runner:
python setup.py test
flask-peewee Documentation, Release 0.6.
4 Chapter 1. Installing
flask-peewee Documentation, Release 0.6.
2.2 Creating a simple model
Let’s add a simple model. Before we can do that, though, it is necessary to initialize the peewee database wrapper and
configure the database:
from flask import Flask
flask-peewee bindings
from flask_peewee.db import Database
configure our database
DATABASE = { 'name': 'example.db', 'engine': 'peewee.SqliteDatabase', } DEBUG = True SECRET_KEY = 'ssshhhh'
app = Flask(name) app.config.from_object(name)
instantiate the db wrapper
db = Database(app)
if name == 'main': app.run()
What this does is provides us with request handlers which connect to the database on each request and close it when
the request is finished. It also provides a base model class which is configured to work with the database specified in
the configuration.
Now we can create a model:
import datetime from peewee import (^) *
class Note (db.Model): message = TextField() created = DateTimeField(default=datetime.datetime.now)
Note: The model we created, Note, subclasses db.Model, which in turn is a subclass of peewee.Model that is
pre-configured to talk to our database.
2.3 Setting up a simple base template
We’ll need a simple template to serve as the base template for our app, so create a folder named templates. In the
templates folder create a file base.html and add the following:
< html > < title >Test site < body > (continues on next page)
6 Chapter 2. Getting Started
flask-peewee Documentation, Release 0.6.
(continued from previous page) < h2 >{% block content_title %}{% endblock %} {% block content %}{% endblock %}
2.4 Adding users to the site
Before we can edit these Note models in the admin, we’ll need to have some way of authenticating users on the site.
This is where Auth comes in. Auth provides a User model and views for logging in and logging out, among other
things, and is required by the Admin.
from flask_peewee.auth import Auth
create an Auth object for use with our flask app and database wrapper
auth = Auth(app, db)
Let’s also modify the code that runs our app to ensure our tables get created if need be:
if name == 'main': auth.User.create_table(fail_silently= True ) Note.create_table(fail_silently= True )
app.run()
After cleaning up the imports and declarations, we have something like the following:
import datetime from flask import Flask from flask_peewee.auth import Auth from flask_peewee.db import Database from peewee import (^) *
configure our database
DATABASE = { 'name': 'example.db', 'engine': 'peewee.SqliteDatabase', } DEBUG = True SECRET_KEY = 'ssshhhh'
app = Flask(name) app.config.from_object(name)
instantiate the db wrapper
db = Database(app)
class Note (db.Model): message = TextField() created = DateTimeField(default=datetime.datetime.now)
create an Auth object for use with our flask app and database wrapper
auth = Auth(app, db) (continues on next page)
2.4. Adding users to the site 7
flask-peewee Documentation, Release 0.6.
This is pretty lousy so let’s clean it up to display the message and when it was published. We can do that by customizing
the columns displayed. Edit the app with the following changes:
from flask_peewee.admin import Admin, ModelAdmin
class NoteAdmin (ModelAdmin): columns = ('message', 'created',)
admin = Admin(app, auth)
admin.register(Note, NoteAdmin)
admin.setup()
Now our modeladmin should look more like this:
Let’s go ahead and add the auth.User model to the admin as well:
2.5. Managing content using the admin area 9
flask-peewee Documentation, Release 0.6.
admin.register(Note, NoteAdmin) auth.register_admin(admin)
admin.setup()
2.6 Exposing content using a REST API
Adding a REST API is very similar to how we added the Admin interface. We will create a RestAPI object, and
then register our project’s models with it. If we want to customize things, we can subclass RestResource.
The first step, then, is to create the RestAPI object:
from flask_peewee.rest import RestAPI
create a RestAPI container
api = RestAPI(app)
api.setup()
This doesn’t do anything yet, we need to register models with it first. Let’s register the Note model from earlier:
create a RestAPI container
api = RestAPI(app)
register the Note model
api.register(Note)
api.setup()
Assuming your project is still running, try executing the following command (or just browse to the url listed):
$ curl http://127.0.0.1:5000/api/note/
You should see something like the following:
"meta": { "model": "note", "next": "", "page": 1, "previous": "" }, "objects": [ { "message": "blah blah blah this is a note", "id": 1, "created": "2011-09-23 09:07:39" }, { "message": "this is another note!", "id": 2, "created": "2011-09-23 09:07:54" } ] }
10 Chapter 2. Getting Started
flask-peewee Documentation, Release 0.6.
12 Chapter 2. Getting Started
CHAPTER 3
Database Wrapper
The Peewee database wrapper provides a thin layer of integration between flask apps and the peewee orm.
The database wrapper is important because it ensures that a database connection is created for every incoming request,
and closed upon request completion. It also provides a subclass of Model which works with the database specified in
your app’s configuration.
Most features of flask-peewee require a database wrapper, so you very likely always create one.
The database wrapper reads its configuration from the Flask application. The configuration requires only two argu-
ments, but any additional arguments will be passed to the database driver when connecting:
name The name of the database to connect to (or filename if using sqlite3)
engine The database driver to use, must be a subclass of peewee.Database.
from flask import Flask from peewee import (^) *
from flask_peewee.db import Database
DATABASE = { 'name': 'example.db', 'engine': 'peewee.SqliteDatabase', }
app = Flask(name) app.config.from_object(name) # load database configuration from this module
instantiate the db wrapper
db = Database(app)
start creating models
class Blog (db.Model): name = CharField()
.. etc
CHAPTER 4
Admin Interface
Many web applications ship with an “admin area”, where priveleged users can view and modify content. By intro-
specting your application’s models, flask-peewee can provide you with straightforward, easily-extensible forms for
managing your application content.
Here’s a screen-shot of the admin dashboard:
4.1 Getting started
To get started with the admin, there are just a couple steps:
flask-peewee Documentation, Release 0.6.
1. Instantiate an Auth backend for your project – this component is responsible for providing the security for the
admin area
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)
2. Instantiate an Admin object
continued from above...
from flask_peewee.admin import Admin
admin = Admin(app, auth)
3. Register any ModelAdmin or AdminPanel objects you would like to expose via the admin
continuing... assuming "Blog" and "Entry" models
admin.register(Blog) # register "Blog" with vanilla ModelAdmin admin.register(Entry, EntryAdmin) # register "Entry" with a custom ˓→ModelAdmin subclass
assume we have an "AdminPanel" called "NotePanel"
admin.register_panel('Notes', NotePanel)
4. Call Admin.setup(), which registers the admin blueprint and configures the urls
after all models and panels are registered, configure the urls
admin.setup()
Note: For a complete example, check the example which ships with the project.
4.2 Customizing how models are displayed
We’ll use the “Message” model taken from the example app, which looks like this:
class Message (db.Model): user = ForeignKeyField(User) content = TextField() pub_date = DateTimeField(default=datetime.datetime.now)
def unicode(self): return '%s: %s' % (self.user, self.content)
If we were to simply register this model with the admin, it would look something like this:
16 Chapter 4. Admin Interface