Flask 烧瓶应用程序中的内存数据
我认为在Flask中使用实例变量的正确方法是添加用户和会话,但我正在尝试测试一个概念,我现在还不想讨论所有这些。我正在尝试让一个web应用程序将一个图像加载到一个变量中,然后可以对该变量执行不同的图像操作。显然,您不希望在每次新请求时都必须在映像上执行一系列操作,因为这样会非常低效 有没有一种方法可以让我从不同的路径访问烧瓶中的Flask 烧瓶应用程序中的内存数据,flask,Flask,我认为在Flask中使用实例变量的正确方法是添加用户和会话,但我正在尝试测试一个概念,我现在还不想讨论所有这些。我正在尝试让一个web应用程序将一个图像加载到一个变量中,然后可以对该变量执行不同的图像操作。显然,您不希望在每次新请求时都必须在映像上执行一系列操作,因为这样会非常低效 有没有一种方法可以让我从不同的路径访问烧瓶中的app.var?我尝试过使用全局上下文和Flask的当前应用程序,但我得到的印象是,它们并不是为了这个目的 我的蓝图的代码是: import os from flask
app.var
?我尝试过使用全局上下文和Flask的当前应用程序
,但我得到的印象是,它们并不是为了这个目的
我的蓝图的代码是:
import os
from flask import Flask, url_for, render_template, \
g, send_file, Blueprint
from io import BytesIO
from PIL import Image, ImageDraw, ImageOps
home = Blueprint('home', __name__)
@home.before_request
def before_request():
g.img = None
g.user = None
@home.route('/')
def index():
return render_template('home/index.html')
@home.route('/image')
def image():
if g.img is None:
root = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(root, '../static/images/lena.jpg')
g.img = Image.open(filename)
img_bytes = BytesIO()
g.img.save(img_bytes, 'jpeg')
img_bytes.seek(0)
return send_file(img_bytes, mimetype='image/jpg')
@home.route('/grayscale', methods=['POST'])
def grayscale():
if g.img:
print('POST grayscale request')
g.img = ImageOps.grayscale(img)
return "Grayscale operation successful"
else:
print('Grayscale called with no image loaded')
return "Grayscale operation failed"
/image
路由正确返回图像,但我希望能够调用/grayscale
,执行该操作,并且能够再次调用/image
,让它从内存中返回图像而不加载它。您可以在会话变量中保存一个键,并使用它在全局字典中标识图像。但是,如果使用多个Flask应用程序实例,这可能会导致一些问题。但是有一个就好了。否则,您可以在处理多个工作人员时使用Redis。我还没有尝试过下面的代码,但它应该显示出这个概念
from flask import session
import uuid
app.config['SECRET_KEY'] = 'your secret key'
img_dict = {}
@route('/image')
def image():
key = session.get('key')
if key is None:
session['key'] = key = uuid.uuid1()
img_dict[key] = yourimagedata
@home.route('/grayscale', methods=['POST'])
def grayscale():
key = session.get('key')
if key is None:
print('Grayscale called with no image loaded')
return "Grayscale operation failed"
else:
img = img_dict[key]
print('POST grayscale request')
g.img = ImageOps.grayscale(img)
return "Grayscale operation successful"
这里的一些代码将有助于全面理解您的意图。我懒洋洋地在电话里发帖,上班时忘了更新。不幸的是,这样不行,我得到的答复是,
键为None
。然而,我确实找到了Flask IIIF,目前我正试图理解如何实现ImageSimpleCache
,这听起来像是我想要的东西。我忘了。为了让这项工作正常进行,你需要通过执行app.config['secret\u key']='your secret key'
来设置一个密钥。最终有机会使用UUID进行了尝试,它似乎完成了我目前需要的任务。谢谢