0%

flask-login

flas-login

1. 原理

1.1 首次登陆

1.2 第二次登陆

2 实现

2.1 操作数据库

首先给定数据库信息

结构

传统的数据库表是一个二维表。而SQLAlchemy使用对象来表示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 传统的
[
('1', 'Michael'),
('2', 'Bob'),
('3', 'Adam')
]
# SQLAlchemy
class User(object):
def __init__(self, id, name):
self.id = id
self.name = name

[
User('1', 'Michael'),
User('2', 'Bob'),
User('3', 'Adam')
]

用法

直接用法

直接

flask中的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
# 引擎 数据库://username:[email protected]/database
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:[email protected]/taskt"
# 创建对象
db = SQLAlchemy(app)
# 定义用户模型
class User(UserMixin, db.Model):
__tablename__ = 'user'
userid = db.Column('userid', Integer, primary_key=True)
username = db.Column('username', String(30), unique=True)
email = db.Column('email', String(50), unique=True)
password = db.Column('password', String(100), unique=False)

def __init__(self, username, password, email=None):
self.username = username
self.password = password
self.email = email

def is_authenticated(self):
return True

# 获取数据
username = form.username.data
password = form.password.data
email = form.email.data
# 添加数据
db.session.add(User(username=username, password=password, email=email))
db.session.commit()
# 查询数据
db_pass_user = User.query.filter_by(username=username).first()

2.2 flask-login

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/env python

# encoding: utf-8
from flask import Flask, Blueprint, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Integer, String

from flask_login import (LoginManager, login_required, login_user,

logout_user, UserMixin, )
from wtforms import StringField, PasswordField, SubmitField, Form
from flask_cors import CORS

app = Flask(__name__)
CORS(app, supports_credentials=True)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:[email protected]/taskt"
db = SQLAlchemy(app)


class LoginForm(Form):
username = StringField('username')
password = PasswordField('password')
email = StringField('email')
submit = SubmitField('submit')


# user models

class User(UserMixin, db.Model):
__tablename__ = 'user'
userid = db.Column('userid', Integer, primary_key=True)
username = db.Column('username', String(30), unique=True)
email = db.Column('email', String(50), unique=True)
password = db.Column('password', String(100), unique=False)

def __init__(self, username, password, email=None):
self.username = username
self.password = password
self.email = email

def is_authenticated(self):
return True

def is_actice(self):
return True

def is_anonymous(self):
return False

def get_id(self):
return str(self.userid) # User.query.filter_by(username=self.username).first().userid

def __repr__(self):
return '<%s %s>' % (self.username, self.password)


# flask-login
app.secret_key = 's3cr3t'
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'
login_manager.init_app(app)


@login_manager.user_loader
def load_user(user_id):
print("user_id: " + user_id)
return User.query.filter_by(userid=user_id).first()


@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
username = form.email.data
password = form.password.data
db_pass_user = User.query.filter_by(username=username).first()

if db_pass_user and db_pass_user.password == password:

login_user(db_pass_user)
return render_template("home.html", data=db_pass_user)
else:
return "wrong username/password "
else:
return render_template("login.html", form=form)


@app.route("/register", methods=['POST', 'GET'])
def register():
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
username = form.username.data
password = form.password.data
email = form.email.data
db.session.add(User(username=username, password=password, email=email))
db.session.commit()
return "success"


@app.route("/")
@app.route("/index")
def index():
return render_template("/index.html", form=LoginForm()) # redirect('/login')


@app.route('/logout', methods=['GET', 'POST'])
@login_required
def logout():
logout_user()

return "logout page"


# test method

@app.route('/test')
@login_required
def test():
return "yes , you are allowed"


app.run(debug=True)

3 跨域问题

1
2
from flask_cors import CORS
CORS(app, supports_credentials=True)