我正在开始一个简单的项目,我正在尝试创建crud并为某些用户授予权限。
我在python-flask中编程,我的数据库是Postgres。
Python版本 - 3.6.5 / Postgres - 10.3 / 烧瓶0.12.2
当我尝试将用户添加到我的数据库时,它给了我这个错误:
__init__()
需要1个位置参数,但有3个被赋予
add_user.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>This is a tittle </title>
</head>
<body>
<form method="POST" action="/post_user">
<label> Email: </label>
<input id="email" name ="email" type="text" />
<label> Password: </label>
<input id="password" name ="password" type="password" />
<input type="submit" />
</form>
</body>
</html>
app.py
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required
#check Block tags - importante para poupar linhas de codigo
#Create app
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:admin@localhost/projetofinal'
app.config['SECRET_KEY'] = 'super-secret'
app.config['SECURITY_REGISTERABLE'] = True
#Set the application in debug mode so that the server is reloaded on any code change & helps debug
app.config['DEBUG'] = True
app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SECURITY_PASSWORD_SALT'] = '$2a$16$PnnIgfMwkOjGX4SkHqSOPO'
# Create database connection object
db = SQLAlchemy(app)
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/add')
def add():
return render_template('add_user.html')
# <> - dynamic url routing
# login_required - Need to be logged to acess this section
@app.route('/profile/<email>')
@login_required
def profile(email):
user = User.query.filter_by(email=email).first()
return render_template('profile.html', user=user)
@app.route('/post_user', methods=['POST'])
def post_user():
user = User(request.form['email'], request.form['password'])
db.session.add(user) #add object
db.session.commit() #save
return redirect(url_for('index'))
if __name__=="__main__":
app.run()
答案 0 :(得分:1)
您必须传递命名参数才能实例化用户模型:
User(email=request.form['email'], password=request.form['password'])