如何使用peewee创建Flask登录页面?

时间:2019-07-19 08:48:51

标签: python flask peewee

我为什么在这里

我正在寻找一个简单的烧瓶登录身份验证系统,该系统使用peewee和flask_login的login_required模块。我已经知道,除了使用“ login_user()”进行身份验证外,其他一切似乎都可以正常工作,并检查表单中的正确字段。在服务器端,请求看起来像通过了。但是,当我在网页上提交时,除了控制台中的POST 200代码外,什么都没有发生。

我尝试将peewee直接输入我的app.py中,并将数据库用户手动加载到所需部分中,然后成功将其重定向到下一页。不过,当我尝试此操作时,@login_required页上仍未对其进行授权,即使是这样,它也总是会自动进行。

文件方案:

app.py
 UserManager.py
 Users.db 
 Temlates/
    login.html

app.py

from form import *
from flask import *
from UserManager import *
from flask_login import LoginManager, login_required, login_user, logout_user, UserMixin

# Host config
host = "127.0.0.1"
port = 8000
hostname = host + str(port)

# App config
app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)
app.secret_key = 'dev'

# Routing
@app.route('/')
def hello():
    return redirect(url_for('login'))

@login_manager.user_loader
def load_user(id):
    return get_username(id)

@app.route('/login', methods=['GET', 'POST'])
def login_page():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username == get_username(username) and password == get_password(password):
            login_user(get_username(username))
            return redirect(url_for('index'))
        else:
            error = 'Invalid Credentials. Please try again.'
    return render_template('login.html', error=error)

@app.route('/logout')
def logout_page():
    logout_user()
    return "Logged Out"

@app.route('/index')
@login_required
def index():
    return "Authenticated"

# Run
if __name__ == "__main__":
    print(' * Testing Server', flush=True)
    app.run(host, port, debug=True)

UserManager.py

from peewee import *
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin

db = SqliteDatabase(
'C:/path/to/Users.db')

class User(Model, UserMixin):
    username = CharField(unique=True)
    password = CharField(unique=True)
    class Meta:
        database = db

db.connect()
db.create_tables([User], safe = True)

def create_user(username, password):
    try:
        User.create(
        username=username,
        password=generate_password_hash(password))
    except IntegrityError:
        print("User already exists")

def delete_user(user_id):
    try:
        user = User.get(User.username == user_id)
        user.delete_instance()
        print(user_id + " deleted")
    except User.DoesNotExist:
        print('no such user')

def list_users():
    try:
        print('Users: '),
        for person in User.select():
            print(person.username),
    except:
        print('no users')

def remake_user(username, password):
    delete_user(username)
    create_user(username, password)
    print(username + ' remade')

def get_username(data):
    return User.get(User.username == data)

def get_password(data):
    return User.get(User.password == data)

db.close()

login.html

<html>
  <head>
    <title>login page</title>
  </head>
  <body>
    <div class="container">
      <h1>Please login</h1>
      <br>
      <form action="" method="post">
         <input type="text" placeholder="Username" name="username" value="{{
          request.form.username }}">
         <input type="password" placeholder="Password" name="password" value="{{
          request.form.password }}">
         <input type="submit" value="Login">
      </form>
    </div>
  </body>
</html>

0 个答案:

没有答案