本文介绍了SQLAlchemy和Falcon-会话初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering where the best place would be to create a scoped session for use in falcon.

通过阅读flask-sqlalchemy代码,它以某种方式进行了如下操作:

From reading the flask-sqlalchemy code, it, in a round about way, does something like this:

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()

这对猎鹰有用吗? get_ident func在使用Gunicorn时会做正确的事"吗?

Would this work for falcon? Will the get_ident func "do the right thing" when using gunicorn?

推荐答案

您可以使用中间件

示例.

  1. 创建引擎,session_factory和scoped_session对象.

  1. Create engine, session_factory and scoped_session object.

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)

  • 创建中间件.

  • Create middleware.

    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()
    

  • 注册中间件.

  • Register middleware.

    import falcon
    
    
    app = falcon.API(middleware=[
        SQLAlchemySessionManager(Session),
    ])
    

  • 在每个请求中都可以访问会话.

  • Session is accessible in every request.

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

  • 这篇关于SQLAlchemy和Falcon-会话初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-22 07:59