Flask-01 基本組成, 專案拆分
本文主要介紹如何開始一個Flask專案, 以及更具Flask的豐富的拓展包, 來拆分專案, 讓一個Flask專案滿足基本的MVC架構, 下面就開始進入正文.
Flask是一種使用Python編寫的輕量級的Web框架, WSGI工具採用Werkzeug,模板引擎使用Jinja2, Flask使用的是BSD授權
Flask核心簡單, 可以自定義擴充套件, 沒有固定的資料庫和模板等設定, 簡單輕便
Flask也有web開發'微'框架之稱
開始專案
下面是官網中的一個Flask專案, 只需要簡單的7行程式碼, 我們就是可以讓一個Flask專案執行起來
Flask由於框架體量小, 所有的拓展包都需要我們自己去安裝, 所以一個Flask專案會安裝很多的拓展包是很常見的
最簡單的一個Flask專案
from flask import Flask app = Flask(__name__) route('/') .def hello(): return 'hello' if __name__ == '__main__': main()
拆分
基於專案的可拓展性和程式碼的可閱讀性, 當代碼量較大時, 將所有的程式碼寫在一個檔案中是一件很可怕的事, 所以我們就要對其進行拆分, 主要還是參考 MVC模式進行, 將不同的功能放在其對應的模組中, 方便我們進行閱讀
將主要的執行內容寫在執行檔案manage.py中, 引入 Manage 進行管理app
建立app的檔案目錄, 將views 和 models 寫入其中進行管理
建立 static 目錄,存放靜態檔案
建立 templates 目錄, 存放網頁模板
建立utils 目錄, 管理工具函式
Manger管理app
from flask_script import Manager from utils.functions import create_app app = create_app() manage = Manager(app=app) if __name__ == '__main__': manage.run()
views定義路由和控制器
需要藍圖
blueprint
from flask import Blueprint user_buleprint = Blueprint('user', __name__) # 'user'在重定向時使用 route('/') # 設定路由, 訪問的url .def index(): return render_template('index.html') # 返回渲染的模板頁面 # 帶引數返回 route('/') .def index(): content = '' return render_template('index.html', content=content)
註冊藍圖
utils.functions.py
from flask import Flask def create_app(): app = Flask(__name__) # 註冊藍圖, 設定url 字首, 相當於 django中的 namespace app.register_blueprint(blueprint=user_buleprint, url_prefix='/user') return app
設定靜態檔案目錄和模板目錄
def create_app(): BASE_DIR = os.path.dirname(os.path.dirname(__file__)) static_dir = os.path.join(BASE_DIR, 'static') templates_dir = os.path.join(BASE_DIR, 'templates') # 初始化 app app = Flask(__name__, static_folder=static_dir, template_folder=templates_dir) return app
檢視函式
路由
@app.route('/')
客戶端傳送請求給伺服器(瀏覽器到伺服器), 進而請求傳遞到Flask的應用例項,應用例項需要知道對於各個URL請求需要執行哪部分程式碼, 所以它給Python函式建立了一個URLs對映, 這種在URL和函式之間建立聯絡的操作稱之為路由
route規則
在@app.route('/<int:name>')
string 字串 預設
int 整形
float 浮點型
path 路徑
uuid uuid字串
any 任何,無限制
對同一個模板,通過url中傳遞的引數型別不同來執行不同的檢視函式進行渲染
from flask import render_template, request, Blueprint blue = Blueprint('first', __name__) route('/hello/') .def hello(): return render_template('hello.html') route('/hello/<name>/', methods=['POST', "GET"]) .def hello_name(name): if request.method == 'GET': return render_template('hello.html', name=name) route('/hello/<float:float>/') .def float(float): return render_template('hello.html', float=float) route('/hello/<int:int>/') .def float1(int): return render_template('hello.html', int=int) route('/hello/<path:path>/') .def show(path): return render_template('hello.html', path=path) route('/hello/<uuid:uuid>/') .def uuid1(uuid): return render_template('hello.html', uuid=uuid)
methods 請求的方法
獲取傳遞的引數
GET請求:
request.args
POST請求:
request.form