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

首先是配置信息,配置了數(shù)據(jù)庫(kù)連接等基本的信息,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ù)庫(kù)配置類(lèi),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ù)庫(kù)。
SQLALCHEMY_ECHO如果設(shè)置成 True,SQLAlchemy 將會(huì)記錄所有 發(fā)到標(biāo)準(zhǔn)輸出(stderr)的語(yǔ)句,這對(duì)調(diào)試很有幫助。
當(dāng)然,我們?cè)趕etting中設(shè)置了基本的連接數(shù)據(jù)庫(kù)信息,啟動(dòng)時(shí)加載app = create_app('../config.py'),所以這個(gè)類(lèi)刪掉也不會(huì)報(bào)錯(cuò)。
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做登錄的表單驗(yàn)證,這里簡(jiǎn)單做了賬號(hào)密碼不為空如,當(dāng)我們不填寫(xiě)密碼時(shí),點(diǎn)擊登錄:

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" 指定了未登錄時(shí)跳轉(zhuǎn)的頁(yè)面,即被攔截后統(tǒng)一跳到user/login這個(gè)路由下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)
該方法不可缺少,否則會(huì)報(bào):NotImplementedError: No `id` attribute - override `get_id`錯(cuò)誤。
get_id()
返回一個(gè)能唯一識(shí)別用戶的,并能用于從 user_loader 回調(diào)中 加載用戶的 unicode 。注意著 必須 是一個(gè) unicode ——如果 ID 原本是 一個(gè) int 或其它類(lèi)型,你需要把它轉(zhuǎn)換為 unicode 。
is_authenticated()
當(dāng)用戶通過(guò)驗(yàn)證時(shí),也即提供有效證明時(shí)返回 True
is_active()
如果這是一個(gè)通過(guò)驗(yàn)證、已激活、未被停用的賬戶返回 True 。
is_anonymous()
如果是一個(gè)匿名用戶,返回 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)
其中,要實(shí)現(xiàn)一個(gè)load_user()回調(diào)方法,這個(gè)回調(diào)用于從會(huì)話中存儲(chǔ)的用戶 ID 重新加載用戶對(duì)象,id存在則返回對(duì)應(yīng)的用戶對(duì)象,不存在則返回none。
有些操作是需要用戶登錄的,有些操作則無(wú)需用戶登錄,這里使用到了@login_required,在每一個(gè)需要登錄才能訪問(wèn)的路由方法上加@login_required即可。
啟動(dòng)類(lèi),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藍(lán)圖注冊(cè)入app,才能啟動(dòng)login中的userRoute路由,我們?cè)趌ogin.py中使用了藍(lán)圖:userRoute = Blueprint('user', __name__, url_prefix='/user', template_folder='templates', static_folder='static')
@app.before_request def before_request(): pass
這是一個(gè)全局的方法,在請(qǐng)求開(kāi)始之前被調(diào)用,在某些場(chǎng)景下做一些提示或者特殊處理,當(dāng)然這里沒(méi)用上,直接pass,這個(gè)方法去掉對(duì)項(xiàng)目沒(méi)有影響?;緲邮侥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>
登錄前臺(tái)頁(yè)面,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 %}
賬號(hào):{{ 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 %}
到此,一個(gè)Flask實(shí)現(xiàn)簡(jiǎn)單登錄功能就做完了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python Flask基礎(chǔ)到登錄功能的實(shí)現(xiàn)代碼
- python+flask編寫(xiě)一個(gè)簡(jiǎn)單的登錄接口
- Python Flask微信小程序登錄流程及登錄api實(shí)現(xiàn)代碼
- python使用Flask操作mysql實(shí)現(xiàn)登錄功能
- 使用Python的Flask框架表單插件Flask-WTF實(shí)現(xiàn)Web登錄驗(yàn)證
- Python的Flask框架應(yīng)用程序?qū)崿F(xiàn)使用QQ賬號(hào)登錄的方法
- Python的Flask框架中實(shí)現(xiàn)登錄用戶的個(gè)人資料和頭像的教程
- Python Flask前端自動(dòng)登錄功能實(shí)現(xiàn)詳解
相關(guān)文章
利用Python?實(shí)現(xiàn)分布式計(jì)算
這篇文章主要介紹了利用Python?實(shí)現(xiàn)分布式計(jì)算,文章通過(guò)借助于?Ray展開(kāi)對(duì)分布式計(jì)算的實(shí)現(xiàn),感興趣的小伙伴可以參考一下2022-05-05
python實(shí)現(xiàn)zencart產(chǎn)品數(shù)據(jù)導(dǎo)入到magento(python導(dǎo)入數(shù)據(jù))
這篇文章主要介紹了python實(shí)現(xiàn)zencart產(chǎn)品數(shù)據(jù)導(dǎo)入到magento(python導(dǎo)入數(shù)據(jù)),需要的朋友可以參考下2014-04-04
python中實(shí)現(xiàn)根據(jù)坐標(biāo)點(diǎn)位置求方位角
這篇文章主要介紹了python中實(shí)現(xiàn)根據(jù)坐標(biāo)點(diǎn)位置求方位角方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Python Jupyter Notebook顯示行數(shù)問(wèn)題的解決
這篇文章主要介紹了Python Jupyter Notebook顯示行數(shù)問(wèn)題的解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
python 字符串和整數(shù)的轉(zhuǎn)換方法
今天小編就為大家分享一篇python 字符串和整數(shù)的轉(zhuǎn)換方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
Python爬蟲(chóng)框架之Scrapy中Spider的用法
今天給大家?guī)?lái)的是關(guān)于Python爬蟲(chóng)的相關(guān)知識(shí),文章圍繞著Scrapy中Spider的用法展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
Django通過(guò)設(shè)置CORS解決跨域問(wèn)題
這篇文章主要介紹了Django 通過(guò)設(shè)置CORS解決跨域問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
python 根據(jù)正則表達(dá)式提取指定的內(nèi)容實(shí)例詳解
這篇文章主要介紹了python 根據(jù)正則表達(dá)式提取指定的內(nèi)容實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2016-12-12

