Python 【web框架】之Flask

flask 是Python實現的輕量級web框架。沒有表單,orm等,但擴展性很好。不少Python web開發者十分喜歡。本篇介紹flask的簡單使用及其擴展。html

文中示例源碼已經傳到github:https://github.com/ZingP/webstudy.git.前端

1 安裝flask

pip install flask

2 框架本質

flask是基於Werkzeug模塊和Jinja2模板引擎實現的。前者實現了WSGI協議。咱們來看一下用Werkzeug怎麼實現一個web服務端:python

from werkzeug.wrappers import Request, Response

@Request.application
def hello(request):
    print(request)
    return Response('Hello Werkzeug!')

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 9000, hello)  

而後運行該文件,從瀏覽器上訪問http://localhost:9000/ 就能看到Hello Werkzeug!了。mysql

3 快速開始

開始第一個flask:git

from flask import Flask,render_template

app = Flask(__name__)     # 建立一個Flask對象,__name__傳成其餘字符串也行。

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

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

直接運行,而後訪問http://127.0.0.1:5000/就能夠看到Hello world!了。其中Flask這個類中能夠初始化如下變量:(能夠點擊Flask進去看源碼,能夠看到構造函數)github

def __init__(
        self,
        import_name,                        # 能夠寫任意字符串,通常寫__name__,這樣不會重名
        static_url_path=None,               # 靜態文件前綴,若是該項配置成static_url_path='/yyy',訪問靜態文件的目錄則爲http://127.0.0.1:5000/sss/**.jpg
        static_folder='static',             # 靜態文件路徑,好比在項目目錄下建立static目錄,存放靜態文件。訪問經過http://127.0.0.1:5000/static/**.jpg
        static_host=None,
        host_matching=False,
        subdomain_matching=False,
        template_folder='templates',        # 模板文件夾,視圖函數中須要引入from flask import render_template
        instance_path=None,                 # 當前路徑/instance
        instance_relative_config=False,     # 若是該項爲True,則會到 上面這個路徑下去找配置文件
        root_path=None                      # 根目錄
    ):

4 配置文件

flask的配置有不少種方式:web

(1)經過字典類型配置,直接在視圖函數所在的py文件裏,經過app.config['字段名'] = 值,就能夠配置了。如:正則表達式

app.config['DEBUG'] = True  # 打開調試模式,以字典的方式配置  

字段名能夠有如下內容:redis

default_config = ImmutableDict({
        'ENV':                                  None,
        'DEBUG':                                None,
        'TESTING':                              False,
        'PROPAGATE_EXCEPTIONS':                 None,
        'PRESERVE_CONTEXT_ON_EXCEPTION':        None,
        'SECRET_KEY':                           None,
        'PERMANENT_SESSION_LIFETIME':           timedelta(days=31),
        'USE_X_SENDFILE':                       False,
        'SERVER_NAME':                          None,
        'APPLICATION_ROOT':                     '/',
        'SESSION_COOKIE_NAME':                  'session',
        'SESSION_COOKIE_DOMAIN':                None,
        'SESSION_COOKIE_PATH':                  None,
        'SESSION_COOKIE_HTTPONLY':              True,
        'SESSION_COOKIE_SECURE':                False,
        'SESSION_COOKIE_SAMESITE':              None,
        'SESSION_REFRESH_EACH_REQUEST':         True,
        'MAX_CONTENT_LENGTH':                   None,
        'SEND_FILE_MAX_AGE_DEFAULT':            timedelta(hours=12),
        'TRAP_BAD_REQUEST_ERRORS':              None,
        'TRAP_HTTP_EXCEPTIONS':                 False,
        'EXPLAIN_TEMPLATE_LOADING':             False,
        'PREFERRED_URL_SCHEME':                 'http',
        'JSON_AS_ASCII':                        True,
        'JSON_SORT_KEYS':                       True,
        'JSONIFY_PRETTYPRINT_REGULAR':          False,
        'JSONIFY_MIMETYPE':                     'application/json',
        'TEMPLATES_AUTO_RELOAD':                None,
        'MAX_COOKIE_SIZE': 4093,
    })

經過app.字段名 = 值,如:sql

app.debug = True  # 調試模式  

