博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
views 视图函数
阅读量:7057 次
发布时间:2019-06-28

本文共 4175 字,大约阅读时间需要 13 分钟。

视图

1. CBV和FBV    FBV (function based view)    CBV (class based view )        CBV写法:        from django.views import View        class AddPublisher(View):                    def get(self, request):                print('这个是get')                return render(request, 'add_publisher.html')            def post(self, request):                print('这个是post')                return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})    使用:        url(r'^add_publisher/', views.AddPublisher.as_view()),2. CBV简单的流程:    1. AddPublisher.as_view() ——》 view函数    2. 当请求到来的时候才执行view函数        1. 实例化AddPublisher  ——》 self         2. self.request = request        3. 执行self.dispatch(request, *args, **kwargs)            1. 判断请求方式是否被允许                handler = getattr(self, request.method.lower(), self.http_method_not_allowed)                通过反射获取对应的方法                 GET  ——》  get                POST ——》  post                            2. 执行获取到的方法  get(request,)  或者post(request,)            3. 得到HttpResponse对象,返回给self.dispatch        4. 得到HttpResponse对象,返回django处理    3. request    request.method    ——》 请求的方式 8种  GET POST PUT DELETE OPTIONS    request.GET		  ——》 字典  url上携带的参数    request.POST	  ——》 字典  form表单通过POST请求提交的数据        print(request,type(request))  #当一个页面被请求时,Django就会创建一个包含本次请求原信息的HttpRequest对象。Django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 request 参数承接这个对象。	print(request.method)		# 请求中使用的HTTP方法的字符串表示,全大写表示。	print(request.GET)          #包含所有HTTP  GET参数的类字典对象	print(request.POST)			# 包含所有HTTP POST参数的类字典对象	print(request.path_info)	# 返回用户访问url,不包括域名	    print(request.body)			# 请求体,byte类型 request.POST的数据就是从body里面提取到的    print(request.scheme)		# 表示请求方案的字符串(通常为http或https)    print(request.get_host())	# ip 端口    print(request.get_full_path())	# 返回包含参数(查询字符串)的url(不包括域名)   request.FILES    # 上传的文件    4. response    from django.shortcuts import render, HttpResponse ,redirect            HttpResponse('字符串')				—— 》浏览器显示字符串    render(request,'模板名字',{})      —— 》返回一个完整的页面       redirect(URL)    					—— 》跳转 重定向  location:url     5. JsonResponse	JsonResponse是HttpResponse的子类,专门用来生成JSON编码的响应。类似于HttpResponsed的使用方法
from django.http import JsonResponse	ret = JsonResponse({'foo': 'bar'})	print(ret.content)        return  ret	# b'{"foo": "bar"}'
 

  

def json_data(request):    date = {"name": 'alex', 'age': 84}    import json    return HttpResponse(json.dumps(date))  #content_type: application/json     return JsonResponse(date)   #content_type: application/text

  

类型: content_type: application/json 如果是传递的是字符串 content_type: text /html;charset = utf - 8 默认只能传递字典类型,如果要传递非字典类型需要设置一下safe关键字参数。 ret = JsonResponse([1, 2, 3], safe=False)
6.装饰器的使用 1. FBV的装饰器 @装饰器 2. CBV的装饰器: from django.utils.decorators import method_decorator 1. 直接在方法上加:     @method_decorator(wrapper)     def get(self, request) 2. 给dispatch方法加     @method_decorator(wrapper)     def dispatch(self, request, *args, **kwargs) 3. 给类加     @method_decorator(wrapper, name='post')     @method_decorator(wrapper, name='get')     class AddPublisher(View)
 
# @method_decorator(wrapper, name='post') # 方法三:给类加,哪个方法用加哪个方法的名字# @method_decorator(wrapper, name='get')class AddPublisher(View):    @method_decorator(wrapper)	# 方法二:给dispatch方法加    def dispatch(self, request, *args, **kwargs):        print('执行get方法之前')        ret = super().dispatch(request, *args, **kwargs)        print('执行get方法之后')        return ret	@method_decorator(wrapper)   # 方法一:直接在方法上加    def get(self, request):        print('这个是get')        # print(self.request)        return render(self.request, 'add_publisher.html')    def post(self, request):        print('这个是post')        print(request.body)        err_msg = ''        add_name = request.POST.get('new_name')        pub_list = models.Publisher.objects.filter(name=add_name)        if add_name and not pub_list:            models.Publisher.objects.create(name=add_name)            return redirect('/publisher/')        if not add_name:            err_msg = '不能为空'        if pub_list:            err_msg = '出版社已存在'        return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': err_msg})
 

  

 

转载于:https://www.cnblogs.com/perfey/p/9671354.html

你可能感兴趣的文章
spring-mvc 与 openid4java
查看>>
iBatis简单入门教程
查看>>
将archlinux 2013-06-01版,安装配置为个人工作站
查看>>
十大流行Linux发行版
查看>>
微信公众平台消息接口开发之微信浏览器HTTP_USER_AGENT判断
查看>>
Android自定义ScrollView实现一键置顶功能
查看>>
samba配置
查看>>
php -- realpath($path) 函数
查看>>
Web开发之Goahead
查看>>
crm工作机会实体
查看>>
[分享] 【旧文新读】少一分火气,多一份和气
查看>>
如何用Entity Framework 6 连接Sqlite数据库[转]
查看>>
克隆虚机网卡出现 Device eth0 does not seem to be present, delaying initialization 错误
查看>>
Wampserver2.5配置虚拟主机出现403 Forbidden的处理方案
查看>>
非技术1-学期总结&ending 2016
查看>>
IOT数据库选型——NOSQL,MemSQL,cassandra,Riak或者OpenTSDB,InfluxDB
查看>>
MAC使用GITHUB
查看>>
php Pthread 多线程 (六) Pool类 线程池
查看>>
前端开发神级IDE-sublime text
查看>>
telnet 命令使用方法详解,telnet命令怎么用
查看>>