SQLAlchemy和mysql在并发请求上抛出错误

2024-09-28 13:37:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一份申请,每当我一次做一个请求,一切都很好。但是,当我的vuejs前端同时使用2个请求调用flask后端时,我会遇到一个大错误,请参见下文。这大概是因为flask仍在处理前一个请求,并且在数据库上有一个锁。有没有办法让我的MySQL异步或排队?即使换成更好的数据库解决方案也没问题。只要我能同时在烧瓶中有多个请求

app.py

session = classes.Session()

# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)

类.py

ssl_args = {'ssl_ca': './ca.crt'}
engine = create_engine("URL", connect_args=ssl_args)

Session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

Base = declarative_base()
Base.query = Session.query_property()

错误:

Traceback (most recent call last):
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\connections.py", line 756, in _write_bytes
    self._sock.sendall(data)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\Lib\ssl.py", line 1204, in sendall
    v = self.send(byte_view[count:])
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\Lib\ssl.py", line 1173, in send
    return self._sslobj.write(data)
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2477)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\engine\base.py", line 1706, in _execute_context
    self.dialect.do_execute(
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\engine\default.py", line 716, in do_execute
    cursor.execute(statement, parameters)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\cursors.py", line 148, in execute
    result = self._query(query)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\cursors.py", line 310, in _query
    conn.query(q)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\connections.py", line 547, in query
    self._execute_command(COMMAND.COM_QUERY, sql)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\connections.py", line 814, in _execute_command
    self._write_bytes(packet)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\connections.py", line 759, in _write_bytes
    raise err.OperationalError(
pymysql.err.OperationalError: (2006, "MySQL server has gone away (SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:2477)'))")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "E:\Documents\GitHub\thought4food\app\app.py", line 160, in recipeById
    return json.loads(str(recipe))
  File "E:\Documents\GitHub\thought4food\app\classes\recipe.py", line 21, in __repr__
    ingredients = json.loads(str(self.recipe_ingredients))
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\orm\attributes.py", line 465, in __get__
    return self.impl.get(state, dict_)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\orm\attributes.py", line 911, in get
    value = self.callable_(state, passive)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\orm\strategies.py", line 878, in _load_for_state
    return self._emit_lazyload(
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\orm\strategies.py", line 1041, in _emit_lazyload
    result = session.execute(
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\orm\session.py", line 1670, in execute
    result = conn._execute_20(statement, params or {}, execution_options)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\engine\base.py", line 1521, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\sql\lambdas.py", line 479, in _execute_on_connection
    return connection._execute_clauseelement(
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\engine\base.py", line 1390, in _execute_clauseelement
    ret = self._execute_context(
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\engine\base.py", line 1749, in _execute_context
    self._handle_dbapi_exception(
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\engine\base.py", line 1930, in _handle_dbapi_exception
    util.raise_(
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\util\compat.py", line 211, in raise_
    raise exception
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\engine\base.py", line 1706, in _execute_context
    self.dialect.do_execute(
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\sqlalchemy\engine\default.py", line 716, in do_execute
    cursor.execute(statement, parameters)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\cursors.py", line 148, in execute
    result = self._query(query)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\cursors.py", line 310, in _query
    conn.query(q)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\connections.py", line 547, in query
    self._execute_command(COMMAND.COM_QUERY, sql)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\connections.py", line 814, in _execute_command
    self._write_bytes(packet)
  File "E:\Documents\GitHub\thought4food\app\env\Lib\site-packages\pymysql\connections.py", line 759, in _write_bytes
    raise err.OperationalError(
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2006, "MySQL server has gone away (SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:2477)'))")
[SQL: SELECT ingredients.id AS ingredients_id, ingredients.name AS ingredients_name, ingredients.amount AS ingredients_amount, ingredients.unit AS ingredients_unit
FROM ingredients, recipe_ingredients
WHERE %(param_1)s = recipe_ingredients.recipe_id AND ingredients.id = recipe_ingredients.ingredient_id]
[parameters: {'param_1': 0}]
(Background on this error at: http://sqlalche.me/e/14/e3q8)

Tags: inpyselfgithubenvappexecutesqlalchemy
1条回答
网友
1楼 · 发布于 2024-09-28 13:37:37

我找到了解决办法

我将session = classes.Session()更改为session = classes.Session,并添加了:

@app.teardown_request
def remove_session(ex=None):
    session.remove()

这确保会话不再被使用,并将会话的控制权授予flask

相关问题 更多 >

    热门问题