【问题标题】:Bad Request - The browser (or proxy) sent a request that this server could not understand [duplicate]错误请求 - 浏览器(或代理)发送了此服务器无法理解的请求 [重复]
【发布时间】:2018-12-13 19:40:57
【问题描述】:

我正在尝试创建一个烧瓶应用程序,其中我在网页上有一个文本框。当按下提交时,它会搜索在 postgres 数据库表的文本框中输入的内容。

我收到以下错误:

错误请求 浏览器(或代理)发送了此服务器无法发送的请求 明白。”

我的代码如下:

app.py

from flask import Flask, render_template, request
from sqlalchemy import create_engine

app = Flask(__name__)
app.config['DEBUG']

db_string = "postgres://xx:xx@xx:5432/xx"

db = create_engine(db_string)

@app.route('/', methods=['GET', 'POST'])
def homepage():
    jn = request.form['jobnumber']
    result_set = db.execute("SELECT cost FROM public.options where optionno = (f'%{jn}%')").fetchall()
    return render_template('main.html', test=result_set, jn=jn)

    if __name__ == "__main__":
        app.run(debug=True)

还有我的 html 文件:

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>xxx</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>

<body>
<p>xxx</p>

<form method="POST">
    <input name="jobnumber" type="submit" placeholder="jn">
</form>

<table> 

<td>
       {{test}}

</td>


</table>

</body>
</html>

我确信它会解决它非常简单和简单,但我正在努力,所以任何帮助将不胜感激。

【问题讨论】:

    标签: python flask psycopg


    【解决方案1】:

    由于您的 homepage 函数同时接收 GET 和 POST 请求,您需要分别处理每种情况。当您收到 GET 请求时,您没有 request.form

    @app.route('/', methods=['GET', 'POST'])
    def homepage():
        if request.method == 'POST'
            jn = request.form['jobnumber']
            result_set = db.execute("SELECT cost FROM public.options where optionno = (f'%{jn}%')").fetchall()
            return render_template('main.html', test=result_set, jn=jn)
        else:
            return render_template('main.html')
    

    请注意,将用户的输入直接放入您的 SQL 查询中而不对其进行清理是很危险的,因为这会使您的应用受到SQL injection 攻击。

    【讨论】:

    • 感谢您的回答,成功了!但是,当我在文本框中输入任何内容并按 Enter 键时,现在出现此错误:TypeError: 'dict' object does not support indexing
    • 我猜它与this有关。如果那没有帮助,我建议您提出一个新问题。 @keyring88
    猜你喜欢
    • 2018-06-21
    • 2018-12-20
    • 2020-07-10
    • 2018-07-24
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多