美文网首页
理解编写Flask的基本结构

理解编写Flask的基本结构

作者: ArthurIsUsed | 来源:发表于2020-05-29 11:34 被阅读0次

    早之前看到代码里有from app import app一直不理解两个app,哪个对应哪个,各表示什么意思。原有项目结构如下

    miguelgrinberg/
      |_  venv/
      |_  app/
      |   |_ __init__.py
      |   |_ routes.py
      |_ miguelgrinberg.py
    

    __init__.py文件内容如下,这个from app import routes,表示从FLask这个实例引入routes模块,懂。

    from flask import Flask
    
    app = Flask(__name__)
    
    from app import routes
    

    routes.py内容如下: 这两个app便不清楚哪个是Flask实例,与包名app有什么关系,与启动的FLASK_APP又有什么联系。

    from app import app
    
    # The first URL maps to /, while the second maps to /index. Both routes are associated
    # with the only view function in the application, so they produce the same output,
    # which is the string that the function returns
    @app.route('/')
    @app.route('/index')
    def index():
        return "Hello World!"
    

    直到看到一段话才明白这些关系,为何这样组织代码。

    Remember the two app entities? Here you can see both together in the same sentence. The Flask application instance is called app and is a member of the app package. The from app import app statement imports the app variable that is a member of the app package. If you find this confusing, you can rename either the package or the variable to something else.

    Flask的应用实例名是app,它是名为app包的一个成员。如果觉得混淆,可以改变包名,或者Flask实例名。更改包名后Hello World的项目结构如下:


    需要更改的代码,__init__.pyroutes.py文件中,改为from helloapp import app,即从helloapp这个包中引入routes模块和名为app的Flask实例。之后才有路由策略,返回Hello World!

    当然,也可以改Flask的实例名,appHello = Flask(__name__)。

    在Ubuntu下,export FLASK_APP=miguelgrinberg,指明Flask实例对象app模块的位置。

    Flask needs to be told how to import it, by setting the FLASK_APP environment variable:
    (venv) arthur@arthur:~/PycharmProjects/miguelgrinberg$ export FLASK_APP=miguelgrinberg
    (venv) arthur@arthur:~/PycharmProjects/miguelgrinberg$ flask run
    

    由于在miguelgrinberg文件中有一条from helloapp import app,便从helloapp包中引入了Flask实例。如果没有设置FLASK_APP环境变量,会去app.py找,没有这个文件则会报错。设置变量,也指明了Flask程序的启动入口。

    侧面验证,某些hello world页面只有一个app.py,不用设置变量,直接flask run即可。内容如下:

    from flask import Flask
    app = Flask(__name__)
    @app.route('/')
    def index():
        return 'Hello World!'
    

    现在梳理一下整个启动过程。

    • 设置Flask启动路口位miguelgrinberg
    • from helloapp import app时,helloapp是一个包,自动执行__init__.py文件,实例化Flask。
    • __init__.py中有引入routes, 只不过是把FLask实例化与路由策略的建立分成两个文件。方便以后项目扩展。
    • 引入routes,设置路由策略,建立URI与相应处理函数的关系

    相关文章

      网友评论

          本文标题:理解编写Flask的基本结构

          本文链接:https://www.haomeiwen.com/subject/juqxzhtx.html