У меня проблема с использованием сеанса SQLAlchemy с порождением HTTP-сервера в другом потоке (причина, по которой я порождаю HTTP-сервер в другом потоке, заключается в том, что в противном случае тест просто зависает навсегда).Происходит то, что я передаю конфигурацию БД в каждом запросе.Но это не позволяет мне создавать сеанс на тестовом сервере, который использует SQLite (dev-сервером является 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)
Любая помощь была бы действительно потрясающей!Большое спасибо