20181030django day2 请求、响应、cookie、session、类视图

一、请求

1、url截取,例如http://127.0.0.1:8000/class/room/tianye/19

子app路由截取:

url(r'room/([a-z]+)/([0-9]+)', views.room),

视图:

def room(request,name,age):
    return HttpResponse('name:'+name+'age'+age)

2、查询字符串,如http://127.0.0.1:8000/class/room/?name=tianye&age=19

路由:

    # 1.2、get去参数
    url(r'room/$',views.person)

视图:

# 1.2、get方式获取数据
def person(request):
    name = request.GET.get('name')
    age = request.GET.get('age')
    return HttpResponse('name:'+name+',age:'+age)

3、请求体(body)中发送的数据,比如表单数据、json、xml;

# 1.3、路由请求体(body)中发送的数据,比如表单数据、json、xml;
    url(r'json_data/$',views.get_json)
# 1.3、请求体(body)中发送的数据,比如表单数据、json、xml;
def get_json(request):
    body = request.body
    print(body)
    json_data = json.loads(body)
    print(json_data)
    return HttpResponse(json.dumps(json_data))

4、在http报文的头(header)中,包括自定义头和取系统的头。

注意:自定义头的key,系统会自动添加HTTP_,所以取得时候需要处理!

# 1.4、系统请求头和自定义请求头获取
def get_head(request):
    content_type = request.META['CONTENT_TYPE']
    content_name = request.META['HTTP_NAME']
    print(content_type)
    print(content_name)
    return HttpResponse('nihao')

二、响应:

1、通过Httpresponse,可以通过res['name'] = 'ty',添加响应头

# 2.1、HttpResponse响应:Response(content=响应体, content_type=响应体数据类型, status=状态码)
def get_res(request):
    # 方式一:
    # return HttpResponse('python','Content-Type: text/Html',status=200)
    #方式二:
    res = HttpResponse('python1', 'Content-Type: text/Html', status=200)
    res['name'] = 'ty'  # 自定义响应头
    return res

2、

若要返回json数据,可以使用JsonResponse来构造响应对象,作用:

  • 帮助我们将数据转换为json字符串
  • 设置响应头Content-Type为 application/json
# 2.2JsonResponse响应返回json,注意返回的放一个字典即可
def get_json(request):
    return JsonResponse({"name": "田野", "age": "18"})

三、cookie

1、cookie特点:

  • Cookie以键值对的格式进行信息的存储。
  • Cookie基于域名安全,不同域名的Cookie是不能互相访问的
  • 当浏览器请求某网站时,会将浏览器存储的跟网站相关的所有Cookie信息提交给网站服务器。

2、设置Cookie

可以通过HttpResponse对象中的set_cookie方法来设置cookie。

HttpResponse.set_cookie(cookie名, value=cookie值, max_age=cookie有效期)
  • max_age 单位为秒,默认为None。如果是临时cookie,可将max_age设置为None。

示例:

3 读取Cookie

可以通过HttpRequest对象的COOKIES属性来读取本次请求携带的cookie值。request.COOKIES为字典类型

# 3、cookie
def get_cookie(request):
    # 1、读取cookie
    cookie1 = request.COOKIES.get('my_cookie')
    print(cookie1)
    # print('*'*100)
    # 2、设置cookie  HttpResponse.set_cookie(cookie名, value=cookie值, max_age=cookie有效期)
    res = HttpResponse('ok')
    res.set_cookie('my_cookie','ty',max_age=3600)
    return res

四、类视图

# 4、配置类视图as_view()
    url(r'register/$',views.RegisterView.as_view())

通过

views.RegisterView.as_view()方法内部是一个闭包,返回一个view,执行view方法,进入dispatch()

dispatch()方法内部判断request.method方法是否是类里的方法,如果是则执行。

 @classonlymethod
    def as_view(cls, **initkwargs):
        """Main entry point for a request-response process."""
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError("You tried to pass in the %s method name as a "
                                "keyword argument to %s(). Don't do that."
                                % (key, cls.__name__))
            if not hasattr(cls, key):
                raise TypeError("%s() received an invalid keyword %r. as_view "
                                "only accepts arguments that are already "
                                "attributes of the class." % (cls.__name__, key))

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get
            self.request = request
            self.args = args
            self.kwargs = kwargs
            return self.dispatch(request, *args, **kwargs)
        view.view_class = cls
        view.view_initkwargs = initkwargs

        # take name and docstring from class
        update_wrapper(view, cls, updated=())

        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())
        return view

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

视图类装饰方法一:

在路由中装饰:

在视图里写闭包函数my_decorator(func)

def my_decorator(func):
    def wrapper(request, *args, **kwargs):
        print('自定义装饰器被调用')
        print('请求路径%s' % request.path)
        return func(request, *args, **kwargs)
    return wrapper

路由中对as_view()进行装饰

 url(r'register/$', my_decorator(views.RegisterView.as_view()))

视图类装饰方法二:

给类装饰

需要引入包

from django.utils.decorators import method_decorator

使用method_decorator原因是,如果直接给方法装饰,方法里第一个参数是self,但是闭包里的方法第一个属性是request,所以method_decorator默认会给方法第一个参数加入self。

# 单独装饰函数,name写入函数名,如果装饰所有的函数需要name='dispatch'
@method_decorator(my_decorator, name='get')
class RegisterView(View):
    '''类视图:处理注册'''

    def get(self, request):
        '''处理注册页面,返回注册页面'''
        print(request.method)
        # return render(request, './static_files/register.html')
        return HttpResponse('get')

    def post(self, request):
        '''处理注册页面,返回注册页面'''
        print(request.method)
        # return render(request, './static_files/register.html')
        return HttpResponse('post')

视图类装饰方法三:

用一个扩展类去模拟View的as_view()方法,并去装饰

   # 4.3第三种方式装饰视图类
    url(r'DemoView/$', views.DemoView.as_view())
class MyDecoratorMixin(View):
    @classmethod
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        view = my_decorator(view)
        return view


class DemoView(MyDecoratorMixin):
    def get(self, request):
        print('get方法')
        return HttpResponse('ok')

    def post(self, request):
        print('post方法')
        return HttpResponse('ok')

猜你喜欢

转载自blog.csdn.net/weixin_42670402/article/details/83548394