這種方式是之前一種方式爲基礎的,將第一種方式中的各類字段,抽出經常使用字段,讓其支持這種配置方式。

另外直接更新一個字典也能夠:

app.config.update({...})  #更新這個字典的方式

(2) 方式二:從py文件中導入配置。app.config.from_pyfile('.py文件'), 如:

app.config.from_pyfile('settings.py')

相似還有:

app.config.from_pyfile('settings.py')

# app.config.from_envvar('環境變量名')
# 若是環境變量名爲py文件,會自動調用app.config.from_pyfile()

# app.config.from_json('json文件')            # json文件形式

# app.config.from_mapping({"DEBUG": True})    # 字典形式

# app.config.from_object('python類或者類的路徑')
# app.config.from_object('settings.TestConfig')

# 在settings.py中:
class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite://:memory:'


class ProductionConfig(Config):
    DATABASE_URI = 'mysql://user@localhost/foo'


class DevelopmentConfig(Config):
    DEBUG = True


class TestConfig(Config):
    TESTING = True  

注意:配置文件中的key必須是大寫;另外,經過類導入配置文件的路徑須要從sys.path中存在的開始寫。

5 路由系統

5.1 常規路由

flask 的路由系統是有一個裝飾器+視圖函數實現:

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

當我看到這樣的路由方式仍是比較驚訝的,不過不論是什麼樣的路由,最後都是將url和視圖函數一一對應。若是咱們點開route這個裝飾器,不難看到這樣一句源碼:

def route(self, rule, **options):
        """A decorator that is used to register a view function for a
        given URL rule.  This does the same thing as :meth:`add_url_rule`
        but is intended for decorator usage::

            @app.route('/')
            def index():
                return 'Hello World'

        For more information refer to :ref:`url-route-registrations`.

        :param rule: the URL rule as string
        :param endpoint: the endpoint for the registered URL rule.  Flask
                         itself assumes the name of the view function as
                         endpoint
        :param options: the options to be forwarded to the underlying
                        :class:`~werkzeug.routing.Rule` object.  A change
                        to Werkzeug is handling of method options.  methods
                        is a list of methods this rule should be limited
                        to (``GET``, ``POST`` etc.).  By default a rule
                        just listens for ``GET`` (and implicitly ``HEAD``).
                        Starting with Flask 0.6, ``OPTIONS`` is implicitly
                        added and handled by the standard request handling.
        """
        def decorator(f):
            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator  

從self.add_url_rule(rule, endpoint, f, **options)這句看,flask是經過裝飾器把路由規則和視圖函數關聯起來。實際上咱們也能夠這麼寫路由:

def hello_world():
    from flask import url_for
    url = url_for("xxx")
    print("URL:", url)
    return 'Hello World!'

app.add_url_rule("/", view_func=hello_world, endpoint="xxx", methods=['GET', 'POST'])
# endpoint 這裏用來反向生成url,默認是函數名
# methods 指的是支持的請求方式

不過推薦仍是用裝飾器的方式寫路由,經常使用路由寫法有如下幾種:

@app.route('/user/<username>')
@app.route('/post/<int:post_id>')
@app.route('/post/<float:post_id>')
@app.route('/post/<path:path>')
@app.route('/login', methods=['GET', 'POST'])

注意,當匹配參數是,須要在視圖函數中接收一下,如:

@app.route('/user/<int:uid>')
def hello_world(uid):
    print("UID:", uid)
    return 'Hello World!'  

規則支持的匹配類型有如下幾種:

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

5.2 自定義路由 

也許你會以爲這些路由規則不太自由,不夠用;那麼能夠經過自定義的方式:

from flask import Flask, url_for
from werkzeug.routing import BaseConverter

app = Flask(__name__)


# 自定義經過正則匹配url
class RegexConverter(BaseConverter):
    """
    自定義URL匹配正則表達式
    """

    def __init__(self, map, regex):
        super(RegexConverter, self).__init__(map)
        self.regex = regex   # 會按照傳入的正則表達式進行匹配

    def to_python(self, value):
        """
        路由匹配時,匹配成功後傳遞給視圖函數中參數的值
        :param value: 
        :return: 
        """
        return value

    def to_url(self, value):
        """
        使用url_for反向生成URL時,傳遞的參數通過該方法處理,返回的值用於生成URL中的參數
        :param value: 
        :return: 
        """
        val = super(RegexConverter, self).to_url(value)
        return val

