Search code examples
htmlmysqlhttp-postquart

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


I was trying to create a register form which post the data to MySQL database. The code are

@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')

and my form code are

<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>

When I stay on the register page and submit up the form it worked and sent the data over to the database. But when I try to access the page from the index page, I get

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

I assumed that the problem is my register page is trying to request a form data which has not been submitted yet. If my assumption are correct, is there anyways to fix my problem?


Solution

  • You can use

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

    to check if you received a get or post request

    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')
    

    It will render the register.html template without looking for any post data if the method is 'GET'

    By the way, you should check if the username or mail doesn't already exist before inserting your data (Avoiding duplicate when you'll query for a specific user on login)