在Flask中,我如何使用阻止?

时间:2017-06-30 06:16:12

标签: python 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))

当我填写表单并点击提交按钮时,会发生如下错误。

  

并非在字符串格式化期间转换所有参数

我猜这是因为挫败。 当我插入print(thwart(username))时,输出 b'用户名'

int(x)没有值。

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

上述内容似乎无效,因为(thwart(username)),我不确定。

你能告诉我如何解决它吗?

1 个答案:

答案 0 :(得分:3)

要表示带有项目的元组,在右括号之前应该有一个尾随逗号:

>>> 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 根据{{​​3}},未定义DB API v2返回值。您最好使用cursor.fetch*()来获取结果。