Flask學習-Flask app接受第一個HTTP請求


一、__call__()

在Flask app啟動后,一旦uwsgi收到來自web server的請求,就會調用后端app,其實此時就是調用app的__call__(environ,start_response).

flask.py:

def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)

  

二、wsgi_app()

當http請求從server發送過來的時候,他會啟動__call__功能,這時候就啟動了最關鍵的wsgi_app(environ,start_response)函數。

fask.py:

def wsgi_app(self, environ, start_response):
        
        with self.request_context(environ):  #2.1,把環境變量入棧
            rv = self.preprocess_request()   #2.2,請求前的處理操作,主要執行一些函數,主要是准備工作。
            if rv is None:   #請求前如果沒有需要做的事情,就會進入到請求分發
                rv = self.dispatch_request()  #2.3 進行請求分發
            response = self.make_response(rv)  #2.4 返回一個response_class的實例對象,也就是可以接受environ和start_reponse兩個參數的對象
            response = self.process_response(response)  #2.5 進行請求后的處理操作,只要是執行一些函數,和preprocesses_request()類似,主要是清理工作。
            return response(environ, start_response)   #2.6 對web server(uwsgi)進行正式回應

  

2.1 環境變量入棧

通過with上下文管理,生成request請求對象和請求上下文環境,並入棧。

執行如下代碼塊:

   def request_context(self, environ):
        
        return _RequestContext(self, environ) #調用_RequestContext()類

  

2.1.1 調用_RequestContext()類

首先 會執行__enter__()函數,執行_request_ctx_stack的push方法,把環境變量進行入棧操作。

注意:_request_ctx_stack = LocalStack()

#請求上下文初始化
class _RequestContext(object):
   
    def __init__(self, app, environ):
        self.app = app
        self.url_adapter = app.url_map.bind_to_environ(environ)
        self.request = app.request_class(environ)
        self.session = app.open_session(self.request)
        self.g = _RequestGlobals()
        self.flashes = None
'''
調用with的時候就會執行
'''
    def __enter__(self):
        _request_ctx_stack.push(self)

'''
with進行上下文管理的例子: with離開后就會執行自定義上下文管理 class Diycontextor: def __init__(self,name,mode): self.name = name self.mode = mode def __enter__(self): print "Hi enter here!!" self.filehander = open(self.name,self.mode) return self.filehander def __exit__(self,*para): print "Hi exit here" self.filehander.close() with Diycontextor('py_ana.py','r') as f: for i in f: print i '''
def __exit__(self, exc_type, exc_value, tb): if tb is None or not self.app.debug: _request_ctx_stack.pop()

  

這一步最主要的是LocalStack類。

