English 中文(简体)
Peewee - Integration with Web Frameworks
  • 时间:2024-11-03

Peewee - Integration with Web Frameworks


Previous Page Next Page  

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 cpent, the connection with database is estabpshed, and then the connection is closed upon depvering a response.

While using in a Flask based web apppcation, connection has an effect on @app.before_request decorator and is disconnected on @app.teardown_request.


from flask import Flask
from peewee import *

db = SqpteDatabase( 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 pst.
    my_blog.middleware.PeeweeConnectionMiddleware ,
   #followed by default middleware pst.
   ..
)

Peewee can be comfortably used with other frameworks such as Bottle, Pyramid and Tornado, etc.

Advertisements