在启用多进程的Flask应用中使用全局变量可以通过使用共享内存或者数据库来实现。
示例代码:
from multiprocessing import Value
from flask import Flask
app = Flask(__name__)
counter = Value('i', 0)
@app.route('/')
def index():
with counter.get_lock():
counter.value += 1
return f'Counter: {counter.value}'
if __name__ == '__main__':
app.run()
示例代码:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'
db = SQLAlchemy(app)
class GlobalVariable(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
value = db.Column(db.String(50))
@app.route('/')
def index():
variable = GlobalVariable.query.filter_by(name='counter').first()
if variable is None:
variable = GlobalVariable(name='counter', value='0')
db.session.add(variable)
else:
variable.value = str(int(variable.value) + 1)
db.session.commit()
return f'Counter: {variable.value}'
if __name__ == '__main__':
app.run()
以上是在启用多进程的Flask应用中使用全局变量的两种方法。具体选择哪种方法取决于应用的需求和实际情况。
领取专属 10元无门槛券
手把手带您无忧上云