Flask笔记(一)


在这里插入图片描述

pipenv 创建虚拟环境

  • 全局安装 pipenv,通过命令 pip install pipenv
  • 打开终端,进入目标文件夹,输入命令 pipenv install,绑定项目
  • 输入命令 pipenv shell,进入虚拟环境
  • 输入命令 pipenv install flask,安装 flask
  • 最后 exit, 退出虚拟环境

配置文件

  • 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)
    
  • 20
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值