您好,登錄后才能下訂單哦!
符合一下關(guān)鍵詞,這篇博客有可能會對你有幫助
這是一篇個人博客搭建的記錄博客,也是一篇關(guān)于Flask和Vue的簡單"工具書",最后的代碼會包含Web開發(fā)中常用的功能。(不全,只是使用頻率相對高的)
《Flask Web開發(fā) 基于Python的Web應(yīng)用開發(fā)實戰(zhàn)》
Vue.js
個人博客的解決方案那么多,為什么我要自己再搭建一個呢?
其實搭建個人博客的目的并不是為了寫博客...否則直接使用WordPress了,個人博客只是我想要實踐自己學(xué)的技術(shù),同時考慮到以后可能會加入負(fù)載均衡、集群等技術(shù),導(dǎo)致架構(gòu)大改,或者嘗試實現(xiàn)語音控制等新玩法,一行一行碼出來的在操作的可行性上必然是更好的。
博客功能尚不健全,只實現(xiàn)了以下的基本功能
前端:注冊登陸,博客創(chuàng)建(markdown編輯器),首頁拉取所有文章,創(chuàng)建博客需要登陸狀態(tài)。
后端:以上服務(wù)需要的視圖函數(shù),配置跨域,令牌管理與驗證,數(shù)據(jù)庫管理。
出于記錄的分享的目的,將實現(xiàn)登錄狀態(tài)管理的代碼整理如下
要實現(xiàn)基于令牌的登錄狀態(tài)管理,其思路大致如下
這是一個大致的思路,后續(xù)調(diào)用手保護(hù)的視圖函數(shù)部分,無論是讓前后端完成什么操作,都可以執(zhí)行根據(jù)需要實現(xiàn)。
以下部分將根據(jù)以上思路的順序,展示主要代碼,最后將貼出完成代碼。
前后端分離首選需要配置跨域,此處采用后端解決的方案,使用flask_cors庫,代碼如下:
由于會前端在獲取token后會在每次HTTP請求時將token設(shè)置在頭部,我給出的命名為'token',若使用了其他名稱,需在'Access-Control-Allow-Headers'中替換
from flask_cors import CORS
CORS(app,supports_credentials=True)
@app.after_request
def after_request(resp):
resp = make_response(resp)
resp.headers['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
resp.headers['Access-Control-Allow-Headers'] = 'content-type,token'
return resp
前端將獲取的帳號密碼傳遞給后臺,將請求獲取的token寫入Vuex中。(Vuex中會將token寫入localStorage)
let _this = this
axios.post('http://127.0.0.1:5000/login',{
username:this.username,
password:this.password,
})
.then(function(response){
let token = response.data
_this.changeLogin({Authorization: token})
})
.catch(function(error){
})
視圖函數(shù)將通過用戶名和密碼,驗證用戶信息,并生成token,返回token。
# Routes
@app.route('/login',methods=['POST'])
def login():
json = request.get_json()
user = User.query.filter_by(username = json['username']).first()
if user.verify_password(json['password']):
g.currnet_user = user
token = user.generate_auth_token(expiration=3600)
return token
return "wrong password"
配置Axios鉤子,在每次HTTP請求的頭部都添加token
axios.interceptors.request.use(
config => {
let token = localStorage.getItem('Authorization');
if(token){
config.headers.common['token'] = token
}
return config
},
err => {
return Promise.reject(err);
});
flask_httpauth模塊實現(xiàn)的功能很少,其核心部分是我們需要自己實現(xiàn)@auth.verify_password這個回調(diào)函數(shù),當(dāng)被@auth.login_required修飾的視圖函數(shù)被訪問時,會先執(zhí)行回調(diào)函數(shù),在回調(diào)函數(shù)中將獲取http頭部的token,并驗證該token是否合法,若合法則允許訪問。
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
@auth.verify_password
def verify_password(username_token):
username_token = request.headers.get('Token')
if username_token == '':
return False
else:
g.currnet_user = User.verify_auth_token(username_token)
g.token_used = True
return g.currnet_user is not None
@auth.login_required
@app.route('/creatpost',methods=['POST'])
def new_post():
json = request.get_json()
newpost = Post(title=json['title'],content=json['content'])
db.session.add(newpost)
db.session.commit()
return "200 OK"
以上部分即是實現(xiàn)基于令牌管理的代碼核心部分,閱讀以上代碼知曉思路即可,由于其還調(diào)用了諸如ORM中的函數(shù)的原因,所以只有以上部分代碼功能并不健全,請參考下面簡化后的完整代碼。
強調(diào):以下代碼出于簡化的目的,皆為實現(xiàn)功能的最基本碼,并沒有遵循各種規(guī)范。
import os
from flask import Flask,make_response,render_template,redirect,url_for,jsonify,g,current_app,request,session
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth
from flask_login import login_user,UserMixin,LoginManager,login_required
from werkzeug.security import generate_password_hash,check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
basedir = os.path.abspath(os.path.dirname(__file__))
# SQLite
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret-key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# CORS
CORS(app,supports_credentials=True)
@app.after_request
def after_request(resp):
resp = make_response(resp)
resp.headers['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
resp.headers['Access-Control-Allow-Headers'] = 'content-type,token'
return resp
# Http auth
auth = HTTPBasicAuth()
@auth.verify_password
def verify_password(username_token):
username_token = request.headers.get('Token')
if username_token == '':
return False
else:
g.currnet_user = User.verify_auth_token(username_token)
g.token_used = True
return g.currnet_user is not None
@auth.error_handler
def auth_error():
return unauthorized('Invalid credentials')
# Routes
@app.route('/login',methods=['POST'])
def login():
json = request.get_json()
user = User.query.filter_by(username = json['username']).first()
if user.verify_password(json['password']):
g.currnet_user = user
token = user.generate_auth_token(expiration=3600)
return token
return "wrong password"
@app.route('/register',methods=['POST'])
def register():
json = request.get_json()
email = json['username'] + '@email.com'
user = User(email=email,username=json['username'],password=json['password'])
db.session.add(user)
db.session.commit()
return "200 OK register"
@app.route('/postlist')
def article():
ptemp = Post.query.all()
return jsonify({
'posts': [post.to_json() for post in ptemp],
})
@auth.login_required
@app.route('/creatpost',methods=['POST'])
def new_post():
json = request.get_json()
newpost = Post(title=json['title'],content=json['content'])
db.session.add(newpost)
db.session.commit()
return "200 OK"
def unauthorized(message):
response = jsonify({'error': 'unauthorized', 'message': message})
response.status_code = 401
return response
# ORM
class User(UserMixin,db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64),unique=True,index=True)
username = db.Column(db.String(64),unique=True,index=True)
password_hash = db.Column(db.String(128))
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self,password):
self.password_hash = generate_password_hash(password)
def verify_password(self,password):
return check_password_hash(self.password_hash,password)
def generate_auth_token(self,expiration):
s = Serializer(current_app.config['SECRET_KEY'],expires_in = expiration)
return s.dumps({'id':self.id}).decode('utf-8')
@staticmethod
def verify_auth_token(token):
s = Serializer(current_app.config['SECRET_KEY'])
try:
data = s.loads(token)
except:
return None
return User.query.get(data['id'])
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(64),unique=True,index=True)
content = db.Column(db.String(64))
def to_json(self):
json_post = {
'title': self.title,
'content': self.content,
}
return json_post
if __name__ == '__main__':
db.drop_all()
db.create_all()
app.run()
import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import router from './router';
import iView from 'iview';
import 'iview/dist/styles/iview.css';
import axios from 'axios';
import vueAxios from 'vue-axios';
import store from './store';
import Vuex from 'vuex'
Vue.config.productionTip = false
Vue.use(VueRouter)
Vue.use(iView)
Vue.use(vueAxios,axios)
Vue.use(Vuex)
router.afterEach(route=>{
window.scroll(0,0);
})
router.beforeEach((to,from,next)=>{
let token = localStorage.getItem('Authorization');
if(!to.meta.isLogin){
next()
}else{
let token = localStorage.getItem('Authorization');
if(token == null || token == ''){
next('/')
}else{
next()
}
}
})
axios.interceptors.request.use(
config => {
let token = localStorage.getItem('Authorization');
if(token){
config.headers.common['token'] = token
}
return config
},
err => {
return Promise.reject(err);
});
new Vue({
el:'#app',
render: h => h(App),
router,
store,
})
import Vue from 'vue';
import Vuex from 'vuex';
import store from './index';
Vue.use(Vuex);
export default new Vuex.Store({
state:{
Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : ''
},
mutations:{
changeLogin (state, user) {
state.Authorization = user.Authorization;
localStorage.setItem('Authorization', user.Authorization);
}
},
})
import Vue from 'vue'
import Router from 'vue-router'
import home from '../components/home.vue'
import articleDetail from '../components/articleDetail'
import createPost from '../components/createPost'
Vue.use(Router)
export default new Router({
mode:'history',
routes:[
{
path:'/',
component:home,
name:'home',
meta:{
isLogin:false
}
},
{
path:'/article',
component:articleDetail,
name:'article',
meta:{
isLogin:false
}
},
{
path:'/createpost',
component:createPost,
name:'createpost',
meta:{
isLogin:true
}
},
]
})
<template>
<div class="super">
<div class="header">
<div class="buttomDiv">
<Button type="success" class="loginButton" @click="showLoginModal">Login</Button>
<Button type="primary" class="loginButton" @click="showRegisterModal">Register</Button>
</div>
</div>
<div class = "content">
<div class="contentLeft">
<div
v-for = "post in blogList"
>
<thumbnail
v-bind:title=post.title
v-bind:content=post.content
></thumbnail>
</div>
</div>
<div class="contentRight"></div>
</div>
<Modal v-model="registerModalStatus" @on-ok="registerEvent">
<p>Register</p>
<Input v-model="username" placeholder="Username" />
<Input v-model="password" placeholder="Password" />
</Modal>
<Modal v-model="loginModalStatus" @on-ok="loginEvent">
<p>Login</p>
<Input v-model="username" placeholder="Username" />
<Input v-model="password" placeholder="Password" />
</Modal>
</div>
</template>
<script>
import axios from 'axios'
import {mapMutations} from 'vuex'
import store from '../store'
import thumbnail from './articleThumbnail.vue'
export default{
name: 'home',
data:function(){
return {
loginModalStatus:false,
registerModalStatus:false,
username:'',
password:'',
blogList:'',
}
},
components:{
thumbnail:thumbnail,
},
created(){
localStorage.removeItem("Authorization","")
let _this = this
axios.get('http://127.0.0.1:5000/postlist')
.then(function(response){
_this.blogList = response.data.posts
})
.catch(function(error){
})
},
methods:{
...mapMutations([
'changeLogin'
]),
showRegisterModal:function(){
this.registerModalStatus = true;
},
showLoginModal:function(){
this.loginModalStatus = true;
},
registerEvent:function(){
let that = this
axios.post('http://127.0.0.1:5000/register',{
username:this.username,
password:this.password,
})
.then(function(res){
})
.catch(function(error){
})
},
loginEvent:function(){
let _this = this
axios.post('http://127.0.0.1:5000/login',{
username:this.username,
password:this.password,
})
.then(function(response){
let token = response.data
_this.changeLogin({Authorization: token})
})
.catch(function(error){
})
},
navigator:function(){
this.$router.push("/article")
},
},
}
</script>
<style scoped>
</style>
完整代碼github地址
haythamBlog
haythamBlog_flask
####
要獲取更多Haytham原創(chuàng)文章,請關(guān)注公眾號"許聚龍":
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。