初始flask

创建flask项目

image.png

解读flask程序

image.png

代码分为3部分

  • 导入安装好的flask包,通过flask类,flask类即为flask的核心,实例化这个flask类到一个实例化对象app,__name__这个参数,python会根据所处的模块来赋予他相应的值。
from flask import Flask

app = Flask(__name__)
  • @app.route('/')是匹配url的,flask里面是以装饰器来实现的,如果匹配到了url就会触发下面的视图函数执行,并且return回具体的数据给前端或者移动端
@app.route('/')      #匹配url
def hello_world():
    return 'Hello World!'
  • app.run源码下在内部定义了默认的ip+端口为127.0.0.1:5000
if __name__ == '__main__':
    app.run()

这里需要注意flask正是依赖了werkzeug模块(flask有5个依赖包,分别是:jinja2、Makeupsafe、werkzeug、click、itdangerous),由werkzeug模块实现了socket服务端

带你走进源码世界

1 app.run() 调用 werkzeug.serving的run_simple(host, port, self, **options)
2 self()等价于app(), app()调用Flask类的__call__方法
3 Flask类的__call__方法返回了 self.wsgi_app(environ, start_response)
4 flask程序的执行过程都在 self.wsgi_app(environ, start_response)中

具体代码:

def run(self, host=None, port=None, debug=None,
            load_dotenv=True, **options):
       
         ...
        
         _host ='127.0.0.1'
         _port = 5000
        
         ...
            
         host = host or sn_host or _host
         port = int(port or sn_port or _port)
            
         ...
    
         from werkzeug.serving import run_simple

            try:
                run_simple(host, port, self, **options)
            finally:
                # reset the first request information if the development server
                # reset normally.  This makes it possible to restart the server
                # without reloader and that stuff from an interactive shell.
                self._got_first_request = False
    def wsgi_app(self, environ, start_response):
        """The actual WSGI application. This is not implemented in
        :meth:`__call__` so that middlewares can be applied without
        losing a reference to the app object. Instead of doing this::

            app = MyMiddleware(app)

        It's a better idea to do this instead::

            app.wsgi_app = MyMiddleware(app.wsgi_app)

        Then you still have the original application object around and
        can continue to call methods on it.

        .. versionchanged:: 0.7
            Teardown events for the request and app contexts are called
            even if an unhandled error occurs. Other events may not be
            called depending on when an error occurs during dispatch.
            See :ref:`callbacks-and-errors`.

        :param environ: A WSGI environment.
        :param start_response: A callable accepting a status code,
            a list of headers, and an optional exception context to
            start the response.
        """
        ctx = self.request_context(environ)
        error = None
        try:
            try:
                ctx.push()
                response = self.full_dispatch_request()
            except Exception as e:
                error = e
                response = self.handle_exception(e)
            except:  # noqa: B001
                error = sys.exc_info()[1]
                raise
            return response(environ, start_response)
        finally:
            if self.should_ignore_error(error):
                error = None
            ctx.auto_pop(error)

    def __call__(self, environ, start_response):
        """The WSGI server calls the Flask application object as the
        WSGI application. This calls :meth:`wsgi_app` which can be
        wrapped to applying middleware."""
        return self.wsgi_app(environ, start_response)

关键词:

  • werkzeug是一个WSGI工具包,本质上是一个socket服务端
  • flask基于werkzeug,flask只保留了web开发的核心功能
  • flask的执行过程都在def wsgi_app(self, environ, start_response):

注意:以后创建一个flask项目,不要用pycharm自带的flask快捷方式创建,推荐直接创建一个空的python项目

DEBUG模式

这个东西就是可以让你代码中的错误在浏览器端看的更清晰,让你死得更加明白哈哈哈!!!

4种方法:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    a = [1,2,3,4]
    print(a[4])  #很明显我们的索引已经越界了,这个肯定是会报错的
    return "hello"

if __name__ == '__main__':
    app.run(debug=True)  # 设置
from flask import Flask
app = Flask(__name__)
app.debug = True  # 设置

@app.route('/')
def hello():
    a = [1,2,3,4]
    print(a[4])
    return "hello"

if __name__ == '__main__':
    app.run()
from flask import Flask
app = Flask(__name__)
app.config.update(DEBUG=True)  # 设置

@app.route('/')
def hello():
    a = [1,2,3,4]
    print(a[4])
    return "hello"

if __name__ == '__main__':
    app.run()
  • 第四种需要在app.py所在的目录里再创建一个config.py,配置的信息一般为大写

config.py

DEBUG = True

app.py

from flask import Flask
import config  # 导入
app = Flask(__name__)

app.config.from_object(config)  # 设置

@app.route('/')
def hello():
    a = [1,2,3,4]
    print(a[4])
    return "hello"

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

image.png

posted @ 2020-02-26 16:57  JIAYIYAN  阅读(143)  评论(0编辑  收藏  举报