• 技术文章 >Python框架 >Django

    django1和2的区别

    silencementsilencement2019-07-27 16:58:05原创4019

    Django

    路由匹配使用path和re_path代替url函数

    path匹配绝对路径,re_path匹配正则表达式路径

    from django.urls import path, re_path

    urlpatterns = [

    path(’’, index_views),

    path(‘login/’,login_views),

    path(‘register/’,register_views),

    path(‘check/’,check_views),

    path(“test/”,test_views),

    re_path(“str:user”,user_views),

    re_path(“index/(\d+)”,showcontent)

    ]

    Django的path默认支持以下5个转化器:

    str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式

    int,匹配正整数,包含0。

    slug,匹配字母、数字以及横杠、下划线组成的字符串。

    uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。

    path,匹配任何非空字符串,包含了路径分隔符

    django1与2路由的差别

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    在django1中的url在django2中为re_path

    django2中新增了path

        1.from django.urls import path

        2.不支持正则,精准匹配

        3.有5个转换器(int,str,slug,path,uuid)

        4.自定义转换器:

            1 写一个类:

            class Test:

                regex = '[0-9]{4}'

                def to_python(self, value):

                    # 写一堆处理

                    value=value+'aaa'

                    return value

                def to_url(self, value):

                    return '%04d' % value

            2 from django.urls import register_converter

            3 register_converter(Test,'ttt')

            4 path('index/<ttt:year>', views.index,name='index'),

    MVC和MTV

    1

    2

    3

    4

    5

      M          T                 V    models     template         views

     

        M          V                 C(路由+views)    models    模板    控制器

     

    其实MVC与MTV是一样的,django中为MTV,数据交互层,视图层以及控制层

    视图层:request对象

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    request对象:

    # form表单,不写method ,默认是get请求

    #     1 什么情况下用get:请求数据,请求页面,

    #     2 用post请求:向服务器提交数据

    # request.GET  字典

    # request.POST  字典

    # 请求的类型

    # print(request.method)

    # 路径

    # http://127.0.0.1:8000/index/ppp/dddd/?name=lqz

    # 协议:ip地址和端口/路径?参数(数据) 

    # print(request.path) -->/index/ppp/dddd/

    # print(request.get_full_path()) -->/index/ppp/dddd/?name=lqz

    JsonResponse

    向前端页面发json格式字符串

    1

    2

    3

    4

    封装了jsonfrom django.http import JsonResponse

     

    dic={'name':'lqz','age':18}

    li=[1,2,3,4]return JsonResponse(li,safe=False)

    专题推荐:django
    上一篇:卸载django输入什么命令 下一篇:如何测试django

    相关文章推荐

    • python怎么安装django• Django怎么更新版本• django具体做什么

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网