class LocalStack(object):

    """This class works similar to a :class:`Local` but keeps a stack
    of objects instead.  This is best explained with an example::
LocalStack類似於Local類,但是它保持了一個棧功能。它能夠將對象入棧、出棧,如下: >>> ls = LocalStack() >>> ls.push(42) >>> ls.top 42 >>> ls.push(23) >>> ls.top 23 >>> ls.pop() 23 >>> ls.top 42 They can be force released by using a :class:`LocalManager` or with the :func:`release_local` function but the correct way is to pop the item from the stack after using. When the stack is empty it will no longer be bound to the current context (and as such released).
入棧的對象可以通過LocalManage類進行強制釋放,或者通過函數release_local函數。但是,正確的姿勢是通過pop函數把他們出棧。
當棧為空時,它不再彈出上下文對象,這樣就完全釋放了。 By calling the stack without arguments it returns a proxy that resolves to the topmost item on the stack.
通過調用調用無參數的stack,返回一個proxy。

  

從LocalStack的說明可以得知這幾個事情:

1、LocalStack是一個類似Local的類,但是它具備棧的功能,能夠讓對象入棧、出棧以及銷毀對象。

2、可以通過LocalManager類進行強制釋放對象。

由引申出兩個類:Local類和Localmanager類

Local類用於添加、存儲、或刪除上下文變量。

LocalManager類:由於Local對象不能管理自己,所以通過LocalManager類用來管理Local對象。

 

我們再回到wsgi_app函數中的2.2步驟:

2.2  preprocess_request

preprocess_request()方法,主要是進行flask的hook鈎子, before_request功能的實現,也就是在真正發生請求之前,有些准備工作需要提前做。比如,連接數據庫。

代碼如下:

   def preprocess_request(self):
       
        for func in self.before_request_funcs:
            rv = func()
            if rv is not None:
                return rv

  

它會執行preprocess_request列表里面的每個函數。執行完成后,他會進入到dispatch_request方法。

2.3 dispatch_request

'''
分發請求
1、獲取endpoint和values,即請求url和參數
2、調用視圖函數view_functions[endpoint](**values)
3、處理異常錯誤
'''		
    def dispatch_request(self):
        
        try:
            endpoint, values = self.match_request()
            return self.view_functions[endpoint](**values)
        except HTTPException, e:
            handler = self.error_handlers.get(e.code)
            if handler is None:
                return e
            return handler(e)
        except Exception, e:
            handler = self.error_handlers.get(500)
            if self.debug or handler is None:
                raise
            return handler(e)

  

進入dispatch_request()后,先執行match_request(),match_request()定義如下:

    def match_request(self):
        rv = _request_ctx_stack.top.url_adapter.match()
        request.endpoint, request.view_args = rv
        return rv

  

注意:函數里面的url_adapter。

self.url_adapter = app.url_map.bind_to_environ(environ),其實他使一個Map()對象,Map()對象位於werkzeug.routing模塊,用於處理routeing。

從函數可以看出,它會返回一個元組(endpoint,view_args)

endpoint:是一個url

view_args:是url的參數

例如:

>>> m = Map([
        ...     Rule('/', endpoint='index'),
        ...     Rule('/downloads/', endpoint='downloads/index'),
        ...     Rule('/downloads/<int:id>', endpoint='downloads/show')
        ... ])
        >>> urls = m.bind("example.com", "/")
        >>> urls.match("/", "GET")
        ('index', {})
        >>> urls.match("/downloads/42")
        ('downloads/show', {'id': 42})

  

match_request()執行完成后,此時已經獲取到了url和url里面包含的參數的信息。接着進入視圖函數的執行:view_functions()

 在Flask app啟動一節我們知道,view_functions()是一個字典,類似view_functions = {'hello_world':hello_world},當我們執行

self.view_functions[endpoint](**values)

就相當於執行了hello_wold(**values),即自行了視圖函數。也就是我們最開始app里面的hello_world視圖函數:

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

  

這時就會返回'Hello  World!‘如果有異常,則返回異常內容。

 至此,就完成了dispatch_request(),請求分發工作。這時,我們再次回到wsgi_app中的2.4步:response = self.make_response(rv)

2.4 make_response

def make_response(self, rv):
    """Converts the return value from a view function to a real
    response object that is an instance of :attr:`response_class`.

    The following types are allowd for `rv`:

    ======================= ===========================================
    :attr:`response_class`  the object is returned unchanged
    :class:`str`            a response object is created with the
                            string as body
    :class:`unicode`        a response object is created with the
                            string encoded to utf-8 as body
    :class:`tuple`          the response object is created with the
                            contents of the tuple as arguments
    a WSGI function         the function is called as WSGI application
                            and buffered as response object
    ======================= ===========================================

    :param rv: the return value from the view function
    """
    if isinstance(rv, self.response_class):
        return rv
    if isinstance(rv, basestring):
        return self.response_class(rv)
    if isinstance(rv, tuple):
        return self.response_class(*rv)
    return self.response_class.force_type(rv, request.environ)

  

通過make_response函數,將剛才取得的 rv 生成響應,重新賦值response

2.5 process_response

再通過process_response功能主要是處理一個after_request的功能,比如你在請求后,要把數據庫連接關閉等動作,和上面提到的before_request對應和類似。

def after_request(self, f):
        self.after_request_funcs.append(f)
        return f

  

之后再進行request_finished.send的處理,也是和socket處理有關,暫時不詳細深入。之后返回新的response對象。

這里特別需要注意的是,make_response函數是一個非常重要的函數,他的作用是返回一個response_class的實例對象,也就是可以接受environ和start_reponse兩個參數的對象

 

當所有清理工作完成后,就會進入response(environ, start_response)函數,進行正式回應。

2.6 response(environ, start_response)

 最后進入response()函數,說response函數之前,我們先來看看response函數的由來:

response = self.make_response(rv)
response = self.process_response(response)

  

2.6.1 response=make_response()

而make_response的返回值為:return self.response_class.force_type(rv, request.environ)

其中的response_class = Response,而Response最終來自werkzeug.

werkzeug import Response as ResponseBase

@classmethod
    def force_type(cls, response, environ=None):
"""Enforce that the WSGI response is a response object of the current
        type.  Werkzeug will use the :class:`BaseResponse` internally in many
        situations like the exceptions.  If you call :meth:`get_response` on an
        exception you will get back a regular :class:`BaseResponse` object, even
        if you are using a custom subclass.

        This method can enforce a given response type, and it will also
        convert arbitrary WSGI callables into response objects if an environ
        is provided::

            # convert a Werkzeug response object into an instance of the
            # MyResponseClass subclass.
            response = MyResponseClass.force_type(response)

            # convert any WSGI application into a response object
            response = MyResponseClass.force_type(response, environ)

        This is especially useful if you want to post-process responses in
        the main dispatcher and use functionality provided by your subclass.

        Keep in mind that this will modify response objects in place if
        possible!

  

