zoukankan      html  css  js  c++  java
  • Flask 学习(三)路由介绍

    Flask路由规则都是基于Werkzeug的路由模块的,它还提供了很多强大的功能。

    两种添加路由的方式

    方式一:
      @app.route('/xxxx')  # @decorator
      def index():
         return "Index"
    方式二:
      def index():
         return "Index"
      app.add_url_rule('/xxx', "n1", index)  #n1是别名 

    @app.route和app.add_url_rule参数

    @app.route和app.add_url_rule参数:
                rule,                       URL规则
                view_func,                  视图函数名称
                defaults=None,              默认值,当URL中无参数,函数需要参数时,使用defaults={'k':'v'}为函数提供参数
                endpoint=None,              名称,用于反向生成URL,即: url_for('名称')
                methods=None,               允许的请求方式,如:["GET","POST"]
                
    
                strict_slashes=None,        对URL最后的 / 符号是否严格要求,
                                            如:
                                                @app.route('/index',strict_slashes=False),
                                                    访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可
                                                @app.route('/index',strict_slashes=True)
                                                    仅访问 http://www.xx.com/index 
                redirect_to=None,           重定向到指定地址
                                            如:
                                                @app.route('/index/<int:nid>', redirect_to='/home/<nid>')
                                                或
                                                def func(adapter, nid):
                                                    return "/home/888"
                                                @app.route('/index/<int:nid>', redirect_to=func)

    举例使用

    # ============对url最后的/符号是否严格要求=========
    @app.route('/test',strict_slashes=True)  #当为True时,url后面必须不加斜杠
    def test():
        return "aaa"
    @app.route('/test',strict_slashes=False)  #当为False时,url上加不加斜杠都行
    def test():
        return "aaa"
    
    @app.route("/json_test/<int:age>" ,defaults={'age':66})
    def json_test(age):
        ret_dic = {'name': 'xiaowang', 'age': age}
        return jsonify(ret_dic) # 转换json形式

    带参数的路由

    @app.route('/hello/<name>')
    def hello(name):
        return 'Hello %s' % name
    
    @app.route('/hello/<name>_<age>_<sex>')  # 多个参数
    def hello(name,age,sex):
        return 'Hello %s,%s,%s' %(name,age,sex)

    在浏览器的地址栏中输入http://localhost:5000/hello/Joh,你将在页面上看到”Hello Joh”的字样。

    URL路径中/hello/后面的参数被作为hello()函数的name参数传了进来。

    多个参数

    # 动态路由参数
    @app.route("/json_param/<int:age>" ,strict_slashes=False)
    def json_param(age):
        ret_dic = {'name': 'xiaowang', 'age': age}
        return jsonify(ret_dic)

     endpoint

    当请求传来一个url的时候,会先通过rule找到endpoint(url_map),然后再根据endpoint再找到对应的view_func(view_functions)。通常,endpoint的名字都和视图函数名一样。
    实际上这个endpoint就是一个Identifier,每个视图函数都有一个endpoint,
    当有请求来到的时候,用它来知道到底使用哪一个视图函数
    endpoint可以解决视图函数重名的情况

    Flask中装饰器多次使用
    # 验证用户装饰器
    def wrapper(func):
        @wraps(func)
        def inner(*args, **kwargs):
            if not session.get("user_info"):
                return redirect("/login")
            ret = func(*args, **kwargs)
            return ret
        return inner
    
    @app.route("/login", methods=("GET", "POST"))
    def login():
        # 模板渲染
        # print(request.path)
        # print(request.url)
        # print(request.headers)
        if request.method == "GET":
            print(request.args.get("id"))
            text_tag = "<p>你看见了吗test:<input type='text' name='test'></p>"
            text_tag = Markup(text_tag)
            return render_template("login.html", msg=text_tag)  # sum = add_sum)
        else:
    
            # print(request.form)
            # print(request.values.to_dict())   # 这个里面什么都有,相当于body
            # print(request.json)  # application/json
            # print(request.data)
            username = request.form.get("username")
            password = request.form.get("password")
            if username == "alex" and password == "123":
                session["user_info"] = username
                # session.pop("user_info")  #删除session
                return "登录成功"
            else:
                return render_template("login.html", msg="用户名或者密码错误")
    
    
    # endpoint可以解决视图函数重名的情况
    @app.route("/detail", endpoint="detail")
    @wrapper  # f = route(wrapper(detail))
    def detail():
        print(url_for("detail"))
        return render_template("detail.html", **STUDENT)
    
    
    @app.route("/detail_list", endpoint="detail_list")
    @wrapper  # f = route(wrapper(detail_list))
    def detail_list():
        return render_template("detail_list.html", stu_list=STUDENT_LIST)
    
    
    @app.route("/detail_dict")
    def detail_dict():
        if not session.get("user_info"):
            return redirect("/login")
        return render_template("detail_dict.html", stu_dict=STUDENT_DICT)

    反向生成URL: url_for

    endpoint("name")   #别名

    @app.route('/index',endpoint="xxx")  #endpoint是别名
    def index():
        v = url_for("xxx")
        print(v)
        return "index"

    静态文件位置

    一个Web应用的静态文件包括了JS, CSS, 图片等,Flask的风格是将所有静态文件放在”static”子目录下。并且在代码或模板中,使用url_for('static')来获取静态文件目录
    
    app = Flask(__name__,template_folder='templates',static_url_path='/xxxxxx')
    
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
    <div class="page">
        {% block body %}
        {% endblock %}
    </div>

    两个常用函数

    @app.route("/bo")
    def bo():
        # return render_template("bo.html")
        return send_file("s1.py") # 发送文件(可以是图像或声音文件)
    
    
    @app.route("/json_test/<int:age>" ,defaults={'age':66})
    def json_test(age):
        ret_dic = {'name': 'xiaowang', 'age': age}
        return jsonify(ret_dic) # 转换json形式,帮助转换为json字符串, 并且设置响应头Content-Type: application/json

      

  • 相关阅读:
    什么是Code Review
    支撑5亿用户、1.5亿活跃用户的Twitter最新架构详解及相关实现
    shell的数组操作
    CDN(内容分发网络)技术原理
    云计算服务模型,第 3 部分: 软件即服务(PaaS)
    Mongodb
    360的开源项目
    用linux mail命令发送邮件[Linux]
    BZOJ2761:[JLOI2011]不重复数字(map)
    BZOJ1821:[JSOI2010]部落划分(并查集,二分)
  • 原文地址:https://www.cnblogs.com/xiao-apple36/p/11598590.html
Copyright © 2011-2022 走看看