TypeError:__ init __()得到了一个意外的关键字参数' username'

时间:2017-03-22 14:53:06

标签: python flask sqlalchemy

我正在尝试创建自己的数据库,但我得到一个TypeError:__ init __()得到了一个意外的关键字参数' username'。

我遵循文档和模拟堆栈溢出但我仍然得到相同的错误。如果我有一个构造函数 init 或者使用方法db.create_all(),它似乎也没有什么区别。

我做错了什么?我有人愿意帮助我,谢谢你:)。

from flask import Flask, flash, redirect, render_template, request, session, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from passlib.apps import custom_app_context as pwd_context
from tempfile import gettempdir

# configure application
app = Flask(__name__)

#Flask-SQLAlchemy  https://www.tutorialspoint.com/flask/flask_sqlalchemy.htm
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///froshims3.db"
db = SQLAlchemy(app)

# configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = gettempdir()
app.config["SESSION_PERMANENT"] = False
Session(app)

class users(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String)
    hash = db.Column(db.String)

# def __init__(self, username, password):
#   self.username = username
#   self.password = password

#db.create_all()

@app.route("/")
def index():
    return apology("TODO")

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user."""
    if request.method == "GET":
        # redirect user to register page
        return render_template("register.html")

    else: 
        # query database to see if username doesn't exist.
        rows = db.session.query("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
        if len(rows) == 1:
            return apology("username already exist")

        # hash: http://stackoverflow.com/questions/7627752/secure-authentication-system-in-python
        hash = pwd_context.encrypt(request.form["password"])
        user = Users(request.form["username"], request.form["dorm"])
        db.session.add(user)
        db.session.commit()
        user_id = db.session.query("SELECT id from users WHERE username = :username", username=request.form.get("username"))
        session["user_id"]= user_id
    return apology("Well Done")

2 个答案:

答案 0 :(得分:1)

有几件事:

  1. 如果您希望应用能够像您一样从数据创建用户,那么您的SQLAlchemy类需要__init__()方法。这就是错误告诉你的。 (如果你只是从桌子上读书,你不需要为此烦恼)
  2. 我对db.create_all()一无所知,因为我总是从外部数据库中获取资源,但我的理解是它会创建任何不存在的表,但不会覆盖已有的表已经创建了。因此,如果您的数据库存在,您可能不需要它。
  3. hash是保留字。怀疑这是搞乱任何事情,但改变它作为最佳实践的问题。我改变了它,将其推入用户模型。
  4. 您可以在完成db.commit()之后立即从已创建的实例中提取ID,而不是执行其他SQL查询。
  5. 我还将您的查询更改为" ORM Way"因为您正在使用SQLAlchemy,所以这就是您想要执行SQL的方式。
  6. 更新代码:

    from flask import Flask, flash, redirect, render_template, request, session, url_for
    from flask_sqlalchemy import SQLAlchemy
    from flask_session import Session
    from passlib.apps import custom_app_context as pwd_context
    from tempfile import gettempdir
    
    # configure application
    app = Flask(__name__)
    
    #Flask-SQLAlchemy  https://www.tutorialspoint.com/flask/flask_sqlalchemy.htm
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///froshims3.db"
    db = SQLAlchemy(app)
    
    # configure session to use filesystem (instead of signed cookies)
    app.config["SESSION_FILE_DIR"] = gettempdir()
    app.config["SESSION_PERMANENT"] = False
    Session(app)
    
    class User(db.Model):
        __tablename__ = 'users'
        id = db.Column(db.Integer, primary_key = True)
        username = db.Column(db.String)
        hash = db.Column(db.String)
    
        def __init__(self, username, password):
          self.username = username
          self.password = password
    
    db.create_all()
    
    @app.route("/")
    def index():
        return "TODO"
    
    @app.route("/register", methods=["GET", "POST"])
    def register():
        """Register user."""
        if request.method == "GET":
            # redirect user to register page
            return render_template("register.html")
    
        else:
            # query database to see if username doesn't exist.
            # ORM Way:
            exists = User.query.filter_by(username=request.form.get("username")).count()
            if exists:
                return "username already exists"
    
            # hash: http://stackoverflow.com/questions/7627752/secure-authentication-system-in-python
            hash_pwd = pwd_context.encrypt(request.form["password"])
            user = User(request.form["username"], hash_pwd)
            db.session.add(user)
            db.session.commit()
            session["user_id"]= user.id
        return "Well Done"
    

答案 1 :(得分:0)

@emma 我知道这个问题已经一岁了,但是对于SQLAlchemy错误

您必须导入这些功能 根据您的情况

from sqlalchemy import Column, String, Integer

以及您要添加的任何其他功能,只需导入它们 校验 here