python - 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')}}" />
解决方案
一种方法是直接将内存中的原始字节作为图像返回(跳过保存到磁盘)
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
推荐阅读
- python - scikit-learn 的 one-hot-encoded 特征的格式应该是什么?
- c# - 单个事务中的数据库操作和调用 API
- sql-server - 在 Ireport 4.7.1 中,连接数据库时出现套接字创建错误
- regex - 将所有以#WAV 开头的行替换为一行,notepad++
- php - 检查数组中删除、更改和添加的元素
- amazon-cloudwatch - AWS Cloudwatch 见解 - 返回不成功的 id
- python - 如何在查询 django 中过滤 2 Q 条件?
- javascript - 如何使溢出文本从左到右动画?
- python - 在 Python 中拟合 Arima 模型时出现值警告
- lme4 - 使用 lmer() 和 lme() 对带有子样本的裂区设计进行建模的 df 和 p 值的差异