Python | Flask,在类中使用request.form发布数据并更新Jinja模板

2024-05-14 23:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用外汇兑换器api构建一个小应用程序,它的功能是获取一种货币,并将一个值转换为新货币。我似乎在访问我的类“调查”时被抓住了,我试图从我的html表单获取数据我的程序在self.convertFrom=request.form['convertFrom']上被捕获,python调试器给了我“RuntimeError:在请求上下文之外工作”。如果有人能向我展示/解释我在这里做错了什么,我将不胜感激

app.py

from flask_debugtoolbar import DebugToolbar
from forex_python.converter import CurrencyRates
from handleForm import Survey
app = Flask(__name__)
survey = Survey()
result=["Give me something to convert!"]

@app.route("/")
def home_page():
    """Loads home page where user can enter their first conversion"""
    return render_template('index.html')

@app.route("/conversion")
def show_conversion():
    """shows the users conversion"""
    return render_template('convSubmit.html', result=result)

@app.route("/conversion/new", methods=["POST"])
def add_conversion():
    """clear old conversion from list and add new"""
    result=[]
    result.append(survey.convertCurrency())
    return redirect("/conversion")

手形

from flask import Flask, render_template, request
from forex_python.converter import CurrencyRates
c = CurrencyRates()


class Survey():
    def __init__(self):
        self.convertFrom=request.form['convertFrom'] <---gets caught here
        self.convertTo=request.form['convertTo']
        self.value=request.form['value']
        

    def convertCurrency(self):
        currencyFrom = self.convertFrom
        currencyTo = self.convertTo
        getValue = int(self.value)
        result = c.convert(currencyFrom, currencyTo, getValue)
        return result

Tags: fromimportselfformappreturnrequestdef
1条回答
网友
1楼 · 发布于 2024-05-14 23:49:00

请求变量仅在请求处于活动状态时可用。简单来说,只有当处理路由的视图函数调用它时,它才可用

在本例中,您正试图在任何根函数之外初始化测量对象。当应用服务器启动时,在保留任何请求之前,该行将被调用,因此flask抛出一个错误,表示您在请求上下文之外调用它

要修复它,您应该在视图函数中移动survey = Survey()


@app.route("/conversion/new", methods=["POST"])
def add_conversion():
    """clear old conversion from list and add new"""
    result=[]
    survey = Survey()
    result.append(survey.convertCurrency())
    return redirect("/conversion")

虽然这样可以解决问题,但让类构造函数直接访问请求全局仍然不是一个好模式

如果需要构造函数本身来初始化这些参数,可以将这些参数作为参数传递给构造函数,然后在初始化时传递它们


from flask import Flask, render_template, request
from forex_python.converter import CurrencyRates
c = CurrencyRates()


class Survey():
    def __init__(self, convertFrom, convertTo, value):
        self.convertFrom=convertFrom < -gets caught here
        self.convertTo=convertTo
        self.value=value
        

    def convertCurrency(self):
        currencyFrom = self.convertFrom
        currencyTo = self.convertTo
        getValue = int(self.value)
        result = c.convert(currencyFrom, currencyTo, getValue)
        return result

然后更改view函数以将值传递给构造函数

@app.route("/conversion/new", methods=["POST"])
def add_conversion():
    """clear old conversion from list and add new"""
    result=[]
    survey = Survey(request.form["convertFrom"], request.form["convertTo"], request.form["value"])
    result.append(survey.convertCurrency())
    return redirect("/conversion")

相关问题 更多 >

    热门问题