首页 > 解决方案 > 烧瓶路由可以同时返回 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'}

标签: pythonflaskjinja2

解决方案


这是一个最小的工作示例,它使用和生成的页面{{ 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)

推荐阅读