如何在 Python Quart 中接受请求之前呈现网页?

How to make webpage render before taking request in Python Quart?

我试图创建一个注册表单,其中 post 数据到 MySQL 数据库。代码是

@app.route('/register', methods=['GET', 'POST'])
async def register():
    conn = await aiomysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PASS, db=DB_NAME)
    cur = await conn.cursor()
    _Username = (await request.form)["Username"]
    _Email = (await request.form)["Email"]
    _Password = (await request.form)["Password"]
    async with conn.cursor() as cur:
        await cur.execute (
            "INSERT INTO Users (Username, Email, Password) VALUES (%s, %s, %s)", (_Username, _Email, _Password)
                          )
    await conn.commit()
    return await render_template('register.html')

我的表单代码是

<form action="" method="POST">
                   <input class="text" type="text" name="Username" placeholder="Username" required="">
                   <input class="text email" type="email" name="Email" placeholder="Email" required="">
                   <input class="text" type="password" name="Password" placeholder="Password" required="">
                   <input class="text w3lpass" type="password" name="password" placeholder="Confirm Password" required="">
                   <input type="submit" value="SIGNUP">
               </form>

当我停留在注册页面并提交表格时,它起作用并将数据发送到数据库。 但是当我尝试从索引页面访问该页面时,我得到

400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

我假设问题是我的注册页面正在尝试请求尚未提交的表单数据。如果我的假设是正确的,有没有办法解决我的问题?

您可以使用

if request.method == 'POST' 
#or 
if request.method == 'GET' 

检查您是否收到 get 或 post 请求

async def register():
    if request.method == 'POST':
        conn = await aiomysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PASS, db=DB_NAME)
        cur = await conn.cursor()
        _Username = (await request.form)["Username"]
        _Email = (await request.form)["Email"]
        _Password = (await request.form)["Password"]
        async with conn.cursor() as cur:
            await cur.execute (
                "INSERT INTO Users (Username, Email, Password) VALUES (%s, %s, %s)", (_Username, _Email, _Password)                          )
        await conn.commit()
    return await render_template('register.html')

如果方法是 'GET'

,它将呈现 register.html 模板而不查找任何 post 数据

顺便说一句,您应该在插入数据之前检查用户名或邮件是否不存在(避免在登录时查询特定用户时重复)