從上面可以知道,force_type()是一個類方法,強制使當前對象成為一個WSGI的reponse對象。

 

 2.6.2  response = self.process_response(response)

def process_response(self, response):
        
        session = _request_ctx_stack.top.session
        if session is not None:
            self.save_session(session, response)
        for handler in self.after_request_funcs:
            response = handler(response)
        return response

  

process_response()執行了2個操作:

1、保存會話

2、執行請求后的函數列表中每一個函數,並返回response對象

 

最后response函數會加上environ, start_response的參數並返回給uwsgi(web服務器),再由uwsgi返回給nginx,nignx返回給瀏覽器,最終我們看到的內容顯示出來。

 至此,一個HTTP從請求到響應的流程就完畢了.

 

三、總結

總的來說,一個流程的關鍵步驟可以簡單歸結如下:

 

 最后附上flask 0.1版本的注釋源碼:

# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
from threading import local
from jinja2 import Environment, PackageLoader, FileSystemLoader
from werkzeug import Request as RequestBase, Response as ResponseBase, \
     LocalStack, LocalProxy, create_environ, cached_property, \
     SharedDataMiddleware
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, InternalServerError
from werkzeug.contrib.securecookie import SecureCookie
from werkzeug import abort, redirect
from jinja2 import Markup, escape

try:
    import pkg_resources
    pkg_resources.resource_stream
except (ImportError, AttributeError):
    pkg_resources = None

#Request繼承werkzeug的Request類
class Request(RequestBase):
 
    def __init__(self, environ):
        RequestBase.__init__(self, environ)
        self.endpoint = None
        self.view_args = None
		
#Response繼承werkzeug的Response類
class Response(ResponseBase):
    default_mimetype = 'text/html'

#請求的全局變量類
class _RequestGlobals(object):
    pass

#請求上下文初始化
class _RequestContext(object):
   
    def __init__(self, app, environ):
        self.app = app
        self.url_adapter = app.url_map.bind_to_environ(environ)
        self.request = app.request_class(environ)
        self.session = app.open_session(self.request)
        self.g = _RequestGlobals()
        self.flashes = None
