zoukankan      html  css  js  c++  java
  • Flask框架第三篇.Flask 中的 Response

    1.web框架response三剑客

    1.1 render_template

    from flask import Flask,render_template
    ​
    # 实例化产生一个Flask对象
    app = Flask(__name__)
    ​
    @app.route('/index')
    def index():
        return render_template("index.html")   
    ​
    if __name__ == '__main__':
        app.run()
    View Code

    消除黄色提示方法: templates --> Mark Directory as --> Template Folder --> jinjia2

     

    1.2 redirect

    from flask import Flask,render_template,redirect
    # 实例化产生一个Flask对象
    app = Flask(__name__)
    ​
    @app.route('/index')
    def index():
        return render_template("index.html")
    ​
    @app.route('/login')
    def login():
        return redirect("/index")
    ​
    if __name__ == '__main__':
        app.run()
    View Code

    1.3 HttpResponse

    from flask import Flask,render_template,redirect
    # 实例化产生一个Flask对象
    app = Flask(__name__)
    ​
    # 将 '/'和视图函数hello_workd的对应关系添加到路由中
    @app.route('/') # 1. v=app.route('/') 2. v(hello_world)
    def hello_world():
        return 'Hello World!'   # HttpResponse('Hello World!')
    if __name__ == '__main__':
        app.run()
    View Code

    2.send_file

    浏览器特性 可识别的Content-type 自动渲染 不可识别的Content-type 会自动下载

    from flask import Flask,render_template,redirect
    from flask import send_file
    ​
    # 实例化产生一个Flask对象
    app = Flask(__name__)
    ​
    @app.route('/index')
    def index():
        return render_template("index.html")
    ​
    @app.route('/login')
    def login():
        return redirect("/index")
    ​
    @app.route('/get_file')
    def get_file():
        return send_file("app.py")
        #返回文件内容,自动识别文件类型,Content-type中添加文件类型,Content-type:文件类型
        #返回本质是一个 instance (流媒体)
    if __name__ == '__main__':
        app.run()
    View Code

    3.jsonify

    from flask import Flask,render_template,redirect
    from flask import send_file,jsonify
    ​
    # 实例化产生一个Flask对象
    app = Flask(__name__)
    ​
    @app.route('/get_json')
    def get_json():
        data = {"k":"v"}
        # return data     # Flask 1.1.1 版本中 可以直接返回字典格式,无需jsonify
        # return jsonify(data)
        return jsonify("hello world")  # 返回标准格式的JSON字符串 先序列化JSON的字典,Content-type中加入 Application/json
    if __name__ == '__main__':
        app.run()
    View Code

     

  • 相关阅读:
    6.素数和(素数的判断)
    6.素数和(素数的判断)
    5.明明的随机数(桶排序经典例题)
    5.明明的随机数(桶排序经典例题)
    5.明明的随机数(桶排序经典例题)
    5.明明的随机数(桶排序经典例题)
    Algs4-1.2.11根据Date的API实现一个SmartDate类型
    Algs4-1.2.10编写一个类VisualCounter
    Algs4-1.2.9使用Counter统计BinarySearch检查的key个数
    Algs4-1.2.8引用型变量赋值-数组复制
  • 原文地址:https://www.cnblogs.com/lilinyuan5474/p/15568836.html
Copyright © 2011-2022 走看看