Peewee – Integration with Web Frameworks
”;
Peewee can work seamlessly with most of the Python web framework APIs. Whenever the Web Server Gateway Interface (WSGI) server receives a connection request from client, the connection with database is established, and then the connection is closed upon delivering a response.
While using in a Flask based web application, connection has an effect on @app.before_request decorator and is disconnected on @app.teardown_request.
from flask import Flask from peewee import * db = SqliteDatabase(''mydatabase.db'') app = Flask(__name__) @app.before_request def _db_connect(): db.connect() @app.teardown_request def _db_close(exc): if not db.is_closed(): db.close()
Peewee API can also be used in Django. To do so, add a middleware in Django app.
def PeeweeConnectionMiddleware(get_response): def middleware(request): db.connect() try: response = get_response(request) finally: if not db.is_closed(): db.close() return response return middleware
Middleware is added in Django’s settings module.
# settings.py MIDDLEWARE_CLASSES = ( # Our custom middleware appears first in the list. ''my_blog.middleware.PeeweeConnectionMiddleware'', #followed by default middleware list. .. )
Peewee can be comfortably used with other frameworks such as Bottle, Pyramid and Tornado, etc.
Advertisements
”;