flask第四編

42686 ワード

目次
  • 一、flaskコンテキストソース分析(詳細はtxtとピクチャを参照)
  • 1、具体的な流れ及びソース分析
  • 2、セッションおよび要求拡張分析
  • 二、flask-sessionの使用
  • 三、データベース接続プール
  • 四、flask-script
  • 一、flaskコンテキストソース分析(詳細はtxtとピクチャを参照)
    1、具体的な流れ及びソース分析
             (ctx):
        1 flask     , 6     
        # context locals
    	_request_ctx_stack = LocalStack()       # LocalStack  
    	_app_ctx_stack = LocalStack()			# LocalStack  
    	current_app = LocalProxy(_find_app)     # LocalProxy  
    	request = LocalProxy(partial(_lookup_req_object, "request"))   # LocalProxy  
    	session = LocalProxy(partial(_lookup_req_object, "session"))   #  LocalProxy  
    	g = LocalProxy(partial(_lookup_app_object, "g"))  # LocalProxy  
        2      app()  ,  Flask  __call__()return self.wsgi_app(environ, start_response)
        3   wsgi_app()
        	3.1   ctx = self.request_context(environ),  RequestContext  
            def request_context(self,environ):
                return RequestContext(self,environ)
              RequestContext   
            Class RequestContext(object):
                def __init__(self,app,environ,request=None,session=None):
                	```
                  	if request is None:
                        request = app.request_class(environ)
                    self.request = request
            		self.session = session
           	            request    session 
            3.2   ctx.push()-->RequestContext   push  
            	  _request_ctx_stack.push(self)  self ctx  
                      _request_ctx_stack = LocalStack(),  LocalStack   push  
            def push(self, obj):  
            """Pushes a new item to the stack"""
           		rv = getattr(self._local, "stack", None)  #      self._local,  "stack"  ,    None;self_local  __init__        self._local = Local();   Local() flask            local  , ()   
            	if rv is None:   #       stack,  None
                	self._local.stack = rv = []
            	rv.append(obj)  #  ctx        ,storage    {'  id1':{'stack':[ctx,]},{'  id2':{'stack':[ctx,]}},...}
            	return rv
    	4            request  ,  print(request)
        	4.1       request = LocalProxy(partial(_lookup_req_object, "request"))  ,request     LocalProxy,        ,    request  。request      __repr__  ,obj = self._get_current_object(),  self._get_current_object()def _get_current_object(self):
            	if not hasattr(self.__local, "__release_local__"):  #  ,self.__local  __init__      ,object.__setattr__(self, "_LocalProxy__local", local)       _ __  -->self._LocalProxy__local = local
                	return self.__local()  #        , ()      _lookup_req_object  
            	try:
                	return getattr(self.__local, self.__name__)
            	except AttributeError:
                	raise RuntimeError("no object bound to %s" % self.__name__)
           	4.2         
    		def _lookup_req_object(name):  #     request
        		top = _request_ctx_stack.top   #   LocalStack   top  ,        ,          ctx  
        		if top is None:
            		raise RuntimeError(_request_ctx_err_msg)
        		return getattr(top, name)  #     ,          request  
            # top  
            def top(self)
            try:
                return self._local.stack[-1]   #         ctx  
            except (AttributeError, IndexError):
                return None
            4.3print(request)         request   __str__;  ,        print(request.method)           request method  
    	5     ctx.auto_pop(error), ctx    
    

    2、セッション及び要求拡張分析について
    # session  
    1     app    open_session---->   wsgi_app()-->ctx = self.request_context(environ),  ctx.push()---->
            if self.session is None:
                session_interface = self.app.session_interface  # self ctx  ,ctx   app  flask  ,session_interface = SecureCookieSessionInterface()
                self.session = session_interface.open_session(self.app, self.request)
    
                if self.session is None:  #       None  ,     session
                    self.session = session_interface.make_null_session(self.app) 
    2     app    save_session----->-response = self.full_dispatch_request()     :   before_first_request,before_request,    ,after_request,savesession
    self.full_dispatch_request()---->  :self.finalize_request(rv)--->self.process_response(response)---->  :self.session_interface.save_session(self, ctx.session, response)
    #       
    before_first_request,before_request,after_request    
    # flask       ,     
    -ctx:
    	- :RequestContext  :   request session
    	-   :_request_ctx_stack.push(self)   :ctx   storage   
    -app_ctx:
    	- :AppContext(self)   :      app g
    	-   _app_ctx_stack.push(self)    :app_ctx   storage   
    # g    ?
               g  ,g     global 
    g                 ,        (           )
    # g   session   
    g          (       )
    session:     ,              
    #     
    request session      ,        。   LocalProxy  ,    request session   。
    

    二、flask-sessionの使用
    1      flask session       cookie 
    2          ,    ,redis(   )。。。
    3       :flask-session
    #      
    from flask import Flask,session
    import redis
    from flask_session import RedisSessionInterface
    app = Flask(__name__)
    
    conn = redis.Redis(host='127.0.0.1',port=6379)
    app.session_interface = RedisSessionInterface(conn,key_prefix='lqz')     # session_interface = SecureCookieSessionInterface()  session     cookie  
    @app.route('/set_session')
    def set_session():
        session['age']='123'
        return 'session   ,  age=123'
    @app.route('/get_session')
    def get_session():
        s = session.get('age','   ')
        return '    session '+s
    if __name__ == '__main__':
        app.run()
    #      app.config
    from flask import Flask,session
    from flask_session import Session
    from redis import Redis
    from datetime import timedelta
    app = Flask(__name__)
    
    app.config['SESSION_TYPE'] = 'redis'
    app.config['SESSION_REDIS'] = Redis(host='127.0.0.1',port='6379')
    app.config['SESSION_KEY_PREFIX'] = 'lqz'
    #   session     ,   31 
    app.config['PERMANENT_SESSION_LIFETIME']=timedelta(days=31) 
    app.config.from_object('settings.Pro')
    Session(app)  
    @app.route('/set_session')
    def set_session():
        session['name']='lqz'
        return 'session   ,  name=lqz'
    @app.route('/get_session')
    def get_session():
        s = session.get('name','   ')
        return '    session '+s
    if __name__ == '__main__':
        app.run()
    #           settings.py
    from flask import Flask,session
    from flask_session import Session
    app = Flask(__name__)
    
    # app.config['SESSION_TYPE'] = 'redis'
    # app.config['SESSION_REDIS'] = Redis(host='127.0.0.1',port='6379')
    # app.config['SESSION_KEY_PREFIX'] = 'lqz'
    # #   session     
    # app.config['PERMANENT_SESSION_LIFETIME']=timedelta(days=31)
    app.config.from_object('settings.Pro')
    Session(app)   #        ,            ,           ,      
    @app.route('/set_session')
    def set_session():
        session['name']='lqz'
        return 'session   ,  name=lqz'
    @app.route('/get_session')
    def get_session():
        s = session.get('name','   ')
        return '    session '+s
    if __name__ == '__main__':
        app.run()
    # settings.py 
    from redis import Redis
    from datetime import timedelta
    class Pro:
        DEBUG = True
        SESSION_TYPE = 'redis'
        SESSION_REDIS = Redis(host='127.0.0.1',port='6379')
        SESSION_KEY_PREFIX = 'lqz'
        PERMANENT_SESSION_LIFETIME = timedelta(days=31)
    
    

    三、データベース接続プール
    https://www.cnblogs.com/liuqingzheng/articles/9006055.html
        
    1          
    #      ,        curser       ,     
    conn = pymysql.Connect(host='127.0.0.1', user='root', password="123", database='luffy', port=3306)
    curser = conn.cursor()
    #   
    #    :     ,           ,        
    #   
    conn = pymysql.Connect(host='127.0.0.1', user='root', password="123", database='luffy', port=3306)
    curser = conn.cursor()
    
    2         
    	-pip3 install DButils
        -    :
        	       (           ,       close  ,     ,            ,         。      ,      )
               :          ,         ,      ,pool    
    
    3     
    	-   :  sql_pool.py
        import pymysql
        # from DBUtils.PooledDB import PooledDB
        from dbutils.pooled_db import PooledDB
        POOL = PooledDB(
            creator=pymysql,  #           
            maxconnections=6,  #            ,0 None        
            mincached=2,  #     ,              ,0     
            maxcached=5,  #            ,0 None   
            maxshared=3,  #              ,0 None      。PS:   ,  pymysql MySQLdb     threadsafety  1,          ,_maxcached   0,            。
            blocking=True,  #              ,      。True,  ;False,       
            maxusage=None,  #               ,None     
            setsession=[],  #             。
            ping=0,
            # ping MySQL   ,        。
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123',
            database='luffy',
            charset='utf8'
        )
        
        -   :  
        from sql_pool import POOL
    	conn = POOL.connection() #           (    ,    )
        curser = conn.cursor()
        curser.execute('select * from luffy_order where id<2')
        res=curser.fetchall()
        print(res)
    

    四、flask-script
    1 django       python manage.py runserver 
    2    flask-script       
    	pip3 install flask-script
        
    3   
    	-    runserver
        -     
    
    from flask import Flask
    from flask_script import Manager
    app = Flask(__name__)
    manager=Manager(app)
    
    #       
    @manager.command
    def custom(arg):
        """
             
        python manage.py custom 123
        :param arg:
        :return:
        """
        print(arg)
    
    @manager.option('-n', '--name', dest='name')
    @manager.option('-u', '--url', dest='url')
    def cmd(name, url):
        """
             (-n     --name)
          : python manage.py  cmd -n lqz -u http://www.oldboyedu.com
          : python manage.py  cmd --name lqz --url http://www.oldboyedu.com
        :param name:
        :param url:
        :return:
        """
        print(name, url)
    #    ?
    # excel        ,     ,   
    
    @app.route('/')
    def index():
        return '  '
    
    if __name__ == '__main__':
        manager.run()
    #     ,  :python3       .py runserver
    #python3 manage.py runserver --help