'''
調用with的時候就會執行
'''
    def __enter__(self):
        _request_ctx_stack.push(self)

'''
with離開后就會執行
自定義上下文管理
class Diycontextor:
    def __init__(self,name,mode):
        self.name = name
        self.mode = mode

    def __enter__(self):
        print "Hi enter here!!"
        self.filehander = open(self.name,self.mode)
        return self.filehander

    def __exit__(self,*para):
        print "Hi exit here"
        self.filehander.close()

with Diycontextor('py_ana.py','r') as f:
    for i in f:
        print i
'''
    def __exit__(self, exc_type, exc_value, tb):
       
        if tb is None or not self.app.debug:
            _request_ctx_stack.pop()

'''
 self.url_adapter = app.url_map.bind_to_environ(environ)
 >>> m = Map([
        ...     Rule('/', endpoint='index'),
        ...     Rule('/downloads/', endpoint='downloads/index'),
        ...     Rule('/downloads/<int:id>', endpoint='downloads/show')
        ... ])
        >>> urls = m.bind("example.com", "/")
        >>> urls.build("index", {})
        '/'
        >>> urls.build("downloads/show", {'id': 42})
        '/downloads/42'
        >>> urls.build("downloads/show", {'id': 42}, force_external=True)
        'http://example.com/downloads/42'
'''
def url_for(endpoint, **values):
  
    return _request_ctx_stack.top.url_adapter.build(endpoint, values)

'''
flash實現,通過get_flashed_messages獲取消息
'''
def flash(message):
   
    session['_flashes'] = (session.get('_flashes', [])) + [message]

def get_flashed_messages():
    
    flashes = _request_ctx_stack.top.flashes
    if flashes is None:
        _request_ctx_stack.top.flashes = flashes = \
            session.pop('_flashes', [])
    return flashes

'''
實現render_template功能,模板名和{content}
'''
def render_template(template_name, **context):
    
    current_app.update_template_context(context)
    return current_app.jinja_env.get_template(template_name).render(context)

'''
實現render_template_string功能,模板名和{content}
'''
def render_template_string(source, **context):
    
    current_app.update_template_context(context)
    return current_app.jinja_env.from_string(source).render(context)

def _default_template_ctx_processor():
   
    reqctx = _request_ctx_stack.top
    return dict(
        request=reqctx.request,
        session=reqctx.session,
        g=reqctx.g
    )

def _get_package_path(name):
    try:
        return os.path.abspath(os.path.dirname(sys.modules[name].__file__))
    except (KeyError, AttributeError):
        return os.getcwd()

'''
Flask類
'''
class Flask(object):

'''
全局變量
'''
    request_class = Request
    response_class = Response
    static_path = '/static'
    secret_key = None
    session_cookie_name = 'session'
    jinja_options = dict(
        autoescape=True,
        extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']
    )

'''
當前模塊名
app=Flask(__name__)

'''
    def __init__(self, package_name):
        self.debug = False
        self.package_name = package_name
        self.root_path = _get_package_path(self.package_name)
        self.view_functions = {}
        self.error_handlers = {}
        self.before_request_funcs = []
        self.after_request_funcs = []
        self.template_context_processors = [_default_template_ctx_processor]
		
        self.url_map = Map()
		
"""
A WSGI middleware that provides static content for development
    environments or simple server setups. Usage is quite simple::

        import os
        from werkzeug.wsgi import SharedDataMiddleware

        app = SharedDataMiddleware(app, {
            '/shared': os.path.join(os.path.dirname(__file__), 'shared')
        })
"""

        if self.static_path is not None:
            self.url_map.add(Rule(self.static_path + '/<filename>',
                                  build_only=True, endpoint='static'))
            if pkg_resources is not None:
                target = (self.package_name, 'static')
            else:
                target = os.path.join(self.root_path, 'static')
            self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {
                self.static_path: target
            })       
        self.jinja_env = Environment(loader=self.create_jinja_loader(),
                                     **self.jinja_options)
        self.jinja_env.globals.update(
            url_for=url_for,
            get_flashed_messages=get_flashed_messages
        )

