用flas接收用户输入的问题

2024-10-05 10:11:09 发布

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

这是我几周前第一次学习python时写的一个程序,它简单地解出二次公式,检查解是否无关,并找到二次图的一些关键特征,包括顶点、对称线,我甚至让它对根进行因子化。这一切都很好,但它只在控制台工作。在

当我开始把它带到flask应用程序中并修改它以接受用户输入时,它只适用于结果是完美的数字而不是小数。例如A=1b=4c=4。每当输入A=2b=1C=4之类的内容时,它会给我这样的提示:http405错误。在

在主.py公司名称:

from flask import Flask, render_template, request
import math

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def quadratic():
    if request.method == 'POST':
        a = float(request.form['a'])
        b = float(request.form['b'])
        c = float(request.form['c'])
        outside = b * -1
        bsquared = b ** 2
        four_a_c = 4 * a * c
        discriminant = bsquared - four_a_c
        bottom = 2 * a
        discriminant_sqrt = math.sqrt(discriminant)
        top = outside + discriminant_sqrt
        top2 = outside - discriminant_sqrt
        root = top/bottom
        root2 = top2/bottom
        equation = a * root ** 2 + b * root + c
        equation2 = a * root2 ** 2 + b * root + c
        if equation < 1 and equation > -1:
            Ex = "Not Extraneous"
        else:
            Ex = "Extraneous"
        if equation2 < 1 and equation2 > -1:
            Ex2 = "Not Extraneous"
        else:
            Ex2 = "Extraneous"

        return render_template('form.html', discriminant=discriminant, a=a, b=b, c=c, outside=outside, bsquared=bsquared, bottom=bottom, root=root, root2=root2, ex=Ex, ex2=Ex2)

    if request.method == 'GET':
        return render_template('form.html')

if __name__ == '__main__':
    app.run()

在表单.html公司名称:

^{pr2}$

Tags: formappifrequesttemplaterootsqrtfloat
2条回答

当收到HTTP状态错误代码时,最好的做法是在调试模式下运行应用程序。由于您希望在WSGI服务器后面运行应用程序,因此最简单的方法是将最后一行更改为

app.run(debug=True)

一旦您这样做,您将看到实际的错误。在这种情况下

^{pr2}$

使用交互式调试器,我们可以检查原因。在

^{3}$

这是你问题的根源。根据documentation for the ^{} module(加黑体表示强调):

CPython implementation detail: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases follows Annex F of the C99 standard where appropriate. The current implementation will raise ValueError for invalid operations like sqrt(-1.0) or log(0.0) (where C99 Annex F recommends signaling invalid operation or divide-by-zero), and OverflowError for results that overflow (for example, exp(1000.0)).

math.sqrt(a_negative_number)将引发一个ValueError。你的输入没有解决方案(或者有一个复杂的解决方案,这取决于你如何看待它)。你能做的最好的事情就是检查这个案例并向用户提供更好的反馈。在

try:
    discriminant_sqrt = math.sqrt(discriminant)
except ValueError:
    flash('There is no solution for the given inputs.', 'error')
else
    # continue with calculations

表单的action属性应该是/,而不是{}。如果这只是一个单页Flask应用程序,您甚至可以将action属性一起删除到表单来自的同一个URL。在

相关问题 更多 >

    热门问题