python之Flask實現(xiàn)簡單登錄功能的示例代碼
網(wǎng)站少不了要和數(shù)據(jù)庫打交道,歸根到底都是一些增刪改查操作,這里做一個簡單的用戶登錄功能來學(xué)習(xí)一下Flask如何操作MySQL。
用到的一些知識點:Flask-SQLAlchemy、Flask-Login、Flask-WTF、PyMySQL
這里通過一個完整的登錄實例來介紹,程序已經(jīng)成功運行,在未登錄時攔截了success.html頁面跳轉(zhuǎn)到登錄頁面,登錄成功后才能訪問success。
以下是項目的整體結(jié)構(gòu)圖:

首先是配置信息,配置了數(shù)據(jù)庫連接等基本的信息,config.py
DEBUG = True SQLALCHEMY_ECHO = False SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:1011@localhost/rl_project?charset=utf8' SECRET_KEY = '*\xff\x93\xc8w\x13\x0e@3\xd6\x82\x0f\x84\x18\xe7\xd9\\|\x04e\xb9(\xfd\xc3'
common/_init_.py
# config=utf-8 from flask_sqlalchemy import SQLAlchemy __all__ = ['db'] db = SQLAlchemy()
數(shù)據(jù)庫配置類,common/data.py
# config=utf-8
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_ECHO
def db_query(sql, settings=None, echo=None):
if settings is None:
settings = SQLALCHEMY_DATABASE_URI
if echo is None:
echo = SQLALCHEMY_ECHO
return create_engine(settings, echo=echo).connect().execute(text(sql)).fetchall()
def db_execute(sql, settings=None, echo=None):
if settings is None:
settings = SQLALCHEMY_DATABASE_URI
if echo is None:
echo = SQLALCHEMY_ECHO
return create_engine(settings, echo=echo).connect().execute(text(sql)).rowcount
SQLALCHEMY_DATABASE_URI用于連接數(shù)據(jù)的數(shù)據(jù)庫。
SQLALCHEMY_ECHO如果設(shè)置成 True,SQLAlchemy 將會記錄所有 發(fā)到標準輸出(stderr)的語句,這對調(diào)試很有幫助。
當然,我們在setting中設(shè)置了基本的連接數(shù)據(jù)庫信息,啟動時加載app = create_app('../config.py'),所以這個類刪掉也不會報錯。
form/login_form.py
# config=utf-8
from flask_wtf import FlaskForm as Form
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired
class LoginForm(Form):
accountNumber = StringField('accountNumber', validators=[DataRequired('accountNumber is null')])
password = PasswordField('password', validators=[DataRequired('password is null')])
使用Flask-WTF做登錄的表單驗證,這里簡單做了賬號密碼不為空如,當我們不填寫密碼時,點擊登錄:

model/_init_.py
# config=utf-8
from flask import Flask
from flask_login import LoginManager
from common import db
login_manager = LoginManager()
login_manager.login_view = "user.login"
def create_app(config_filename=None):
app = Flask(__name__)
login_manager.init_app(app)
if config_filename is not None:
app.config.from_pyfile(config_filename)
configure_database(app)
return app
def configure_database(app):
db.init_app(app)
其中,login_manager.login_view = "user.login" 指定了未登錄時跳轉(zhuǎn)的頁面,即被攔截后統(tǒng)一跳到user/login這個路由下model/user_model.py
# config=utf-8
from flask_login import UserMixin
from common import db
class User(db.Model, UserMixin):
user_id = db.Column('id', db.Integer, primary_key=True)
accountNumber = db.Column(db.String(200), unique=True)
password = db.Column(db.String(50), unique=True)
name = db.Column(db.String(20), unique=True)
__tablename__ = 'tb_user'
def __init__(self, user_id=None, account_number=None, password=None, name="anonymous"):
self.user_id = user_id
self.accountNumber = account_number
self.password = password
self.name = name
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.user_id)
def __repr__(self):
return '<User %r>' % (self.accountNumber)
這里需要注意:
def get_id(self): return unicode(self.user_id)
該方法不可缺少,否則會報:NotImplementedError: No `id` attribute - override `get_id`錯誤。
get_id()
返回一個能唯一識別用戶的,并能用于從 user_loader 回調(diào)中 加載用戶的 unicode 。注意著 必須 是一個 unicode ——如果 ID 原本是 一個 int 或其它類型,你需要把它轉(zhuǎn)換為 unicode 。
is_authenticated()
當用戶通過驗證時,也即提供有效證明時返回 True
is_active()
如果這是一個通過驗證、已激活、未被停用的賬戶返回 True 。
is_anonymous()
如果是一個匿名用戶,返回 True 。
login.py
#encoding:utf-8
#!/usr/bin/env python
from flask import render_template, request, redirect, Flask, Blueprint
from flask_login import login_user, login_required
from model.user_model import User
from model import login_manager
from form.login_form import LoginForm
userRoute = Blueprint('user', __name__, url_prefix='/user', template_folder='templates', static_folder='static')
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@userRoute.before_request
def before_request():
pass
@userRoute.route('/success')
@login_required
def index():
return render_template('success.html')
@userRoute.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if request.method == 'POST':
if not form.validate_on_submit():
print form.errors
return render_template('login.html', form=form)
user = User.query.filter(User.accountNumber == form.accountNumber.data,
User.password == form.password.data).first()
if user:
login_user(user)
return render_template('success.html')
return render_template('login.html', form=form)
其中,要實現(xiàn)一個load_user()回調(diào)方法,這個回調(diào)用于從會話中存儲的用戶 ID 重新加載用戶對象,id存在則返回對應(yīng)的用戶對象,不存在則返回none。
有些操作是需要用戶登錄的,有些操作則無需用戶登錄,這里使用到了@login_required,在每一個需要登錄才能訪問的路由方法上加@login_required即可。
啟動類,runserver.py
# config=utf-8
from login import userRoute
from model import create_app
DEFAULT_MODULES = [userRoute]
app = create_app('../config.py')
for module in DEFAULT_MODULES:
app.register_blueprint(module)
@app.before_request
def before_request():
pass
if __name__ == '__main__':
app.run(debug=True)
DEFAULT_MODULES = [userRoute]是將userRoute藍圖注冊入app,才能啟動login中的userRoute路由,我們在login.py中使用了藍圖:userRoute = Blueprint('user', __name__, url_prefix='/user', template_folder='templates', static_folder='static')
@app.before_request def before_request(): pass
這是一個全局的方法,在請求開始之前被調(diào)用,在某些場景下做一些提示或者特殊處理,當然這里沒用上,直接pass,這個方法去掉對項目沒有影響?;緲邮侥0?,base.html
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<script src="{{ url_for('static', filename='jquery1.42.min.js') }}"></script>
{% block head %}{% endblock %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
登錄前臺頁面,login.html
{% extends "base.html" %}
{% block title %}python flask user page{% endblock %}
{% block head %}
<style type="text/css"></style>
{% endblock %}
{% block content %}
<form action="{{ url_for('user.login') }}" method="post">
{% if form.errors %}
<ul>
{% for name, errors in form.errors.items() %}
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
{% endif %}
賬號:{{ form.accountNumber(size=20) }}<label>{{ form.accountNumber.errors[0] }}</label><br/>
密碼:<input name="password" type="password"/><br/>
{{ form.hidden_tag() }}
<button type="submit">登錄</button>
</form>
{% endblock %}
到此,一個Flask實現(xiàn)簡單登錄功能就做完了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實現(xiàn)zencart產(chǎn)品數(shù)據(jù)導(dǎo)入到magento(python導(dǎo)入數(shù)據(jù))
這篇文章主要介紹了python實現(xiàn)zencart產(chǎn)品數(shù)據(jù)導(dǎo)入到magento(python導(dǎo)入數(shù)據(jù)),需要的朋友可以參考下2014-04-04
python中實現(xiàn)根據(jù)坐標點位置求方位角
這篇文章主要介紹了python中實現(xiàn)根據(jù)坐標點位置求方位角方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
Python Jupyter Notebook顯示行數(shù)問題的解決
這篇文章主要介紹了Python Jupyter Notebook顯示行數(shù)問題的解決方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
python 字符串和整數(shù)的轉(zhuǎn)換方法
今天小編就為大家分享一篇python 字符串和整數(shù)的轉(zhuǎn)換方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
python 根據(jù)正則表達式提取指定的內(nèi)容實例詳解
這篇文章主要介紹了python 根據(jù)正則表達式提取指定的內(nèi)容實例詳解的相關(guān)資料,需要的朋友可以參考下2016-12-12

