ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Django --- 视图层

2019-11-27 10:04:08  阅读:189  来源: 互联网

标签:self request 视图 Django kwargs method def view


目录

1.视图函数

视图函数简称视图,是一个简单的python函数,他接收web请求并返回文本响应,响应可以是一个网页,一个重定向,或者是字符串,什么都可以,但是一定要又响应。

2.小白必会三板斧

1.HttpResponse

可以返回字符串

2.render

可以调用HTML文件进行操作

3.redirect

重定向

3.JsonResponse

可以将数据按照json串的格式传给前端,但是默认的是只能传字典,字符编码默认是ascii。

from django.http import JsonResponse
def index(request):
    # dic = {'username':'wang','hobby':'骑行'}
    dic = ['上海']
    return JsonResponse(dic,safe=False,json_dumps_params = {'ensure_ascii':False},)

# 1.json_dumps_params = {'ensure_ascii':False},)   更改字符编码格式
# 2.safe=False   更改传入的数据类型

4.FBV与CBV

FBV:基于函数的视图

CBV:基于类的视图

# views视图中
from django.views import View

class MyLogin(View):
    def get(self,request):
        print('我是mylogin里面的get方法')
        return render(request,'login.html')

    def post(self,request):
        print('我是mylogin里面的post方法')
        return render(request,'ceshi.html')
    
# urls.py中
 url(r'^login/',views.MyLogin.as_view())

5.CBV源码

# View源代码
class View(object):

    http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

    def __init__(self, **kwargs):
        for key, value in six.iteritems(kwargs):
            setattr(self, key, value)

    @classonlymethod
    def as_view(cls, **initkwargs):
        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

        update_wrapper(view, cls, updated=())

        update_wrapper(view, cls.dispatch, assigned=())
        return view

    def dispatch(self, request, *args, **kwargs):
    
        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)

    def http_method_not_allowed(self, request, *args, **kwargs):
        logger.warning(
            'Method Not Allowed (%s): %s', request.method, request.path,
            extra={'status_code': 405, 'request': request}
        )
        return http.HttpResponseNotAllowed(self._allowed_methods())
    
# views.py中的代码
class MyLogin(View):
    def get(self,request):              #  方法名一定是八大请求方法的名字
        print('我是mylogin里面的get方法')
        return render(request,'login.html')

    def post(self,request):
        print('我是mylogin里面的post方法')
        return render(request,'ceshi.html')
 
# urls.py中的代码
url(r'^login/',views.MyLogin.as_view()),    本质上还是FBV,

6.给CBV加装饰器

1.直接放在类中方法的上面

2.使用内置模块,放在类方法上面 ----- 推荐

from django.utils.decorators import method_decorator

@method_decorator(outter)    # 括号内写上装饰器函数,放在需要被装饰的类方法上

3.使用内置方法,直接放在类上面

from django.utils.decorators import method_decorator

@method_decorator(outter,name='post')

7.form表单传文件需要注意的事项:

1.mothod必须改成post

2.enctype改成formdata格式

前期在使用post超后端发送请求的时候,需要去settings配置文件中注释掉一个中间件crf。

# 针对于文件的操作使用的是
file_obj = request.FILES         # django会将文件数据放在request.FILES中
file_obj.name 

with open(file_obj.name,'wb') as f:
    for line in file_obj:
        f.write(line)

标签:self,request,视图,Django,kwargs,method,def,view
来源: https://www.cnblogs.com/whkzm/p/11939973.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有