flask基础知识

dacaoxin

Posted by dacaoxin on December 27, 2018

1. flask注册路由的两种方法

  • 使用装饰器,如下代码所示
1
2
3
4
5
6
    app = Flask(__name__)
    app.config.from_object('config')

    @app.route('/')
    def hello():
        return 'hello flask!!!'
  • 使用路由注册函数
1
    app.add_url_rule('/', view_func=hello)

查看flask原码可以发现,方法一中使用装饰器实际上还是调用了add_url_rule()方法注册路由。推荐使用装饰器来注册,因为这样代码会更简洁优雅。

2. run()函数的参数

示例代码:

1
    app.run(host='0.0.0.0', debug=True, port=88)
  • host参数指定了主机的ip,设置为’0.0.0.0’,则局域网内所有机器均可访问到页页
  • port可以指定端口,不设置的话,默认是5000端口
  • debug设置为True的话,在pycharm中修改了代码并保存时,flask的web服务会自动重启,并加载新代码

3. flask中的配置文件

flask提供了一个from_object()的函数,可以用于加载自定义的配置文件,文件名字没有限制,后缀是.py

1
2
    app.config.from_object('config')
    print(app.config['DEBUG'])      # 可以取到config.py里DEBUG变量的值

这里有两点需要注意:

  • flask使用from_object()加载的配置文件中定义的变量,必须要全部大写,否则会被From_object()忽略
  • DEBUG这个变量默认的值是False

4. flask视图函数的返回值

flask视图函数形式如下:

1
2
3
    # @app.route('/')
    def hello():
        return 'hello flask!!!'

函数的返回值给人的感觉是和普通函数没有什么区别,但是实际上它的返回值会经过flask处理一下,变成一个Response对象。它还可以写成下面形式:

1
2
3
4
5
6
7
8
9
10
11
12
13
    from flask import make_response

    @app.route('/')
    def hello():

        headers = {
            'content-type': 'text/html'
        }

        response = make_response('hello, flask', 404)
        rsponse.headers = headers

        return response

使用make_response()构造一个Response对象,它的参数是返回的内容以及status_code(如200, 301, 404)。Response对象也可以设置headers成员, 通过headers里的content-type告诉client,返回的字符串的处理方式。如:

text/html : 表示是html文本格式 text/plain : 表示是普通字符串格式 application/json : 表示是json串格式

headers里还可以设置’location’,并且配合Response对象的status_code设为301来实现重定向, 如:

1
2
3
4
5
6
7
8
9
10
11
12
    @app.route('/')
    def hello():

        headers = {
            'content-type': 'text/html',
            'location': 'https://www.baidu.com'
        }

        response = make_response('hello, flask', 301)
        response.headers = headers

        return response

当然,很多时候并不是直接返回一个Response对象,而是以元组的形式返回, 如:

1
    return 'hello, flask', 301, headers