基于Flask快速搭建一个管理系统
生活随笔
收集整理的這篇文章主要介紹了
基于Flask快速搭建一个管理系统
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 用到的技術(shù)
1.1 導(dǎo)模塊
from flask import Flask, render_template, jsonify, redirect, request, url_for, session1.2 模塊介紹
1.3 flask路由系統(tǒng)
1.3.1 普通使用
@app.route('/delete')1.3.2 帶有名分組
@app.route('/edit/<string:nid>', methods=['GET', 'POST']) # 有名分組 默認(rèn)string1.3.3 帶請(qǐng)求限制
@app.route('/login', methods=['GET', 'POST']) # 默認(rèn)支持get,需要手動(dòng)添加post1.3.4 帶別名,默認(rèn)別名是函數(shù)名
@app.route('/index', endpoint='index') # 起別名,不寫默認(rèn)函數(shù)名稱1.3.5 路由其他參數(shù)(默認(rèn)string)
DEFAULT_CONVERTERS = {'default': UnicodeConverter,'string': UnicodeConverter,'any': AnyConverter,'path': PathConverter,'int': IntegerConverter,'float': FloatConverter,'uuid': UUIDConverter, }1.3.6?路由的本質(zhì)
本質(zhì)就是:app.add_url_rule()路由加載的源碼流程 -將ur1和函數(shù)打包成為rule對(duì)象 -將ru1e對(duì)象添加到map對(duì)象中。 - app.url_map = map對(duì)象endpoint:如果不寫默認(rèn)是函數(shù)名,endpoint不能重名# 一般使用第一種 @app.route('/index') def index():return render_template(' index.html ')# 第二種 def home():return render_template(' index.html ') app.add_url_rule('/home', 'home', home)|1.3.7?app.add_url_rule參數(shù)
@app.route和app.add_url_rule參數(shù): rule:URL規(guī)則 view_func:視圖函數(shù)名稱 defaults = None, 默認(rèn)值, 當(dāng)URL中無(wú)參數(shù),函數(shù)需要參數(shù)時(shí),使用defaults = {'k': 'v'} 為函數(shù)提供參數(shù) endpoint = None, 名稱,用于反向生成URL,即: url_for('名稱') methods = None, 允許的請(qǐng)求方式,如:["GET", "POST"] #對(duì)URL最后的 / 符號(hào)是否嚴(yán)格要求,默認(rèn)嚴(yán)格,False,就是不嚴(yán)格 strict_slashes = None'''@app.route('/index', strict_slashes=False)#訪問(wèn)http://www.xx.com/index/ 或http://www.xx.com/index均可@app.route('/index', strict_slashes=True)#僅訪問(wèn)http://www.xx.com/index''' #重定向到指定地址 redirect_to = None, '''@app.route('/index/<int:nid>', redirect_to='/home/<nid>')'''1.4?獲取提交的數(shù)據(jù)
# 1. get請(qǐng)求 nid = request.args.get('nid') # 2. post請(qǐng)求 username = request.form.get('username')1.5?返回?cái)?shù)據(jù)
1.5.1 返回時(shí)的格式
return render_template('login.html', error='用戶名錯(cuò)誤') return render_template('login.html', **{'error':'xxx','age':'xxx'})1.5.2?坑1,出現(xiàn)找不到模板,解決辦法
- 項(xiàng)目下面是否有templates文件夾,你的html文件是否放進(jìn)了里面;
- templates文件夾是否和你運(yùn)行的py文件在同一級(jí)目錄;
- render_template('***.html')這里面的名字是否正確,別打錯(cuò)了;
- app = Flask(__name__, template_folder='templates') 在最開(kāi)始的這句話中,template_folder后面一定要跟上templates;
1.6?session&裝飾器
1.6.1 導(dǎo)入&使用
import functools from flask import session# flask使用session需要,傳入一個(gè)secret_key,flask會(huì)生成一個(gè)key返回給前端,類似于cookie存儲(chǔ) app.secret_key = 'lfsakhfnednlasdjmcls'def auth(func):@functools.wraps(func)def inner(*args, **kwargs):if session.get('username'):# print(session.get('username'))ret = func(*args, **kwargs)return retreturn redirect(url_for('login'))return inner@app.route('/index', endpoint='index') # 起別名,不寫默認(rèn)函數(shù)名稱 @auth def index():"""首頁(yè)"""return render_template('index.html', data_dict=DATA_LIST)1.6.2 裝飾器的使用方法
@app.before_requestdef def func():print('xxx')def x1():print('xxx') x1.app.before_request(x1)1.7 request介紹
- django的請(qǐng)求處理是逐一封裝和傳遞;
- flask的請(qǐng)求是利用上下文管理來(lái)實(shí)現(xiàn)的。
1.8 django/flask介紹
- django是個(gè)大而全的框架,flask是一個(gè)輕量級(jí)的框架。 django內(nèi)部為我們提供了非常多的組件:
- ?flask框架本身沒(méi)有太多的功能:路由/視圖/模板(jinja2)/session/中間件,第三方組件非常齊全。
2. 快速搭建管理系統(tǒng)
2.1 基本使用
from flask import Flask# 起一個(gè)名字 app = Flask(__name__)# 配置路由 @app.route('/index') def index():return 'hello word'if __name__ == '__main__':# 啟動(dòng)app.run()2.2 完整版
2.2.1 py
import functools from flask import Flask, render_template, jsonify, redirect, request, url_for, sessionapp = Flask(__name__) # 默認(rèn) template_folder='templates' # 模擬數(shù)據(jù) DATA_LIST = {'1': {'name': 'a', 'age': 32},'2': {'name': 'a', 'age': 64},} # flask使用session需要,傳入一個(gè)secret_key,flask會(huì)生成一個(gè)key返回給前端,類似于cookie存儲(chǔ) app.secret_key = 'lfsakhfnednlasdjmcls'def auth(func):@functools.wraps(func)def inner(*args, **kwargs):if session.get('username'):# print(session.get('username'))ret = func(*args, **kwargs)return retreturn redirect(url_for('login'))return inner@app.route('/login', methods=['GET', 'POST']) # 默認(rèn)支持get,需要手動(dòng)添加post def login():"""登錄"""# render_template, # 類似與django中國(guó)的render# jsonify, # 類似與django中國(guó)的JsonResponse# url_for 別名if request.method == 'GET':return render_template('login.html')username = request.form.get('username')password = request.form.get('password')if username == '1' and password == '1':session['username'] = usernamereturn redirect('/index')return render_template('login.html', error='用戶名錯(cuò)誤')@app.route('/index', endpoint='index') # 起別名,不寫默認(rèn)函數(shù)名稱 @auth def index():"""首頁(yè)"""return render_template('index.html', data_dict=DATA_LIST)@app.route('/edit/<string:nid>', methods=['GET', 'POST']) # 有名分組 默認(rèn)string @auth def edit(nid):"""編輯"""if request.method == 'GET':user_dic = DATA_LIST.get(nid)# print(user_dic) # {'name': 'a', 'age': 32}return render_template('edit.html', user_dic=user_dic)name = request.form.get('username')age = request.form.get('age')DATA_LIST[nid]['name'] = nameDATA_LIST[nid]['age'] = agereturn redirect('/index')@app.route('/delete') @auth def delete():"""刪除"""nid = request.args.get('nid')print(nid) # 2del DATA_LIST[nid]return redirect(url_for('index'))if __name__ == '__main__':app.run()2.2.2?login.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>登錄</title> </head> <body> <form method="post"><p>用戶名:<input type="text" name="username"></p><p>密碼:<input type="password" name="password"></p>{{ error }}<input type="submit" value="提交"> </form> </body> </html>2.2.3?index.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div><div class="bs-example" data-example-id="hoverable-table"><div class="panel panel-info"><div class="panel-heading"><h3 class="panel-title">xx管理系統(tǒng)</h3></div><div class="panel-body"><table class="table table-hover"><thead><tr><th>序號(hào)</th><th>名稱</th><th>年齡</th><th>操作</th></tr></thead><tbody>{% for key,item in data_dict.items() %}<tr><th scope="row">{{ key }}</th><td>{{ item.name }}</td><td>{{ item["age"] }}</td><td><a href="/edit/{{ key }}">編輯</a>|<a href="/delete?nid={{ key }}">刪除</a></td></tr>{% endfor %}</tbody></table></div></div></div> </div> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> </body> </html>2.2.4?edit.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>編輯</title> </head> <body> <form method="post"><p>用戶名:<input type="text" name="username" value="{{ user_dic.name }}"></p><p>密碼:<input type="text" name="age" value="{{ user_dic.age }}"></p><input type="submit" value="提交"> </form> </body> </html>3. 截圖
總結(jié)
以上是生活随笔為你收集整理的基于Flask快速搭建一个管理系统的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 乐筑加速推进绿色建筑理念执行落地
- 下一篇: 四种方法解决:Windows10下使用S