在Flas中读取python重写的图像

2024-03-28 13:58:26 发布

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

我有如下代码:

app = Flask(__name__,static_url_path='/static')
@app.route('/')
def my_form():
    return render_template('my-form.html')

@app.route('/result', methods=['POST'])
def result():

    text = request.form['Name']
    sentiment = generateimage(text)



    return render_template("result.html")

我的-表单.html

<div class="col-lg-1"></div>
<div class="col-lg-10">
    <form action="http://localhost:5505/result" method="POST">
        <div class="form-group">
            <label for="comment">Text</label>
            <textarea class="form-control" rows="10" cols="4" id="comment" name="Name"></textarea>
        </div>
        <input type="submit" class="btn btn-info" value="Analyze">
    </form>
</div>
</div>

结果.html

 <img src ="/static/fig1.png"/> 

flask.py所做的是从my-form抓取文本,处理它并在静态文件夹中生成一个图像,但是当result.html页面加载时,它会显示先前生成的图像,而不是最近生成的图像。你知道吗

如何解决这个问题?你知道吗

def generateimage(text)
       ######some code######
        plt.savefig('/home/aurora/Desktop/sentiment/static/fig1.png', dpi=dpi)

Tags: textname图像divformappreturnmy
1条回答
网友
1楼 · 发布于 2024-03-28 13:58:26

我将假设这是一个缓存问题,否则您对系统的第一次调用将根本不会生成映像。一种快速而肮脏的方法是,在result.html中的图像URL之后添加一个随机查询字符串,从而强制不缓存图像:

<img src ="/static/fig1.png?{{no_cache}}"/>

然后从你的烧瓶应用程序中调用它:

return render_template("result.html", no_cache=time.time())  # import time, of course

这在某种程度上违背了静态内容的目的-如果您总是要基于用户输入来呈现图像,那么存储它几乎没有任何意义-只需创建一个不同的Flask端点,直接将图像呈现给用户,而不必存储它,并调用它而不是图像的静态URL。你知道吗

相关问题 更多 >