python - 当我同时发送两个请求时,matplotlib 中的绘图重叠
问题描述
我对 Flask 和 matplotlib 有疑问。我编写了一个从 matplotlib 返回图表的简单 API。当两个用户同时发送请求时,即使我为图表创建了单独的类,图表也会重叠。
这是我的代码:
class WykresXT:
def make(self, amp, okres):
name = random.randint(0, 1000000)
time = np.arange(0, 20, 0.1)
plot.plot(time, calc_xt(amp=float(amp), czas=time, okres_d=float(okres)))
plot.title('Wykres x(t)')
plot.xlabel('t (czas)')
plot.ylabel('x (wychylenie)')
plot.grid(True, which='both')
plot.axhline(y=0, color='k')
plot.savefig(str(name) + '.png')
plot.close()
plot.figure().clear()
return str(name) + '.png'
@app.route('/wykres_x', methods=['GET'])
def wykres_x():
args = {"amp": request.args.get('amp'), "okres": request.args.get('okres'), "faza": request.args.get('faza')}
if args["amp"] is not None and args["okres"] is not None and args["faza"] is not None:
wykres = WykresXT()
return send_file(wykres.make(args["amp"], args["faza"], args["okres"]))
else:
return "podaj: '?amp=' '&okres=' '&faza='"
还有一个重叠问题的例子:
解决方案
好的,所以我能够重现您的错误并设法修复它。在那里测试,看看它是否适合你。
我创建了这个脚本来一次发送多个请求,取自另一个 SO 帖子。
import requests
from concurrent.futures import ThreadPoolExecutor
def get_url(url):
return requests.get(url)
list_of_urls = [
'http://0.0.0.0:25565/wykres_x?amp=5&okres=10',
'http://0.0.0.0:25565/wykres_x?amp=10&okres=10',
'http://0.0.0.0:25565/wykres_x?amp=15&okres=10',
'http://0.0.0.0:25565/wykres_x?amp=20&okres=10',
'http://0.0.0.0:25565/wykres_x?amp=5&okres=15',
'http://0.0.0.0:25565/wykres_x?amp=10&okres=20',
'http://0.0.0.0:25565/wykres_x?amp=5&okres=30',
'http://0.0.0.0:25565/wykres_x?amp=10&okres=40'
]
with ThreadPoolExecutor(max_workers=10) as pool:
print(list(pool.map(get_url,list_of_urls)))
当我在您的服务器运行时运行此程序时,正如预期的那样,我得到了一些彩色图表。
然后,正如我在评论中提到的,我将 pyplot 调用从隐式更改为显式。这是你的课。
class WykresXT:
def make(self, amp, okres):
name = random.randint(0, 1000000)
time = np.arange(0, 20, 0.1)
fig, ax = plot.subplots() # <-- here is the start of the different part
ax.plot(time, calc_xt(amp=float(amp), czas=time, okres_d=float(okres)))
ax.set_title('Wykres x(t)')
ax.set_xlabel('t (czas)')
ax.set_ylabel('x (wychylenie)')
ax.grid(True, which='both')
ax.axhline(y=0, color='k')
fig.savefig(str(name) + '.png') # <-- end of the modified part
plot.close()
plot.figure().clear()
return str(name) + '.png'
它现在创建了一堆图形,按照您的需要全部分开。
推荐阅读
- c++ - 如何编写广义 constexpr std::is_same_v
- react-native - React Native Expo:面临将价值传递给其他 Screnns 的问题
- python - 有没有办法使用 Python 在 Valorant 中模拟鼠标移动?
- java - quotaUser 对 Google Books API 的使用情况
- r - for循环中的索引
- javascript - Jest - 在递归函数中测试回调调用
- java - Linux 环境中的 Java 应用程序堆栈溢出
- f# - 如何在 f# 中使用 suave 从 http 重定向到 https
- android - DropDownTextView Android 改变颜色
- ios - 在 Xcode 中构建反应本机项目的问题 - 错误:找不到自动链接库 + 未定义符号等