【问题标题】:Python | Flask, using request.form in a class to POST data and update Jinja Template蟒蛇 | Flask,在类中使用 request.form 来发布数据并更新 Jinja 模板
【发布时间】:2021-03-14 03:33:46
【问题描述】:

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

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")

handleForm.py

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

【问题讨论】:

    标签: python flask


    【解决方案1】:

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

    在您的情况下,您正在尝试在任何根函数之外初始化调查对象。该行将在应用服务器启动时调用,在任何请求被保留之前,因此烧瓶会抛出一个错误,说明您在请求上下文之外调用它。

    要修复它,您应该将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
    

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

    @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")
    

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多