将sqlalchemy与cherrypy结合使用
cp_sqlalchem的Python项目详细描述
cherrypy sqlalchemy使在cherrypy中使用sqlalchemy变得很容易 应用程序。
学分
这个包主要是从Sylvain’s SQLAlchemy recipe创建的。
基本用法
cherrypy sqlalchemy有两个元素
- A CherryPy tool that will create a session for use with each request.
- A CherryPy plugin that can maintains information about the database and binds the session to the specific DB.
下面是一个连接到sqlite数据库的示例:
import cherrypy from app import Root from app.models import ORMBase from cp_sqlalchemy import SQLAlchemyTool, SQLAlchemyPlugin def run(): cherrypy.tools.db = SQLAlchemyTool() cherrypy.tree.mount(Root(), '/', { '/': { 'tools.db.on': True } }) SQLAlchemyPlugin( cherrypy.engine, ORMBase, 'sqlite:////path/to/file.db' ) cherrypy.engine.start() cherrypy.engine.block()
值得注意的一点是我们进口的奥姆巴是 sqlalchemy.ext.declarative.declarative_base()用于 创建模型。
从那里,每个请求都可以访问cherrypy.request.db, 这是一个sqlalchemy会话的实例。
在源代码中有一个更完整的example.py。
- 免费软件:BSD许可证
- 文档:https://cp_sqlalchemy.readthedocs.org。