加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Django 14天从小白到进阶- Day3 搞定Views组件

发布时间:2020-12-17 00:08:05 所属栏目:Python 来源:网络整理
导读:本节内容 路由系统 models模型 admin? views视图 template模板 我们已经学过了基本的view写法 单纯返回字符串 It is now %s. " % now return HttpResponse(html) #return HttpResponseNotFound(' Page not found ') # Return a "created" (201) response cod

本节内容

  • 路由系统
  • models模型
  • admin?
  • views视图
  • template模板

我们已经学过了基本的view写法

单纯返回字符串

Page not found')
# Return a "created" (201) response code.
#return HttpResponse(status=201)

返回html文件  

加装饰器

users = models.Account.objects.all() return render(request,'account.html',{'account_list':users}) </pre>

只允许特定方法

@require_http_methods(["GET","POST"])
def my_view(request):

I can assume now that only GET or POST requests make it this far

# ...
pass

  

  

HttpRequest 对象

我们知道每个视图函数的request参数这个东西,但一直没正式讲,它到底是个什么样的存在?  

每一个用户请求在到达视图函数的同时,django会自动创建一个HttpRequest对象并把这个对象当做第一个参数传给要调用的views方法,HttpRequest对象里封装了本次请求所涉及的用户浏览器端数据、服务器端数据等,在views里可以通过request对象来调取相应的属性。

A string representing the scheme of the request (?or??usually).

HttpRequest.path A string representing the full path to the requested page,not including the scheme or domain.

Example: "/music/bands/the_beatles/"

HttpRequest.method A string representing the HTTP method used in the request

 

HttpRequest.content_type A string representing the MIME type of the request,parsed from the CONTENT_TYPE header.

是描述消息内容类型的因特网标准。

MIME 消息能包含文本、图像、音频、视频以及其他应用程序专用的数据。

HttpRequest.GET A dictionary-like object containing all given HTTP GET parameters. See the QueryDict documentation below.

HttpRequest.POSTHttpRequest.COOKIES A dictionary containing all cookies. Keys and values are strings.

HttpRequest.FILES A dictionary-like object containing all uploaded files. Each key in FILES is the name from the . Each value in FILES is an UploadedFile.

FILES will only contain data if the request method was POST and the

that posted to the request had enctype="multipart/form-data". Otherwise,FILES will be a blank dictionary-like object.

A dictionary containing all available HTTP headers. Available headers depend on the client and server,but here are some examples:

    ?– The length of the request body (as a string).
  • ?– The MIME type of the request body.
  • ?– Acceptable content types for the response.
  • ?– Acceptable encodings for the response.
  • ?– Acceptable languages for the response.
  • ?– The HTTP Host header sent by the client.
  • ?– The referring page,if any.
  • ?– The client’s user-agent string.
  • ?– The query string,as a single (unparsed) string.
  • ?– The IP address of the client.
  • ?– The hostname of the client.
  • ?– The user authenticated by the Web server,if any.
  • ?– A string such as??or?.
  • ?– The hostname of the server.
  • ?– The port of the server (as a string).

Attributes set by middleware

Some of the middleware included in Django’s contrib apps set attributes on the request. If you don’t see the attribute on a request,be sure the appropriate middleware class is listed in?.

From the?: A readable and writable,dictionary-like object that represents the current session.

HttpRequest.user   From the AuthenticationMiddleware: An instance of AUTH_USER_MODEL representing the currently logged-in user. If the user isn’t currently logged in,user will be set to an instance of AnonymousUser. You can tell them apart with is_authenticated,like so:

Methods?

除了属性,HttpRequest对象还带有很多方法

()

返回网站服务器地址,Example:?

()

返回服务器主机端口

HttpRequest.get_full_path() Returns the path,plus an appended query string,if applicable.

Example: "/music/bands/the_beatles/?print=true"

HttpRequest.build_absolute_uri(location) Returns the absolute URI form of location. If no location is provided,the location will be set to request.get_full_path().

If the location is already an absolute URI,it will not be altered. Otherwise the absolute URI is built using the server variables available in this request.

Example: "https://example.com/music/bands/the_beatles/?print=true"

HttpRequest.is_secure() Returns True if the request is secure; that is,if it was made with HTTPS.

HttpRequest.is_ajax()判断是否ajax请求

?objects

In contrast to??objects,which are created automatically by Django,??objects are your responsibility. Each view you write is responsible for instantiating,populating,and returning an?.

The??class lives in the??module.

Usage

Passing strings

Typical usage is to pass the contents of the page,as a string,to the??constructor:

>> >> >>

But if you want to add content incrementally,you can use??as a file-like object:

>> >> Here's the text of the Web page.

">> Here's another paragraph.

"

Telling the browser to treat the response as a file attachment

To tell the browser to treat the response as a file attachment,use the??argument and set the??header. For example,this is how you might return a Microsoft Excel spreadsheet:

>> response = HttpResponse(my_data,content_type='application/vnd.ms-excel') >>> response['Content-Disposition'] = 'attachment; filename="foo.xls"'

Attributes

