繁体   English   中英

SQLAlchemy 和 Falcon - 会话初始化

[英]SQLAlchemy and Falcon - session initialization

我想知道最好的地方是创建一个在 falcon 中使用的范围会话。

通过阅读flask-sqlalchemy 代码,它以一种迂回的方式执行以下操作:

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

try:
    from greenlet import get_current as get_ident
except ImportError:
    try:
        from thread import get_ident
    except ImportError:
        from _thread import get_ident

connection_uri = 'postgresql://postgres:@localhost:5432/db'
engine = create_engine(connection_uri)
session_factory = sessionmaker(bind=engine)
session_cls = scoped_session(session_factory, scopefunc=get_ident)
session = session_cls()

这对猎鹰有用吗? 使用 gunicorn 时get_ident func 会“做正确的事”吗?

您可以使用中间件

例子。

  1. 创建引擎、 session_factory 和 scoped_session 对象。

     from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker import settings engine = create_engine( '{engine}://{username}:{password}@{host}:{port}/{db_name}'.format( **settings.POSTGRESQL ) ) session_factory = sessionmaker(bind=engine) Session = scoped_session(session_factory)
  2. 创建中间件。

     class SQLAlchemySessionManager: """ Create a scoped session for every request and close it when the request ends. """ def __init__(self, Session): self.Session = Session def process_resource(self, req, resp, resource, params): resource.session = self.Session() def process_response(self, req, resp, resource, req_succeeded): if hasattr(resource, 'session'): Session.remove()
  3. 注册中间件。

     import falcon app = falcon.API(middleware=[ SQLAlchemySessionManager(Session), ])
  4. 每个请求都可以访问会话。

     import falcon class MyAPI: def on_get(self, req, resp): # You can access self.session here # self.session.add(foo) # self.session.commit()

pypi 上有一个包falcon-sqla ,它提供了一个中间件来管理与 Falcon 的 SQLAlchemy 会话。

它使用请求上下文对象为每个 http 请求添加不同的会话,从而避免使用作用域会话。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM