python - 将 SQLAlchemy 会话与 HTTPServer 一起使用。线程错误
问题描述
我在使用 SQLAlchemy 会话在不同线程上生成 HTTP 服务器时遇到问题(我在另一个线程上生成 HTTP 服务器的原因是因为否则测试会永远挂起)。发生的事情是我在每个请求中都传递了数据库配置。但它不允许我在使用 SQLite 的测试服务器上创建会话(开发服务器是 PostgreSQL)。每次它进入视图时都会引发以下错误:
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 5784 and this is thread id 8560
这是我的测试用例:
class ViewsTestSuite(unittest.TestCase):
def setUp(self):
app = App(8000, testing=True)
try:
httpd_thread = threading.Thread(target=app.run)
httpd_thread.daemon = True
httpd_thread.start()
except KeyboardInterrupt:
pass
我的应用程序设置类:
class App:
def __init__(self, port, testing=False):
self.port = port
self.testing = testing
self.server = None
self.config = None
self.db = None
def run(self):
if self.testing:
self.config = TestingConfig
else:
self.config = DevelopmentConfig
self.init_db()
RequestHandler.config = self.config
self.server = HTTPServer(('localhost', self.port), RequestHandler)
try:
self.server.serve_forever()
except KeyboardInterrupt:
pass
self.server.server_close()
def stop(self):
self.server.server_close()
def init_db(self):
self.db = Database(self.config.DATABASE_URL)
self.db.create_session()
self.db.create_database()
和我正在测试的视图:
def get_recipes(handler):
json_structure = []
db = get_db(handler.config.DATABASE_URL)
db.create_session()
recipes = db.session.query(Recipe, func.coalesce(func.avg(Rating.rating).label('average'), 0)).\
outerjoin(Rating).group_by(Recipe.id).all()
for recipe in recipes:
json_structure.append({
"id": recipe[0].id,
"name": recipe[0].name,
"prep_time": recipe[0].prep_time,
"vegeterian": recipe[0].vegeterian,
"rating": float(recipe[1])
})
return 200, json.dumps(json_structure)
任何帮助都会非常棒!非常感谢
解决方案
推荐阅读
- ios - 在 Tableview 标题中找到 UIButton 并更改按钮标题
- php - 当我单击添加到购物车按钮时会发生什么我在 laravel 中遇到了一些错误?
- arrays - 如何手动增加红宝石?
- laravel - Composer 未安装软件包
- javascript - JSDoc中对象中任意键的值的文档结构
- google-sheets - 确定任何 Y 单元格中的 X 是否具有特定值的公式(Google 电子表格)
- markdown - 打印 mkdocs 生成的 html 页面会暴露链接
- image - 图像后处理失败。如果是照片或大图,请将其缩小到 2500 像素并重新上传
- php - PHP:致命错误:未捕获的错误:在布尔值上调用成员函数 execute()
- python - 我可以在没有 Restful Api 的情况下使用 Elasticsearch