A bytestring representing the content,encoded from a string if necessary.

A string denoting the charset in which the response will be encoded. If not given at??instantiation time,it will be extracted from??and if that is unsuccessful,the??setting will be used.

The??for the response.

Unless??is explicitly set,modifying the value of??outside the constructor will also modify the value of?.

The HTTP reason phrase for the response. It uses the??default reason phrases.

Unless explicitly set,??is determined by the value of?.

This is always?.

This attribute exists so middleware can treat streaming responses differently from regular responses.

?if the response has been closed.

  

Methods

(content='',?content_type=None,?status=200,?reason=None,?charset=None)

Instantiates an??object with the given page content and content type.

?should be an iterator or a string. If it’s an iterator,it should return strings,and those strings will be joined together to form the content of the response. If it is not an iterator or a string,it will be converted to a string when accessed.

?is the MIME type optionally completed by a character set encoding and is used to fill the HTTP?header. If not specified,it is formed by the??and??settings,by default: “text/html; charset=utf-8”.

?is the??for the response.

?is the HTTP response phrase. If not provided,a default phrase will be used.

?is the charset in which the response will be encoded. If not given it will be extracted from?,and if that is unsuccessful,the??setting will be used.

(key,?value='',?max_age=None,?expires=None,?path='/',?domain=None,?secure=None,?httponly=False)

Sets a cookie.?

  • ?should be a number of seconds,or??(default) if the cookie should last only as long as the client’s browser session. If??is not specified,it will be calculated.

  • ?should either be a string in the format??or a??object in UTC. If??is a??object,the??will be calculated.

  • ?if you want to set a cross-domain cookie. For example,??will set a cookie that is readable by the domains www.example.com,blog.example.com,etc. Otherwise,a cookie will only be readable by the domain that set it.

  • ?if you want to prevent client-side JavaScript from having access to the cookie.

    ?is a flag included in a Set-Cookie HTTP response header. It is not part of the??standard for cookies,and it isn’t honored consistently by all browsers. However,when it is honored,it can be a useful way to mitigate the risk of a client-side script from accessing the protected cookie data.

(key,?domain=None)

?and??should be the same values you used in??– otherwise the cookie may not be deleted.

?subclasses

Django includes a number of??subclasses that handle different types of HTTP responses. Like?,these subclasses live in?.

The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g.?),an absolute path with no domain (e.g.?),or even a relative path (e.g.?). In that last case,the client browser will reconstruct the full URL itself according to the current path. See??for other optional constructor arguments. Note that this returns an HTTP status code 302.

This read-only attribute represents the URL the response will redirect to (equivalent to the??response header).

Like?,but it returns a permanent redirect (HTTP status code 301) instead of a “found” redirect (status code 302).

The constructor doesn’t take any arguments and no content should be added to this response. Use this to designate that a page hasn’t been modified since the user’s last request (status code 304).

Acts just like??but uses a 400 status code.

Acts just like??but uses a 404 status code.

Acts just like??but uses a 403 status code.

Like?,but uses a 405 status code. The first argument to the constructor is required: a list of permitted methods (e.g.?).

Acts just like??but uses a 410 status code.

class?

Acts just like??but uses a 500 status code.

CBV(Class based views)

Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了CBV(Class-Based-View)。CBV就是在视图里使用类处理请求。

即可以让我们用类写View。这样做的优点主要下面两种:

  • 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  • 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性
class MyView(View):
def get(self,request):

    return HttpResponse('result')

Django的url收到请求后,是需要把这个请求分配给一个可调用的函数的,而不是一个class。针对这个问题,class-based view提供了一个as_view()静态方法(也就是类方法),调用这个方法,会创建一个类的实例,然后通过实例调用dispatch()方法,dispatch()方法会根据request的method的不同调用相应的方法来处理request(如get(),post()等)。到这里,这些方法和function-based view差不多了,要接收request,得到一个response返回。如果方法没有定义,会抛出HttpResponseNotAllowed异常。  

在url中,就这么写:

urlpatterns = [
path('about/',MyView.as_view()),]

cbv视图属性设置

类的属性可以通过两种方法设置,第一种是常见的Python的方法,可以被子类覆盖。

class GreetingView(View):
greeting = "Good Day"

def get(self,request):
    return HttpResponse(self.greeting)

子类中只需继承

第二种方法,你也可以在url中指定类的属性:

在url中设置类的属性Python

  

Decorating the class

To decorate every instance of a class-based view,you need to decorate the class definition itself. To do this you apply the decorator to the??method of the class.

A method on a class isn’t quite the same as a standalone function,so you can’t just apply a function decorator to the method – you need to transform it into a method decorator first. The??decorator transforms a function decorator into a method decorator so that it can be used on an instance method. For example:

@method_decorator(login_required)
def dispatch(self,*args,**kwargs):
    #print('----')
    return super().dispatch(*args,**kwargs)

Or,more succinctly,you can decorate the class instead and pass the name of the method to be decorated as the keyword argument?:

def get(self,request): print("get request...",request) return HttpResponse("result")

  

  

  

  

  

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读