'''
FileSystemLoader(BaseLoader)
Loads templates from the file system.  This loader can find templates
    in folders on the file system and is the preferred way to load them.

    The loader takes the path to the templates as string, or if multiple
    locations are wanted a list of them which is then looked up in the
    given order::

    >>> loader = FileSystemLoader('/path/to/templates')
    >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])
	
	 A very basic example for a loader that looks up templates on the file
    system could look like this::

        from jinja2 import BaseLoader, TemplateNotFound
        from os.path import join, exists, getmtime

        class MyLoader(BaseLoader):

            def __init__(self, path):
                self.path = path

            def get_source(self, environment, template):
                path = join(self.path, template)
                if not exists(path):
                    raise TemplateNotFound(template)
                mtime = getmtime(path)
                with file(path) as f:
                    source = f.read().decode('utf-8')
                return source, path, lambda: mtime == getmtime(path)
				
PackageLoader(BaseLoader)
    If the package path is not given, ``'templates'`` is assumed.
	默認值為templates
'''
    def create_jinja_loader(self):
        
        if pkg_resources is None:
            return FileSystemLoader(os.path.join(self.root_path, 'templates'))
        return PackageLoader(self.package_name)

'''
template_context_processors=[dict(
        request=reqctx.request,
        session=reqctx.session,
        g=reqctx.g]
'''
    def update_template_context(self, context):
       
        reqctx = _request_ctx_stack.top
        for func in self.template_context_processors:
            context.update(func())

'''
整體APP啟動入口,啟動后進行如下幾個步驟:
1、判斷是否有設置DEBUG
2、運行rum_simple()
app = Flask(__name__)
if __name__ == '__main__():
	app.run()
	
app.run() 
	run_simple(host, port, self, **options) 
	Start a WSGI application. Optional features include a reloader,
    multithreading and fork support.	

'''
    def run(self, host='localhost', port=5000, **options):
       
        from werkzeug import run_simple
        if 'debug' in options:
            self.debug = options.pop('debug')
        options.setdefault('use_reloader', self.debug)
        options.setdefault('use_debugger', self.debug)
        return run_simple(host, port, self, **options)

    def test_client(self):
        
        from werkzeug import Client
        return Client(self, self.response_class, use_cookies=True)

    def open_resource(self, resource):
       
        if pkg_resources is None:
            return open(os.path.join(self.root_path, resource), 'rb')
        return pkg_resources.resource_stream(self.package_name, resource)

    def open_session(self, request):
       
        key = self.secret_key
        if key is not None:
            return SecureCookie.load_cookie(request, self.session_cookie_name,
                                            secret_key=key)

    def save_session(self, session, response):
      
        if session is not None:
            session.save_cookie(response, self.session_cookie_name)

    def add_url_rule(self, rule, endpoint, **options):
       
        options['endpoint'] = endpoint
        options.setdefault('methods', ('GET',))
        self.url_map.add(Rule(rule, **options))


'''
@app.route('/test')
def test():
	pass
	
route是一個裝飾器,它干了2個事情:
1、添加url到map里
2、添加函數名到視圖函數{'test':test}
'''
    def route(self, rule, **options):
        
        def decorator(f):
            self.add_url_rule(rule, f.__name__, **options)
            self.view_functions[f.__name__] = f
            return f
        return decorator

'''
A decorator that is used to register a function give a given
        error code.  Example::

            @app.errorhandler(404)
            def page_not_found():
                return 'This page does not exist', 404

        You can also register a function as error handler without using
        the :meth:`errorhandler` decorator.  The following example is
        equivalent to the one above::

            def page_not_found():
                return 'This page does not exist', 404
            app.error_handlers[404] = page_not_found
			
			error_handlers = {page_not_found:404}

'''	
    def errorhandler(self, code):
       
        def decorator(f):
            self.error_handlers[code] = f
            return f
        return decorator