# 添加到flask中
app.url_map.converters['regex'] = RegexConverter


@app.route('/index/<regex("\d+"):nid>')
def index(nid):
    print(nid)
    url = url_for('index', nid=nid)    # 反向生成url
    print(url)
    return 'Index'


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

運行以後,訪問http://127.0.0.1:5000/index/9999會在後端打印nid是9999,而反向生成的url是/index/9999。

5.3 使用裝飾器

也許咱們想給視圖函數定製一些功能,好比加一些裝飾器,那應該這樣寫:

def auth(func):
    def inner(*args, **kwargs):
        print('before')
        result = func(*args, **kwargs)
        print('after')
        return result

    return inner


@app.route('/index.html', methods=['GET', 'POST'], endpoint='index')
@auth       # 裝飾器必定要放在app.route這個裝飾器之下
def index():
    return 'Index'  

 其中,裝飾器auth必定要放在app.route這個裝飾器之下才能使路由裝飾器先生效。路由還能夠這樣寫:

def index():
    return "Index"

# 方式一:
# app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET", "POST"])

# 方式二:
app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET", "POST"])
app.view_functions['index'] = index

5.4 支持CBV

是否能像django同樣支持CBV呢?固然能夠:

from flask import views
def auth(func):
    def inner(*args, **kwargs):
        print('before')
        result = func(*args, **kwargs)
        print('after')
        return result

    return inner


class IndexView(views.View):
    methods = ['GET']
    decorators = [auth, ]

    def dispatch_request(self):
        print('Index')
        return 'Index!'


app.add_url_rule('/index', view_func=IndexView.as_view(name='index'))  # name=endpoint 反向url使用  

其中,decorators是須要添加的裝飾器。固然還能夠定義get,post等函數:

class IndexView(views.MethodView):
    methods = ['GET', 'POST']
    decorators = [auth, ]

    def get(self):
        return 'Index.GET'

    def post(self):
        return 'Index.POST'

app.add_url_rule('/index', view_func=IndexView.as_view(name='index'))  # name=endpoint  

補充,@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"]

# strict_slashes = None, 對URL最後的 / 符號是否嚴格要求,
# 如:@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>')
# 或
# def func(adapter, nid):
#     return "/home/888"
# @app.route('/index/<int:nid>', redirect_to=func)

# subdomain = None, 子域名訪問
app = Flask(import_name=__name__)
app.config['SERVER_NAME'] = 'lyy.com:5000'
@app.route("/", subdomain="admin")
def static_index():
    """Flask supports static subdomains
    This is available at static.your-domain.tld"""
    return "static.your-domain.tld"

@app.route("/dynamic", subdomain="<username>")
def username_index(username):
    """Dynamic subdomains are also supported
    Try going to user1.your-domain.tld/dynamic"""
    return username + ".your-domain.tld"

6 使用模板

6.1 常規模板

使用的是jinjia2語法,和django差很少。除了不支持simple_tag,畢竟有更簡便的方法自定義。

6.2 自定義模板

py文件:返回HTML文檔時須要引入 render_template

from flask import Flask, render_template

app = Flask(__name__)

# 可直接定義一個函數,到前端頁面去使用
def myhtml(abc):
    return '<h1>liuyouyuan{}</h1>'.format(abc)

@app.route('/index', methods=['GET', 'POST'])
def login():
    return render_template('index.html', yyy=myhtml)    # yyy就至關於前端使用時的函數名字

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

看看index.html直接給yyy()傳參數,就像調用Python函數同樣:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>{{ yyy("niubi")|safe}}</p>
</body>
</html>

7 請求與響應

7.1 視圖函數中拿到請求信息

在flask中,須要引入from flask import request, 經過request拿到請求信息。

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def hello_world():
    print(request)      # 引入request以後,不須要手動傳給視圖函數,flask內部會自動傳,直接獲取就行。
    return 'Hello World!'


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

 能夠看到,引入request以後,不須要手動傳給視圖函數,flask內部會自動傳,直接獲取就行。能夠從request中獲取到的請求信息有:

