内容回顾

视图view

  • FBV CBV

  • 定义CBV

    from django.views import View
    class AddPublisher(View):
        def get(self,request,*args,**kwargs):
        	#处理get请求
        	return response
        def post(self,request,*args,**kwargs):
            #处理post请求
        	return response
    
    • 使用:

      from app01 import views
      url(r'add_publisher/',views.AddPublisher.as_view())
      

as_view的流程

  • 项目启动,执行AddPublisher.as_view()---->view
url(r'add_publisher/',views.AddPublisher.as_view())
url(r'add_publisher/',view)
  • 请求到来时执行view函数
    • 实例化AddPublisher --->self
    • self.request = request
    • 执行self.dispatch(request,*args,**kwargs)
      • 判断请求方式是否被允许 http_method_names = []
        • 允许
          • 通过反射获取到当前请求方式对应的方法 ---> handler
        • 不允许
          • self.http_method_not_allowed --->handler
      • 执行handler(request,*args,**kwargs) --->返回响应

加装饰器

  • from django.utils.decorators import method_decorator

  • 加方法上:

    @method_decorator(timer)
    def get(self,request)
    
  • 加在类上:

    @method_decorator(timer,name='get')
    @method_decorator(timer,name='post')
    class AddPublisher(View):
    
  • 加在dispatch方法上

    @method_decorator(timer)
    def dispatch(self,request):
        ret = super().dispatch(request,*args,**kwargs)
        return ret
    
    @method_decorator(timer,name='dispatch')
    class AddPublisher(View):
    

request对象

  • 属性
    • request.method-->当前的请求方式 GET POST
    • reuqest.GET ---> url上的参数 ?k1=v1&k2=v2
    • request.POST --->POST请求提交的数据
    • request.path_info ---> 路径信息 不包括ip和端口 不包括参数
    • request.body ---> 请求体 字节
    • request.FILES ---> 上传的文件
      • enctype="multipart/form-data"
      • f1.chunks()
    • request.META --> 请求头 全大写 HTTP_ -变成_
    • request.cookies --> cookie
    • request.session --> session
  • 方法
    • request.get_host() 获取主机的ip和端口
    • request.get_full_path() -->路径信息 不包括ip和端口 包括参数
    • request.is_ajax() -->是否是ajax请求

response

  • HttpResponse('字符串') --->字符串 content-type='text/html'

  • render(request,'模板的文件名',{}) --->返回一个完整的页面

  • redirect(重定向的地址) ---> Location:地址

  • JsonResponse({}) content-type='application//json'

  • JsonResponse(非字典,safe=False)

今日内容

路由系统

  • URL配置就像Django锁支撑网站的目录。它的本质是URL与要为该URL调用函数之间的映射表

  • 格式

    from django.conf.urls import url
    
    urlpatterns = [
        url(正则表达式,views视图,参数,别名),
    ]
    
    #Django1.11版本
    from django.conf.urls import url
    from . import views
    
    urlpatterns = [
        url(r'^articles/2003/$', views.special_case_2003),
        url(r'^articles/([0-9]{4})/$', views.year_archive),
        url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
        url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
    ]
    
    #Django2.0版本
    from django.urls import path,re_path
    
    urlpatterns = [
        path('articles/2003/', views.special_case_2003),
        path('articles/<int:year>/', views.year_archive),
        path('articles/<int:year>/<int:month>/', views.month_archive),
        path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
    ]
    
  • 正则表达式

    ^	$	[0-9]	[a-zA-Z]	\d	\w	.
    *	+	?
    
    • 分组
    url(r'^articles/([0-9]{4})/$', views.year_archive), --->分组  将捕获的参数按位置传参传递给视图函数 
    
    • 命名分组
    url(r'^blog/(?P<year>[0-9]{4})/$', views.blogs), --->命名分组  将捕获的参数按关键字传参传递给视图函数
    
  • 视图函数中指定默认值

    # urls.py中
    from django.conf.urls import url
    
    from . import views
    
    urlpatterns = [
        url(r'^blog/$', views.page),
        url(r'^blog/page(?P<num>[0-9]+)/$', views.page),
    ]
    
    # views.py中,可以为num指定默认值
    def page(request, num="1"):
        pass
    
  • include

    from django.conf.urls import include, url
    
    urlpatterns = [
       url(r'^admin/', admin.site.urls),
       url(r'^blog/', include('blog.urls')),  # 可以包含其他的URLconfs文件
    ]
    
  • app01.urls

    from django.conf.urls import url
    from . import views
    
    urlpatterns = [
        url(r'^blog/(?P<year>[0-9]{4})/(?P<month>\d{2})/$', views.blogs),
    ]
    
  • 传递默认参数给视图函数

    from django.conf.urls import url
    from . import views
    
    urlpatterns = [
        url(r'^blog/(?P<year>[0-9]{4})/$', views.year_archive, {'foo': 'bar'}),
    ]
    
  • 命名URL和URL反向解析

    • 命名

      url(r'^home', views.home, name='home'),  # 给我的url匹配模式起名为 home
      url(r'^index/(\d*)', views.index, name='index'),  # 给我的url匹配模式起名为index
      url(r'^blog/$',views.blog,name='blog'),
      
    • 反向解析

      • 模板

        {% url 'blog' %} -->/blog/
        
        {% url 'blog' 222 12 %}--> /blog/222/12
        
        {% url 'blog' year=222 month=12 %}--> /blog/222/12
        
      • py文件中

        from django.urls import reverse
        
        reverse('blog')  ---> '/blog/'
        
        reverse('blogs',args('2019','06')) --->/app01/blog/2019/06/
        
        reverse('blogs',kwargs={'year':'2019','month':'06'}) --->/app01/blog/2019/06/
        
        
      • 分组

        url(r'^blog/([0-9]{4})/(\d{2})/$',views.blogs,name='blogs'), 
        
      • namespace

        url(r'app01/',include('app01.urls',namespace='app01')),
        url(r'app02/',include('app02.urls',namespace='app02'))
        
        url(r'^home/$', views.home, name='home'),   # app01
        

        视图:

        ​ reverse(’app01:home‘) ——》 /app01/home/

        ​ reverse(’app02:home‘) ——》 /app02/home/

        模板:

        ​ {% url 'app01:home' %} —》 /app01/home/

书籍、出版社、作者删除三合一

  • urls

    url(r'^del_(publisher|book|author)/(\d+)/',views.delete),
    
  • views

    def delete(request,table,pk):
        print(table,pk)
        #查找对应的对象
        table_class = getattr(models,table.capitalize())
        table_class.objects.filter(pk=pk).delete()#删除
        #重定向到对应的展示页面
        return redirect(reverse(table))