0

我试图创建一个将数据发布到 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.

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

4

1 回答 1

0

您可以使用

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 模板而不查找任何发布数据

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

于 2021-03-31T11:57:43.337 回答