Sometimes my Flask application hangs on the following line:

with shelve.open('user_db') as db: 

(this happens by chance) I can’t give all the application code (very large), but in general it looks like this:

 @app.route('/', methods=['POST']) def mpage(): Обработка запроса Запуск следующего метода (set_timer) в потоке Возвращение кода 200 def set_timer(): Запускается таймер, запускается отдельный процесс (см следующий метод) и проверяется время выполнения этого процесса def seps(): Тут почти в самом начале лежит проблемная строка 

The application hangs exactly on this line, I found it through debugging messages. Can anyone tell me what the problem is?

UPD: replaced shelve with sqlite3. I open it to a global variable like this:

 conn = sqlite3.connect('user_db.db', check_same_thread=False) 

Hangs here:

 db = conn.cursor() user_mode = db.execute('SELECT id, mode FROM users WHERE id={}'.format(user_id)).fetchall() 

I can not understand what the problem is now

upd2: Fully switched to flask_sqlalchemy. The error did not disappear. Code: Base Model:

 from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./user.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) mode = db.Column(db.Integer, primary_key=False) 

How to use:

 report += 'Открытие БД\n' t_user = User.query.get(user_id) if not t_user: user = User(id=user_id, mode=0) db.session.add(user) db.session.commit() t_user = User.query.get(user_id) user_mode = t_user.mode 

And somewhere in these lines hangs. I do not know what to do

  • Shtktrays even led .. - Xyanight
  • @Xyanight I can’t give you a stable, since all this happens in a multi-threaded / processor application. And so, there is no error. The code just hangs there, and then it is all cut down in the set_timer () method - vladF
  • four
    shelve does not support concurrent access. Try to synchronize access or use solutions that support parallel access. What decision to choose depends on what role your shelve performs. - jfs
  • @jfs In the shelve, I have a user type database: a digit (mode number). What solution should I use here? - vladF 2:41 pm
  • @vladF if there are no special preferences, then any database will do. Book Search Example - jfs

2 answers 2

Just breaks the connection to the database. Add such lines to your config and there will be happiness:

 app.config['SQLALCHEMY_POOL_RECYCLE'] = 299 app.config['SQLALCHEMY_POOL_TIMEOUT'] = 20 
  • Does not work. The code is added to the main application file, but it still hangs on this point - vladF
  • @vladF try using debug import pdb and in the right place pdb.set_trace() - dluhhbiu

Perhaps my advice would be useful - try Postgresql Here is a sample code:

 # -*- coding: utf-8 -*- from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session from contextlib import contextmanager Base = declarative_base() engine = create_engine('postgresql://user:pass@localhost:5432/db_name', pool_size=50, max_overflow=0, echo=True) @contextmanager def session(): connection = engine.connect() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine)) try: yield db_session except Exception as e: print(e) finally: db_session.remove() connection.close() class User(Base): __tablename__ = 'sign' id = Column(Integer, primary_key=True) name = Column(String(50)) def __init__(self, name): self.name = name def new_user(name): with session() as s: user = User(name) s.add(user) s.commit() return s.id 
  • I solved my problem by switching to this DB, but I managed to do it only with a crutch - I just checked if the code hangs in this place or not - vladF