Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 炼金术、水平缩放和范围会话_Python_Orm_Sqlalchemy_Flask Sqlalchemy_Horizontal Scaling - Fatal编程技术网

Python 炼金术、水平缩放和范围会话

Python 炼金术、水平缩放和范围会话,python,orm,sqlalchemy,flask-sqlalchemy,horizontal-scaling,Python,Orm,Sqlalchemy,Flask Sqlalchemy,Horizontal Scaling,我有一个炼金术应用程序,我想缩放horiontally @app.route('/read') def read(): e = db.session.query(Example).get(1) return e.value, 200 @app.route('/increase') def increase(): e = db.session.query(Example).get(1) e.value += 1 db.session.add(e)

我有一个炼金术应用程序,我想缩放horiontally

@app.route('/read')
def read():
    e = db.session.query(Example).get(1)
    return e.value, 200


@app.route('/increase')
def increase():
    e = db.session.query(Example).get(1)
    e.value += 1
    db.session.add(e)
    db.session.commit()
    return e.value, 200
有两个端点:

读取-获取id为1的实体并获取值

增加=获取id为1的实体并增加值

然后我想水平缩放,Alchemy不会同步工作进程之间的会话。所以即使我增加worker 2中的值,也无法从worker 1获得实际值

用户请求示例:

curl GET /read/ [worker-1]
1


curl GET /increase/ [worker-2]
2


curl GET /read/ [worker-1]
1
如您所见,sqlalchemy不提供自动刷新会话状态的工具


解决这个问题的最佳方法是什么?使用新会话进行新查询?或者使用
session.refresh(实例)
。推荐的方法是什么?

您应该在每次请求后中断会话。提供了以下代码段:

from yourapplication.database import db_session

@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

即使如此,对同一对象的并发编辑也是不安全的。如果希望select更新是原子更新,则需要更改会话的隔离级别(请参见)。

另一个选项是使用flask sqlalchemy yes。这也是我链接的那一页上的推荐。这肯定会解决问题。