# 請求相關信息
# request.method
# request.args
# request.form
# request.values
# request.cookies
# request.headers
# request.path
# request.full_path
# request.script_root
# request.url
# request.base_url
# request.url_root
# request.host_url
# request.host
# request.files
# obj = request.files['the_file_name']
# obj.save('/var/www/uploads/' + secure_filename(f.filename))

其中獲取文件直接save到一個目錄就行。

7.2 相應相關

from flask import render_template
from flask import redirect
from flask import make_response

# 響應相關信息
# return "字符串"
# return render_template('html模板路徑',**{})
# return redirect('/index.html')

# response = make_response(render_template('index.html'))
# response是flask.wrappers.Response類型
# response.delete_cookie('key')
# response.set_cookie('key', 'value')
# response.headers['X-Something'] = 'A value'  

在flask中基本都是經過導入一個全局的變量,而後從視圖函數中直接引用,每一個視圖函數每次請求來拿到的都是不同的。

8 session

8.1 默認session

默認的Session是基於Cookies實現的,放在瀏覽器上。若是要對session加密,須要設置密鑰。基本使用以下:

from flask import Flask, session, redirect, url_for, escape, request

app = Flask(__name__)


@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form action="" method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''


@app.route('/logout')
def logout():
    # 從session移除username
    session.pop('username', None)
    return redirect(url_for('index'))


# 若是要加密session,在此處設置祕鑰
app.secret_key = 'reffbyujHSDU!ASn#UIddODN*1243 WEfM'

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

8.2 自定義session

flask中的SessionInterface留了兩個鉤子函數,咱們來看一下:

def open_session(self, app, request):
	"""This method has to be implemented and must either return ``None``
	in case the loading failed because of a configuration error or an
	instance of a session object which implements a dictionary like
	interface + the methods and attributes on :class:`SessionMixin`.
	"""
	raise NotImplementedError()

def save_session(self, app, session, response):
	"""This is called for actual sessions returned by :meth:`open_session`
	at the end of the request.  This is still called during a request
	context so if you absolutely need access to the request you can do
	that.
	"""
	raise NotImplementedError()

請求來時,open_session會嘗試去獲取session;當返回信息時,會調用save_session。因此,咱們要自定義session時,只須要繼承接口類,再重寫這兩個方法便可。  

如今新建一個session.py文件,寫好自定義的session類:

import uuid
import json
from flask.sessions import SessionInterface
from flask.sessions import SessionMixin
from itsdangerous import Signer, BadSignature, want_bytes


class MySession(dict, SessionMixin):
    def __init__(self, initial=None, sid=None):
        self.sid = sid
        self.initial = initial
        super(MySession, self).__init__(initial or ())

    def __setitem__(self, key, value):
        super(MySession, self).__setitem__(key, value)

    def __getitem__(self, item):
        return super(MySession, self).__getitem__(item)

    def __delitem__(self, key):
        super(MySession, self).__delitem__(key)


class MySessionInterface(SessionInterface):
    session_class = MySession
    container = {}

    def __init__(self):
        import redis
        self.redis = redis.Redis()

    def _generate_sid(self):
        return str(uuid.uuid4())

    def _get_signer(self, app):
        if not app.secret_key:
            return None
        return Signer(app.secret_key, salt='flask-session',
                      key_derivation='hmac')

    def open_session(self, app, request):
        """
        程序剛啓動時執行,須要返回一個session對象
        """
        sid = request.cookies.get(app.session_cookie_name)
        if not sid:
            sid = self._generate_sid()
            return self.session_class(sid=sid)

        signer = self._get_signer(app)
        try:
            sid_as_bytes = signer.unsign(sid)
            sid = sid_as_bytes.decode()
        except BadSignature:
            sid = self._generate_sid()
            return self.session_class(sid=sid)

        # session保存在redis中
        # val = self.redis.get(sid)
        # session保存在內存中
        val = self.container.get(sid)

        if val is not None:
            try:
                data = json.loads(val)
                return self.session_class(data, sid=sid)
            except:
                return self.session_class(sid=sid)
        return self.session_class(sid=sid)

    def save_session(self, app, session, response):
        """
        程序結束前執行,能夠保存session中全部的值
        如:
            保存到resit
            寫入到用戶cookie
        """
        domain = self.get_cookie_domain(app)
        path = self.get_cookie_path(app)
        httponly = self.get_cookie_httponly(app)
        secure = self.get_cookie_secure(app)
        expires = self.get_expiration_time(app, session)

        val = json.dumps(dict(session))

        # session保存在redis中
        # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime)
        # session保存在內存中
        self.container.setdefault(session.sid, val)

        session_id = self._get_signer(app).sign(want_bytes(session.sid))

        response.set_cookie(app.session_cookie_name, session_id,
                            expires=expires, httponly=httponly,
                            domain=domain, path=path, secure=secure) 

 用法以下:

