Flask源碼解讀(一)

     Flask是一個使用 Python 編寫的輕量級 Web 應用框架。Flask 自己只是 Werkezug 和 Jinja2 的之間的橋樑,前者實現一個合適的 WSGI 應用,後者處理模板。 固然, Flask 也綁定了一些通用的標準庫包,好比 logging 。 除此以外其它全部一切都交給擴展來實現。我將追蹤一個簡單FlaskApp的運行,看看request和response是怎麼實現,如下是一個簡單的flask app代碼,可用瀏覽器訪問html

#!/usr/bin/env python
# encoding: utf-8

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    import pdb;pdb.set_trace()
    return '<h1>Hello world!</h1>'

@app.route('/user/<name>')
def user(name):
    import pdb;pdb.set_trace()
    return '<h1>Hello,%s!</h1>' % name

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

經過pdb捕捉棧的調用狀況,能夠獲得python

 /home/steinliber/flask-source-code/route/a.py(18)<module>()
-> app.run()
  /home/steinliber/flask-source-code/env/local/lib/python2.7/site-packages/flask/app.py(772)run()
-> run_simple(host, port, self, **options)
  /home/steinliber/flask-source-code/env/local/lib/python2.7/site-packages/werkzeug/serving.py(692)run_simple()
-> inner()
  /home/steinliber/flask-source-code/env/local/lib/python2.7/site-packages/werkzeug/serving.py(657)inner()
-> srv.serve_forever()
  /home/steinliber/flask-source-code/env/local/lib/python2.7/site-packages/werkzeug/serving.py(497)serve_forever()
-> HTTPServer.serve_forever(self)
這是捕捉到的啓動flask服務器調用的函數,從中能夠看到由於app是Flask的實例,則調用app.run()會調用Flask類中的run(),而run()方法只是簡單的爲host和port設置了默認值就調用了werkzeug的run_simple()flask

在werkzeug中的run_simple()函數瀏覽器

def run_simple(hostname, port, application, use_reloader=False,
               use_debugger=False, use_evalex=True,
               extra_files=None, reloader_interval=1,
               reloader_type='auto', threaded=False,
               processes=1, request_handler=None, static_files=None,
               passthrough_errors=False, ssl_context=None):
    if use_debugger:
        from werkzeug.debug import DebuggedApplication
        application = DebuggedApplication(application, use_evalex)
    if static_files:
        from werkzeug.wsgi import SharedDataMiddleware
        application = SharedDataMiddleware(application, static_files)

    def log_startup(sock):
        display_hostname = hostname not in ('', '*') and hostname or 'localhost'
        if ':' in display_hostname:
            display_hostname = '[%s]' % display_hostname
        quit_msg = '(Press CTRL+C to quit)'
        port = sock.getsockname()[1]
        _log('info', ' * Running on %s://%s:%d/ %s',
             ssl_context is None and 'http' or 'https',
             display_hostname, port, quit_msg)

    def inner():
        try:
            fd = int(os.environ['WERKZEUG_SERVER_FD'])
        except (LookupError, ValueError):
            fd = None
        srv = make_server(hostname, port, application, threaded,
                          processes, request_handler,
                          passthrough_errors, ssl_context,
                          fd=fd)
        if fd is None:
            log_startup(srv.socket)
        srv.serve_forever()
    if use_reloader:
        # If we're not running already in the subprocess that is the
        # reloader we want to open up a socket early to make sure the
        # port is actually available.
        if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
            if port == 0 and not can_open_by_fd:
                raise ValueError('Cannot bind to a random port with enabled '
                                 'reloader if the Python interpreter does '
                                 'not support socket opening by fd.')

            # Create and destroy a socket so that any exceptions are
            # raised before we spawn a separate Python interpreter and
            # lose this ability.
            address_family = select_ip_version(hostname, port)
            s = socket.socket(address_family, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind((hostname, port))
            if hasattr(s, 'set_inheritable'):
                s.set_inheritable(True)

            # If we can open the socket by file descriptor, then we can just
            # reuse this one and our socket will survive the restarts.
            if can_open_by_fd:
                os.environ['WERKZEUG_SERVER_FD'] = str(s.fileno())
                s.listen(LISTEN_QUEUE)
                log_startup(s)
            else:
                s.close()

        from ._reloader import run_with_reloader
        run_with_reloader(inner, extra_files, reloader_interval,
                          reloader_type)
    else:
        inner()

這是run_simple()的主要做用部分,前兩個判斷語句是對debug模式以及靜態文件的包裝。ShareDataMiddleware就是一箇中間件,這裏是起到吧文件轉換爲服務器可接受的Response形式的做用。服務器

use_reloader 用於決定當app代碼改變時是否要重啓服務器,如果True,則他會創建一個socket,其中的can_open_by_fd由socket中是否由fromfd特徵決定,若是能夠就將fd儲存在環境變量中以便重啓後的複用,socket開始監聽,然後就調用run_with_reloader,它也接受了函數inner.能夠看出不管use_reloader是否是True時,都會調用函數內部的inner函數,在inner函數內,在環境中WERKZEUG_SERVER_FD這個key儲存了能夠複用的socket,若沒有就設爲None,而後就調用函數make_server,這根據參數process和threads選擇合適的服務器,取得服務器對象後,就調用方法run_forever,這服務器也就啓動了。,werkzeug提供了多種可選的服務器,這裏是一個基本的單線程單進程服務器app

class BaseWSGIServer(HTTPServer, object):

    """Simple single-threaded, single-process WSGI server."""
    multithread = False
    multiprocess = False
    request_queue_size = LISTEN_QUEUE

    def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None

    def log(self, type, message, *args):
        _log(type, message, *args)

    def serve_forever(self):
        self.shutdown_signal = False
        try:
            HTTPServer.serve_forever(self)
        except KeyboardInterrupt:
            pass
        finally:
            self.server_close()

    def handle_error(self, request, client_address):
        if self.passthrough_errors:
            raise
        return HTTPServer.handle_error(self, request, client_address)

    def get_request(self):
        con, info = self.socket.accept()
        return con, info

這個服務器繼承了基本的HTTPServer,HTTPServer能夠在制定的端口接受數據並處理將結果傳遞給RequestHandlerClass,具體能夠看官方文檔https://docs.python.org/2/library/basehttpserver.html框架

在代碼中,request_queue_size制定了請求隊列的最大鏈接數,在__init__函數中handler是請求的處理器,若參數中爲提供,就設爲默認值,然後就是獲得可用的socket,ssl_context主要是幫助實現SSL。另一些就是簡單重寫了HTTPServer的方法,在serve_forever中仍是調用了HTTPServer的方法來實現服務器功能。dom

綜上就是flask一個基本服務器的實現,在其中能夠看到如何爲簡單的服務器添加多種功能,如SSL,socket的複用,服務器的重載等,接下來就是reloader以及SSL的實現python2.7

相關文章
相關標籤/搜索