首页 > 解决方案 > Flask:如何向可能同时访问的每个用户返回不同的内容

问题描述

我正在创建一个小项目(它没有任何形式的登录来区分用户)。用户请求一些统计信息,python 生成一个保存到文件夹然后显示在 HTML 中的图,每次完成新请求时,图像都会被覆盖。您可以想象,如果 2 位用户同时访问,一位用户可能会看到另一位用户的请求。

我的问题主要是找到一种方法来轻松解决这个问题。你会生成一个随机数并用它来写文件名吗?或者从浏览器中获取一些用户独特的数据?

任何建议都受到高度赞赏。

Python

  coin_plot = sns.catplot(x='24hours', y='coin name', data=plot_df, kind='bar')
        plt.title('Coins and 24 hours market change')
        coin_plot.savefig("static/coin_plot.png")

HTML

<img src="{{url_for('static', filename='coin_plot.png')}}" />

标签: pythonhtmlflasksession

解决方案


一种方法是直接将内存中的原始字节作为图像返回(跳过保存到磁盘)

import io
from flask import make_response
...
@app.route("/my_plot.png")
def my_plot():
     ....
     coin_plot = sns.catplot(x='24hours', y='coin name', data=plot_df, kind='bar')
     plt.title('Coins and 24 hours market change')
     buffer = io.StringIO()
     coin_plot.savefig(buffer, format="png")   
     buffer.seek(0)
     response = make_response(buffer.read())
     response.headers.set('Content-Type', 'image/png')
     response.headers.set('Content-Disposition', 'attachment', filename='image.png')
     return response

推荐阅读