Peewee 简明教程

Peewee - Integration with Web Frameworks

Peewee 可以与大多数 Python Web 框架 API 无缝协作。每当 Web 服务器网关接口 (WSGI) 服务器从客户端接收连接请求时,就会建立与数据库的连接,然后在响应传递之后关闭连接。

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.

在基于 Flask 的 Web 应用程序中使用时,连接会对 @app.before_request 修饰符产生影响,并在 @app.teardown_request 上断开。

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 也可以在 Django. 中使用。为此,请在 Django 应用中添加一个中间件。

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

中间件添加到 Django 的设置模块中。

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 可以轻松地与 Bottle、Pyramid 和 Tornado 等其他框架一起使用。

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