from flask import Flask
from flask import session
from session import MySessionInterface
app = Flask(__name__)

app.secret_key = 'asdWhuDW!@##%bxwy'
app.session_interface = MySessionInterface()

@app.route('/login', methods=['GET', "POST"])
def login():
    print(session)
    session['user1'] = 'lyy'
    session['user2'] = 'yy'
    del session['user2']
    print(session)
    return "test mysession"

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

 這樣就能夠了。

8.3 第三方插件

pip install flask-session  使用簡單,能夠參考https://pythonhosted.org/Flask-Session/。不過目前只支持flask0.8,此處不在演示。

9 使用藍圖

咱們回想一下以前的全部介紹都是將視圖函數寫在同一個.py文件中的,對於微小項目能夠,可是稍微大點的項目咱們不可能把視圖函數都寫在同一個文件,否則找起來都很麻煩。因此,確定是要根據必定的邏輯進行目錄劃分的。藍圖的做用就是劃分目錄結構。

不過咱們在介紹藍圖以前,先嚐試着本身劃分一下目錄:

9.1 本身劃分目錄

一個小項目,應該包含app就是app名稱,static放置靜態文件,views下將視圖按功能分爲多個py文件。run.py是入口。

(1)__init__.py:

from flask import Flask
app = Flask(__name__)

from .views import account  

必定要記得導入視圖~~

(2)run.py:

from app import app

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

(3)account.py:

from .. import app

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

9.2 藍圖劃分

(1)run.py:

from app01 import app

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

(2)account.py

from flask import Blueprint

account = Blueprint('account', __name__, url_prefix='/yyy', template_folder='', static_folder='')
# 能夠爲每一個藍圖單獨指定一個模板文件和靜態文件

@account.route('/')
def hello_world():
    return 'Hello blue!'

host.py:

from flask import Blueprint

host = Blueprint('host', __name__)

@host.route('/host.html')
def hello_host():
    return "host.."

__init__.py:

from flask import Flask
from .views.account import account
from .views.host import host

app = Flask(__name__)

app.register_blueprint(account)     # 註冊藍圖
app.register_blueprint(host)

10 message

message在django中是沒有的,它是基於Session實現的一個保存數據的集合,其特色是:使用一次就刪除,能夠用於錯誤信息。直接看代碼吧:

from flask import Flask, flash, request, get_flashed_messages, url_for

app = Flask(__name__)
app.secret_key = 'ewqfQWDWEhqweofhqwofn'


@app.route('/')
def index1():
    messages = get_flashed_messages()   # 取出
    print(messages)
    return "index"


@app.route('/set', endpoint="xxx")
def index2():
    v = url_for("xxx")
    flash(v)    # 存入
    return 'hahahah'

這就OK了。

11 中間件

直接上代碼:

from flask import Flask

app = Flask(__name__)

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


class MiddleWare:
    def __init__(self, wsgi_app):
        self.wsgi_app = wsgi_app

    def __call__(self, *args, **kwargs):
        print("456")   # do something
        return self.wsgi_app(*args, **kwargs)


if __name__ == "__main__":
    app.wsgi_app = MiddleWare(app.wsgi_app)
    app.run(port=9999)

12 更多插件

表單插件參考:WTForms    orm能夠用:SQLAchemy    更多可看:http://flask.pocoo.org/extensions

相關文章
相關標籤/搜索