python - 烧瓶路由可以同时返回 IO 流和变量吗?
问题描述
我正在使用烧瓶路由生成一个 QR 码作为字节流,在主页上使用 jinja2 模板非常简单地调用它,如下所示:
#INDEX.HTML
<img src="{{ url_for('qr') }}">
这可行,但路由函数 ( cost
) 中有另一个变量,我也想在主页上呈现,但我不知道如何返回它。我已经尝试返回一个render_template
包含cost=cost
并调用它,{{cost}}
但它没有出现并且 QR 码没有呈现。是否可以在 return 语句中同时返回 IO 流和变量,或者以某种方式将变量传递给索引路由?
这是路由功能:
#ROUTES.PY
@app.route('/qr', methods=['GET', 'POST'])
def qr():
conversion = requests.get(API_ADDRESS)
cost = conversion*10
basestring = pyqrcode.create(cost, error='H')
stream = BytesIO()
basestring.svg(stream, scale=5)
return stream.getvalue(), 200, {
'Content-Type': 'image/svg+xml',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'}
解决方案
这是一个最小的工作示例,它使用和生成的页面{{ cost }}
由andQRcode
生成@app.route('/qr/<int:cost>')
{{ url_for('qr', cost=cost) }}
from flask import Flask, render_template_string
import pyqrcode
from io import BytesIO
import random
app = Flask(__name__)
@app.route('/')
def index():
#conversion = requests.get(API_ADDRESS)
conversion = random.randint(1, 9)
cost = conversion*10
return render_template_string('''Cost: {{ cost }}<br>
<img src="{{ url_for('qr', cost=cost) }}">''', cost=cost)
@app.route('/qr/<int:cost>') #, methods=['GET', 'POST'])
def qr(cost):
base_string = pyqrcode.create(cost, error='H')
stream = BytesIO()
base_string.svg(stream, scale=5)
return stream.getvalue(), 200, {
'Content-Type': 'image/svg+xml',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'}
if __name__ == '__main__':
app.run(debug=True, use_reloader=False)
推荐阅读
- swift - 如何在 TableViewCell 中嵌入 AVPlayerViewController
- sql - 从同一个表中的两个单独的员工记录中获取新/旧值
- c# - 完成添加到集合时从 BlockingCollection.TakeFromAny 优雅退出
- visual-studio-code - 从 web 视图向扩展发送消息时如何传递回调函数
- php - 在没有类实例化的情况下调用方法
- azure - 用于警报的 Azure Application Insights Webhook 有效负载
- html - 如何使外部样式表中的类的 css 优先于元素的 css
- c# - 无法下载页面以单击使用 Puppeteer for C# 的按钮
- scheme - 如果原子不在列表中,将返回零的方案代码
- c++ - Windows 套接字编程:MFC CSocket 与 Win32 套接字