(3)Flask 应用

目录

验证安装

第一个应用----Hello World

__name__的作用

启动详细参数讲解

调试模式


验证安装

首先我们通过pip查看一下我们是否已经下载成功

通过pip list命令查看

G:\IntelligentSentSingle>pip list
Package             Version
------------------- ------------
amqp                2.5.2
atomicwrites        1.3.0
attrs               19.3.0
Automat             0.8.0
Babel               2.7.0
backcall            0.1.0
billiard            3.6.1.0
celery              4.3.0
certifi             2019.9.11
cffi                1.13.2
chardet             3.0.4
Click               7.0
colorama            0.4.1
constantly          15.1.0
coreapi             2.3.3
coreapi-cli         1.0.9
coreschema          0.0.4
cryptography        2.8
cssselect           1.1.0
decorator           4.4.1
Django              2.2.2
django-filter       2.1.0
django-guardian     2.1.0
django-scrapy       0.1a1
djangorestframework 3.9.4
Flask               1.1.1
Flask-API           1.1
Flask-API-Docs      1.3.3
flower              0.9.3

可以看到flask 1.1.1已经在我们的包管理工具列表里面了

第一个应用----Hello World

下面我们来一个官网的demo演示一下简易的启动操作

from flask import Flask
app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()
D:\python3\python3.exe G:/IntelligentSentSingle/flask/Hello.py
 * Serving Flask app "Hello" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

可以看到,项目已经启动,我们现在去浏览器访问对应地址看看效果

OK,没有问题

__name__的作用

现在我们开始来讲解一下代码里面的app = Flask(__name__)里面的__name__是什么意思

class Flask(_PackageBoundObject):
    """The flask object implements a WSGI application and acts as the central
    object.  It is passed the name of the module or package of the
    application.  Once it is created it will act as a central registry for
    the view functions, the URL rules, template configuration and much more.

    The name of the package is used to resolve resources from inside the
    package or the folder the module is contained in depending on if the
    package parameter resolves to an actual python package (a folder with
    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).

    For more information about resource loading, see :func:`open_resource`.

    Usually you create a :class:`Flask` instance in your main module or
    in the :file:`__init__.py` file of your package like this::

        from flask import Flask
        app = Flask(__name__)

    .. admonition:: About the First Parameter

        The idea of the first parameter is to give Flask an idea of what
        belongs to your application.  This name is used to find resources
        on the filesystem, can be used by extensions to improve debugging
        information and a lot more.

        So it's important what you provide there.  If you are using a single
        module, `__name__` is always the correct value.  If you however are
        using a package, it's usually recommended to hardcode the name of
        your package there.

        For example if your application is defined in :file:`yourapplication/app.py`
        you should create it with one of the two versions below::

            app = Flask('yourapplication')
            app = Flask(__name__.split('.')[0])

        Why is that?  The application will work even with `__name__`, thanks
        to how resources are looked up.  However it will make debugging more
        painful.  Certain extensions can make assumptions based on the
        import name of your application.  For example the Flask-SQLAlchemy
        extension will look for the code in your application that triggered
        an SQL query in debug mode.  If the import name is not properly set
        up, that debugging information is lost.  (For example it would only
        pick up SQL queries in `yourapplication.app` and not
        `yourapplication.views.frontend`)

先看下关于Flask类的doc,里面介绍了app(import_name)的意义

大致意思就是,如果你只是把当前目录作为一个单独的模块的话,随便你取什么名字都无所谓,

但是如果你是作为一个包去引用他的话,那么请一定要注意你的import_name。

我们再来看看源码吧

 __import__(import_name)
这是get_root_path(import_name)方法里面其中的一段,从这里可以看做,它是需要将import_name当做一个package来动态加载的。

大致作用就是范围这个包的路径,这里范围的是目录的路径

那么具体哪些地方需要用到这个方法呢,我们继续看看Flask的父类_PackageBoundObject里面的代码


#第一段代码
@property
  def static_folder(self):
      """The absolute path to the configured static folder."""
      if self._static_folder is not None:
          return os.path.join(self.root_path, self._static_folder)

#第二段代码
@locked_cached_property
    def jinja_loader(self):
        """The Jinja loader for this package bound object.

        .. versionadded:: 0.5
        """
        if self.template_folder is not None:
            return FileSystemLoader(os.path.join(self.root_path, self.template_folder))
#第三段代码
 def open_resource(self, resource, mode="rb"):
        """Opens a resource from the application's resource folder.  To see
        how this works, consider the following folder structure::

            /myapplication.py
            /schema.sql
            /static
                /style.css
            /templates
                /layout.html
                /index.html

        If you want to open the :file:`schema.sql` file you would do the
        following::

            with app.open_resource('schema.sql') as f:
                contents = f.read()
                do_something_with(contents)

        :param resource: the name of the resource.  To access resources within
                         subfolders use forward slashes as separator.
        :param mode: Open file in this mode. Only reading is supported,
            valid values are "r" (or "rt") and "rb".
        """
        if mode not in {"r", "rt", "rb"}:
            raise ValueError("Resources can only be opened for reading")

        return open(os.path.join(self.root_path, resource), mode)

 看到了吗,静态文件需要它,open_resource需要它,还有一个jinja的加载器需要用到它。

所以当你把它作为一个包在外部引用并启动时,一定要写对它的import_name,否则里面的静态资源都无法获取到。

启动详细参数讲解

Flask类的run()方法在本地开发服务器上运行应用程序。

app.run(host, port, debug, options)

所有参数都是可选的

序号 参数与描述
1

host

要监听的主机名。 默认为127.0.0.1(localhost)。设置为“0.0.0.0”以使服务器在外部可用

2

port

默认值为5000

3

debug

默认为false。 如果设置为true,则提供调试信息

4

options

要转发到底层的Werkzeug服务器。

上面给出的Python脚本是从Python shell执行的。

调试模式

通过调用run()方法启动Flask应用程序。但是,当应用程序正在开发中时,应该为代码中的每个更改手动重新启动它。为避免这种不便,请启用调试支持。如果代码更改,服务器将自行重新加载。它还将提供一个有用的调试器来跟踪应用程序中的错误(如果有的话)。

在运行或将调试参数传递给run()方法之前,通过将application对象的debug属性设置为True来启用Debug模式

具体如下

app.run(debug=True)

这样你就如Django的debug一样,可以及时开发及时调试看到代码效果了,不需要重启,而且一旦报错,也可以直接在web页面上看到具体的报错信息来帮助你快速定位bug。

发布了62 篇原创文章 · 获赞 36 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/louishu_hu/article/details/103127578