python 在Flask中,我如何使用阻挠?

ctehm74n  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(98)

此问题在此处已有答案

Why do I get "TypeError: not all arguments converted during string formatting" when trying to use a string in a parameterized SQL query?(8个答案)
5年前关闭。
我一直在努力用flask实现用户注册函数。下面是我完成的代码。

import os
from flask import Flask, render_template, flash, request, url_for, redirect, session
from content_management import Content
from dbconnect import connection
from wtforms import Form, BooleanField, TextField, PasswordField, validators
from passlib.handlers.sha2_crypt import sha256_crypt
from MySQLdb import escape_string as thwart
import gc

def register_page():
    try:
        form = RegistrationForm(request.form)
        if request.method == "POST" and form.validate():
            username = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt((str(form.password.data)))

            c, conn = connection()

            x = c.execute("SELECT * FROM users WHERE username = (%s)", (thwart(username)))
            if int(x) > 0:
                flash("That username is already taken, please choose another")
                return render_template("register.html", form = form)
            else:
                c.execute("INSERT INTO users (username, email, password, tracking) VALUES (%s, %s, %s, %s)", (thwart(username), thwart(password), thwart(email), thwart("/introduction-to-python-programming/")))
                conn.commit()
                flash("Thanks for registering")
                c.close()
                conn.close()
                gc.collect()

                session['login_in'] = True
                session['username'] = username

                return redirect(url_for('dashboard'))
        return render_template("register.html", form = form)

    except Exception as e:
        return(str(e))

当我填写表格并点击提交按钮时,错误发生如下。
在字符串格式化期间并非所有参数都被转换
我猜这是因为thwart的缘故,当我插入print(thwart(username))时,输出b'username'
但是**int(x)**没有值。

x = c.execute("SELECT * FROM users WHERE username = (%s)", (thwart(username)))

上面的似乎不工作,因为(thwart(username)),我不确定。
你能告诉我怎么修吗?

2skhul33

2skhul331#

要用一个元素来表示一个元组,在右括号前应该有一个逗号:

>>> x = (1)  # without trailing command => `(1) == 1`
>>> type(x)
<type 'int'>
>>> x = (1,)  # with trailing comma
>>> type(x)
<type 'tuple'>
x = c.execute("SELECT * FROM users WHERE username = (%s)", (thwart(username),))

或者你可以使用一个列表:

x = c.execute("SELECT * FROM users WHERE username = (%s)", [thwart(username)])

Side Note根据DB API v2cursor.execute*(..)返回值没有定义,最好使用use cursor.fetch*()来获取结果。

相关问题