Flask快速入門必備

1. 安裝

全局安裝 :
pip install Flask

採用虛擬環境:
https://dormousehole.readthedocs.io/en/latest/installation.html#id4

2. hello world

https://dormousehole.readthedocs.io/en/latest/quickstart.html#id2

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

win下:

set FLASK_APP=hello.py
python -m flask run
或者
set FLASK_APP=hello.py
flask run

第二種方式:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'


if __name__ == '__main__':
    app.run(debug=True)

然後

python hello.py

3. route 的含義

是一個裝飾器,將函數名稱與url關聯
訪問url時通過route()裝飾器觸發對應的函數

4. 藍圖 blueprint

路由規劃的,通過配置更好的管理路由

## baicai.py
from flask import Blueprint
route_baicai = Blueprint('baicai_page', __name__)

@route_baicai.route('/')
def index():
    return 'this is baicai index'
    
@route_baicai.route('hello')
def hello():
    return 'this is baicai hello'
## hello.py
from flask import Flask
from baicai import route_baicai

app = Flask(__name__)
app.register_blueprint(route_baicai, url_prefix="/baicai")

@app.route('/')
def hello_world():
    return 'Index!'

@app.route('/hello')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)

意思就是遇到 /baicai 前綴的就去找baicai.py下面的 url
在這裏插入圖片描述
在這裏插入圖片描述

5. 鏈接管理器 url_for

快速方便統一管理url
其實就是視圖渲染,類似laravel的view函數

from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def hello():
    url = url_for('index')
    return 'hello world ' + url

@app.route('url_for')
def index():
    return 'hell index'

if __name__ == '__main__':
    app.run(debug=True)

在這裏插入圖片描述

# UrlManager.py
class UrlManager(object):
    @staticmethod #靜態方法
    def bulidUrl(path):
        return path

    @staticmethod
    def buildStaticUrl(path):
    	path = path + "?v=" + "xxxxx"
        return UrlManager.bulidUrl(path)
from flask import Flask, url_for
from router import route_baicai
from common.libs.UrlManager import UrlManager

app = Flask(__name__)
app.register_blueprint(route_baicai, url_prefix="/baicai")


@app.route('/')
def hello():
    url = url_for('index')
    
    url_1 = UrlManager.bulidUrl('/api')

    return 'hello world, url:%s, url_1:%s'%(url, url_1)

@app.route('/url_for')
def index():
    return 'hello index'

if __name__ == '__main__':
    app.run(debug=True)

6. 日誌記錄系統

https://dormousehole.readthedocs.io/en/latest/quickstart.html#id22

app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')

7. 錯誤處理器

flask.Flask.errorhandler
flask.Blueprit.errorhandler
flask.Blueprint.app_errorhandler

@app.errorhandler(404)
def page_not_found(error):
    app.logger.error(error)
    return 'not found', 404

8. 數據庫 ORM

Flask-SQLAlchemy

http://www.pythondoc.com/flask-sqlalchemy/index.html

  • 安裝
    pip install flask-sqlalchemy
    pip install mysqlclient
from flask import Flask, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]/mysql'
db = SQLAlchemy(app)

@app.route('/db')
def db_index():
    from sqlalchemy import text
    sql = text("select * from `user`")
    res = db.engine.execute(sql)
    for row in res:
        app.logger.info(row)
    return 'hello db'

9. Flask-Script

https://flask-script.readthedocs.io/en/latest/

  • 安裝
    pip install Flask-Script
from flask import Flask

from flask_script import Manager

from flask_sqlalchemy import SQLAlchemy
import os
class Application( Flask ):
    def __init__(self,import_name):
        super( Application,self ).__init__( import_name )
        self.config.from_pyfile( 'config/base_setting.py' )
        if "ops_config" in os.environ:
            self.config.from_pyfile( 'config/%s_setting.py'%os.environ['ops_config'] )

        db.init_app( self )

db = SQLAlchemy()
app = Application( __name__ )

manager = Manager( app )
from application import app,manager

from flask_script import Server

##web server
manager.add_command( "runserver", Server( host='0.0.0.0',port=app.config['SERVER_PORT'],use_debugger = True ,use_reloader = True) )

def main():
    manager.run( )

if __name__ == '__main__':
    try:
        import sys
        sys.exit( main() )
    except Exception as e:
        import traceback
        traceback.print_exc()

python manager.py runserver 啓動

10. 打造一個高可用flask mvc框架

(暫時略)
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

11. 生產部署

  • 單進程啓動服務

python manager.py runserver的方式

  • 多進程啓動服務

使用 uwsgi

參考:

uwsgi.ini

[uwsgi]
#源碼目錄
chdir=/data/www/Order
#python 虛擬環境
home=/data/www/python3_vir
module=manager
callable=app
master=true
processes=4
http=0.0.0.0:8889
socket=/data/www/logs/order.sock
buffer-size=65535
pidfile=/data/www/logs/order.pid
chmod-socket=777
logfile-chmod=644
daemonize=/data/www/logs/order.log
static-map = /static=/data/www/Order/web/static

nginx

	location /static {
		alias  /data/www/Order/web/static/;
	}

	location / {
		try_files $uri @yourapplication;
	}
    location @yourapplication {
      include uwsgi_params;
      uwsgi_pass unix:/data/www/logs/order.sock;
      uwsgi_read_timeout 1800;
      uwsgi_send_timeout 300;
    }
  • 理解筆記
    flask 藍圖理解和入口文件理解
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章