Python 和 Flask 的二次方程

Quadratic Equation with Python and Flask

所以目前我正在尝试使用 flask 制作一个程序,但是当我 运行 它时我得到一个 TypeError,说 The view function for 'post_factors' did not return a valid response. The function either returned None or ended without a return statement. 我不知道如何修复它.这是代码:

import math

def dofactors(a, b, c):
    a = int(a)
    b = int(b)
    c = int(c)
    d = b**2-4*a*c # discriminant

    if d < 0:
        result = 'No solutions'
    elif d == 0:
        x1 = -b / (2*a)
        result = f'The sole solution is {str(x1)}'
    else: # if d > 0
        x1 = (-b + math.sqrt(d)) / (2*a)
        x2 = (-b - math.sqrt(d)) / (2*a)
        result = f'Solutions are {str(x1)} and {str(x2)}'

    return(result)

和 HTML:

<!DOCTYPE html>
<form method="POST">
  <p><h1>Factorizer</h1></p>
    <p>please enter your variable values assuming the form ax^2+bx+c</p>
  <input type="text", placeholder="a", name="a" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '');" />
  <input type="text", placeholder="b", name="b" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '');" />
  <input type="text", placeholder="c", name="c" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '');" />
  <input type="submit">
</form>

编辑:我忘记在主 class 中包含调用它的代码,这里是:

@app.route('/factors')
def form_factors():
    return render_template('factors.html')

和POST函数:

@app.route('/factors', methods=['POST'])
def post_factors():
    a = str(request.form['a'])
    b = str(request.form['b'])
    c = str(request.form['c'])
    dofactors(a, b, c)

您在 dofactor 函数中 returning 值,但是这些“return”不适用于路由,因为它们在不同的范围内。您可以在 post_factors 路线中使用以下内容解决此问题。

return(dofactors(a, b, c))