我想使用 python-socketio 并且我想从 socketio 方法查询我的数据库。我的数据库设置保存在金字塔请求中。但我不明白如何在没有 http-requests 的情况下获取这些设置。
@sio.event
def connect(sid, environ):
print('connect ', sid)
@sio.event
def message(sid, data):
# I want to query my database at this location
sio.send(data)
print('Server send', data)
@sio.event
def disconnect(sid):
print('disconnect ', sid)
我正在考虑使用' pyramid.threadlocal.get_current_request '但这个方法返回无。
我通过此代码将数据库设置添加到金字塔请求中。
__init__.py
def db(request):
session = session_maker(request)
return session
...
config.add_request_method(db, reify=True)
session_maker
def session_returner(request, connect_line):
engine = create_engine(connect_line, echo=debug)
Base.metadata.bind = engine
Session = orm.sessionmaker(bind=engine)
session = Session()
def cleanup(request):
if request.exception is not None:
session.rollback()
session.close()
request.add_finished_callback(cleanup)
return session
def session_maker(request, settings=None):
if settings is None:
settings = get_settings(request)
connect_line = 'postgresql://{user}:{password}@{postgre_server}:{bd_port}/{bd_name}'.format(user=settings['bd_user'], postgre_server=settings['postgre_server'], bd_port=settings['bd_port'], password=settings['bd_password'], bd_name=settings['bd_name'])
return session_returner(request, connect_line)