'''
請求開始前做准備工作,比如數據庫連接,用戶驗證
@app.before_request  
def before_request():  
    #可在此處檢查jwt等auth_key是否合法,  
    #abort(401)  
    #然后根據endpoint,檢查此api是否有權限,需要自行處理  
    #print(["endpoint",connexion.request.url_rule.endpoint])  
    #abort(401)  
    #也可做ip檢查,以阻擋受限制的ip等   
'''
    def before_request(self, f):
        
        self.before_request_funcs.append(f)
        return f

    def after_request(self, f):
        self.after_request_funcs.append(f)
        return f

    def context_processor(self, f):
        self.template_context_processors.append(f)
        return f
'''
 Here is a small example for matching:

        >>> m = Map([
        ...     Rule('/', endpoint='index'),
        ...     Rule('/downloads/', endpoint='downloads/index'),
        ...     Rule('/downloads/<int:id>', endpoint='downloads/show')
        ... ])
        >>> urls = m.bind("example.com", "/")
        >>> urls.match("/", "GET")
        ('index', {})
        >>> urls.match("/downloads/42")
        ('downloads/show', {'id': 42})
'''
    def match_request(self):
        rv = _request_ctx_stack.top.url_adapter.match()
        request.endpoint, request.view_args = rv
        return rv
		
'''
分發請求
1、獲取endpoint和values,即請求url和參數
2、調用視圖函數view_functions[endpoint](**values)
3、處理異常錯誤
'''		
    def dispatch_request(self):
        
        try:
            endpoint, values = self.match_request()
            return self.view_functions[endpoint](**values)
        except HTTPException, e:
            handler = self.error_handlers.get(e.code)
            if handler is None:
                return e
            return handler(e)
        except Exception, e:
            handler = self.error_handlers.get(500)
            if self.debug or handler is None:
                raise
            return handler(e)
'''
from werkzeug.wrappers import BaseResponse as Response

        def index():
            return Response('Index page')

        def application(environ, start_response):
            path = environ.get('PATH_INFO') or '/'
            if path == '/':
                response = index()
            else:
                response = Response('Not Found', status=404)
            return response(environ, start_response)
'''
    def make_response(self, rv):
      
        if isinstance(rv, self.response_class):
            return rv
        if isinstance(rv, basestring):
            return self.response_class(rv)
        if isinstance(rv, tuple):
            return self.response_class(*rv)
        return self.response_class.force_type(rv, request.environ)

    def preprocess_request(self):
       
        for func in self.before_request_funcs:
            rv = func()
            if rv is not None:
                return rv

    def process_response(self, response):
        
        session = _request_ctx_stack.top.session
        if session is not None:
            self.save_session(session, response)
        for handler in self.after_request_funcs:
            response = handler(response)
        return response

    def wsgi_app(self, environ, start_response):
        
        with self.request_context(environ):
            rv = self.preprocess_request()
            if rv is None:
                rv = self.dispatch_request()
            response = self.make_response(rv)
            response = self.process_response(response)
            return response(environ, start_response)

    def request_context(self, environ):
        
        return _RequestContext(self, environ)

    def test_request_context(self, *args, **kwargs):
       
        return self.request_context(create_environ(*args, **kwargs))
'''
app=Flask(__name__)

call(self, environ, start_response) 
			wsgi_app(self, environ, start_response) 
			wsgi_app是flask核心:

'''
    def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)

# context locals
_request_ctx_stack = LocalStack()
current_app = LocalProxy(lambda: _request_ctx_stack.top.app)
request = LocalProxy(lambda: _request_ctx_stack.top.request)
session = LocalProxy(lambda: _request_ctx_stack.top.session)
g = LocalProxy(lambda: _request_ctx_stack.top.g)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM