Flask笔记(一)

pipenv创建虚拟环境

吼吼吼……(此处省略一些字


配置文件

  • config.py:
    DEBUG = True
    

代码(附注释

  • demo.py:
    from flask import Flask, make_response
    
    app = Flask(__name__)
    app.config.from_object('config')
    
    @app.route('/hello/')  # 通过这个装饰器给hello函数定义一个路由,这样就可以通过http请求执行这个函数
    def hello():  # 视图函数
        # 基于类的视图(即插视图)
        return 'Hello, SixGod'
    # app.add_url_rule('/hello/', view_func=hello)
    
    @app.route('/hello2/')
    def hello2():
        # content-type默认是text/html
        return '<html><body><p>Hi, Liushen</p></body></html>'
    
    @app.route('/hello3/')
    def hello3():
        # status code: 200,404,301
        # Response
        headers = {
            'content-type': 'text/plain'  # 如果返回的是json格式的字符串,应为'application/json'
            # 'location': 'https://blog.csdn.net/hongwangdb'  # 重定向
        }
        response = make_response('<html></html>', 404)
        response.headers = headers
        return response
    
    @app.route('/hello4/')
    def hello4():
        headers = {
            'content-type': 'application/json',
            'location': 'https://blog.csdn.net/hongwangdb'
        }
        return '<html></html>', 301, headers  # 这样的写法就没有用到Response对象,本质返回的是一个元组
    
    if __name__ == '__main__':  # 保证在生产环境下不会启动flask自带的外部服务器
        # 生产环境 nginx前置服务器+uwsgi
        app.run(host='0.0.0.0', debug=app.config['DEBUG'], port=85)
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章