日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

基于Flask快速搭建一个管理系统

發布時間:2024/1/8 windows 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基于Flask快速搭建一个管理系统 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 用到的技術

1.1 導模塊

from flask import Flask, render_template, jsonify, redirect, request, url_for, session

1.2 模塊介紹

1.3 flask路由系統

1.3.1 普通使用

@app.route('/delete')

1.3.2 帶有名分組

@app.route('/edit/<string:nid>', methods=['GET', 'POST']) # 有名分組 默認string

1.3.3 帶請求限制

@app.route('/login', methods=['GET', 'POST']) # 默認支持get,需要手動添加post

1.3.4 帶別名,默認別名是函數名

@app.route('/index', endpoint='index') # 起別名,不寫默認函數名稱

1.3.5 路由其他參數(默認string)

DEFAULT_CONVERTERS = {'default': UnicodeConverter,'string': UnicodeConverter,'any': AnyConverter,'path': PathConverter,'int': IntegerConverter,'float': FloatConverter,'uuid': UUIDConverter, }

1.3.6?路由的本質

本質就是:app.add_url_rule()路由加載的源碼流程 -將ur1和函數打包成為rule對象 -將ru1e對象添加到map對象中。 - app.url_map = map對象endpoint:如果不寫默認是函數名,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參數

@app.route和app.add_url_rule參數: rule:URL規則 view_func:視圖函數名稱 defaults = None, 默認值, 當URL中無參數,函數需要參數時,使用defaults = {'k': 'v'} 為函數提供參數 endpoint = None, 名稱,用于反向生成URL,即: url_for('名稱') methods = None, 允許的請求方式,如:["GET", "POST"] #對URL最后的 / 符號是否嚴格要求,默認嚴格,False,就是不嚴格 strict_slashes = None'''@app.route('/index', strict_slashes=False)#訪問http://www.xx.com/index/ 或http://www.xx.com/index均可@app.route('/index', strict_slashes=True)#僅訪問http://www.xx.com/index''' #重定向到指定地址 redirect_to = None, '''@app.route('/index/<int:nid>', redirect_to='/home/<nid>')'''

1.4?獲取提交的數據

# 1. get請求 nid = request.args.get('nid') # 2. post請求 username = request.form.get('username')

1.5?返回數據

1.5.1 返回時的格式

return render_template('login.html', error='用戶名錯誤') return render_template('login.html', **{'error':'xxx','age':'xxx'})

1.5.2?坑1,出現找不到模板,解決辦法

  • 項目下面是否有templates文件夾,你的html文件是否放進了里面;
  • templates文件夾是否和你運行的py文件在同一級目錄;
  • render_template('***.html')這里面的名字是否正確,別打錯了;
  • app = Flask(__name__, template_folder='templates') 在最開始的這句話中,template_folder后面一定要跟上templates;

1.6?session&裝飾器

1.6.1 導入&使用

import functools from flask import session# flask使用session需要,傳入一個secret_key,flask會生成一個key返回給前端,類似于cookie存儲 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') # 起別名,不寫默認函數名稱 @auth def index():"""首頁"""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的請求處理是逐一封裝和傳遞;
  • flask的請求是利用上下文管理來實現的。

1.8 django/flask介紹

  • django是個大而全的框架,flask是一個輕量級的框架。 django內部為我們提供了非常多的組件:
orm / session / cookie / admin / form / modelform/路由/視圖/模板/中間件/分頁/ auth / contenttype/緩存/信號/多數據庫連接
  • ?flask框架本身沒有太多的功能:路由/視圖/模板(jinja2)/session/中間件,第三方組件非常齊全。

2. 快速搭建管理系統

2.1 基本使用

from flask import Flask# 起一個名字 app = Flask(__name__)# 配置路由 @app.route('/index') def index():return 'hello word'if __name__ == '__main__':# 啟動app.run()

2.2 完整版

2.2.1 py

import functools from flask import Flask, render_template, jsonify, redirect, request, url_for, sessionapp = Flask(__name__) # 默認 template_folder='templates' # 模擬數據 DATA_LIST = {'1': {'name': 'a', 'age': 32},'2': {'name': 'a', 'age': 64},} # flask使用session需要,傳入一個secret_key,flask會生成一個key返回給前端,類似于cookie存儲 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']) # 默認支持get,需要手動添加post def login():"""登錄"""# render_template, # 類似與django中國的render# jsonify, # 類似與django中國的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='用戶名錯誤')@app.route('/index', endpoint='index') # 起別名,不寫默認函數名稱 @auth def index():"""首頁"""return render_template('index.html', data_dict=DATA_LIST)@app.route('/edit/<string:nid>', methods=['GET', 'POST']) # 有名分組 默認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管理系統</h3></div><div class="panel-body"><table class="table table-hover"><thead><tr><th>序號</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. 截圖

總結

以上是生活随笔為你收集整理的基于Flask快速搭建一个管理系统的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。