美文网首页
2018-12-19

2018-12-19

作者: Karl_2c80 | 来源:发表于2018-12-19 14:15 被阅读0次

    urls 基本使用

    通过导入include模块,实现对层级结构url的路由

    urls.py ---> 主路由

    from django.conf.urls import url,include
    from django.contrib import admin
    from karlapp import views
    
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^login/$', views.login),
        url(r'^api/', include('karlapp.url_api')),      # 相当于分路由api/xxx的汇聚点
    ]
    

    url_api.py ---> 分路由

    from django.conf.urls import url
    from karlapp import view_api
    
    
    urlpatterns = [
        url(r'^list.html', view_api.list),
        url(r'^add.html', view_api.add),
        url(r'^update.html', view_api.update),
        url(r'^delete.html', view_api.delete),
    ]
    

    views.py

    from django.shortcuts import render,HttpResponse
    from karlapp import models
    
    
    def login(request):
        if request.method == 'GET':
            a = [1,]
            obj_li = models.UserInfo.objects.all()
            # obj_li = models.UserInfo.objects.filter(username='test')
    
            for obj in obj_li:
                print('username ---> ', obj.username)
                print('password ---> ', obj.password)
    
        return render(request, 'login.html', locals())
    
    def index(request):
        return render(request, 'index.html', )
    
    def list(request):
        return HttpResponse("list page")
    
    def add(request):
        return HttpResponse("add page")
    
    def update(request):
        return HttpResponse("update page")
    
    def delete(request):
        return HttpResponse("delete page")
    

    urls 补充使用

    1. URL正则表达式匹配

    正则表达式元字符
    例如:如下两种等价
    url(r'^(?P<num>\d+)/update.html', views.update),
    url(r'^(?P<num>[0-9]+)/update.html', views.update),

    2. URL传递参数

    固定格式:(?P<var_name>*reg*)

    url_api.py

    from django.conf.urls import url
    from karlapp import views
    
    
    urlpatterns = [
        url(r'^list.html', views.list),
        url(r'^add.html', views.add),
        # url(r'^(?P<num>[0-9]+)/update.html', views.update),
        url(r'^(?P<num>\d+)/update.html', views.update),      # 参数num
        url(r'^delete.html', views.delete),
    ]
    

    views.py

    ...略
    
    def update(request, num):      # 传参
        print('update ---> num', num)      # 打印参数
        return HttpResponse("update page")
    
    ...略
    

    浏览器中输入 http://127.0.0.1:8000/api/321/update.html,pycharm打印如下:

    [19/Dec/2018 14:13:16] "GET /api/321/update.html HTTP/1.1" 200 11
    update ---> num 321
    

    相关文章

      网友评论

          本文标题:2018-12-19

          本文链接:https://www.haomeiwen.com/subject/labdkqtx.html