【问题标题】:SQLAlchemy and mysql throwing errors on concurrent requestsSQLAlchemy 和 mysql 在并发请求上抛出错误
【发布时间】:2021-07-18 11:56:29
【问题描述】:

我正在编写一个应用程序,每当我一次执行一个请求时,一切都很好。但是当我的 vuejs 前端调用我的烧瓶后端时,同时使用 2 个请求,我得到一个很大的错误,见下文。这大概是因为flask还在处理之前的请求,并且对数据库有锁。有没有办法让我的 MySQL 异步或让它们排队?即使更改为更好的数据库解决方案也可以。只要我可以在烧瓶中同时有多个请求。

app.py

session = classes.Session()

# configuration
DEBUG = True

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

classes.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)

【问题讨论】:

  • 我也尝试添加池大小,但没有奏效

标签: python python-3.x flask sqlalchemy


【解决方案1】:

我找到了解决办法。

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

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

这确保会话不再使用,并将会话控制权交给烧瓶。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2020-08-22
    • 2013-08-16
    • 1970-01-01
    • 2014-08-05
    • 2019-12-02
    • 2013-04-17
    相关资源
    最近更新 更多