本节内容

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

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

单纯返回字符串

1
2
3
4
5
6
7
8
def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
    #return HttpResponseNotFound('<h1>Page not found</h1>')
 
    # Return a "created" (201) response code.
    #return HttpResponse(status=201)

返回html文件  

1
2
3
4
5
6
def detail(request, poll_id):
    try:
        = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request, 'polls/detail.html', {'poll': p}) 

加装饰器

1
2
3
4
5
6
@login_required
def user_list(request):
     
    users = models.Account.objects.all()
     
    return render(request,'account.html',{'account_list':users})

只允许特定方法

1
2
3
4
5
6
7
from django.views.decorators.http import require_http_methods
 
@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对象来调取相应的属性。

HttpRequest.scheme

A string representing the scheme of the request (http or https 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

1
2
3
4
if request.method == 'GET':
    do_something()
elif request.method == 'POST':
    do_something_else()

 

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

MIME (Multipurpose Internet Mail Extensions)是描述消息内容类型的因特网标准。

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

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

HttpRequest.POST
HttpRequest.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 <input type="file" name="" />. Each value in FILES is an UploadedFile.

FILES will only contain data if the request method was POST and the <form> that posted to the request had enctype="multipart/form-data". Otherwise, FILES will be a blank dictionary-like object.

HttpRequest.META

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

  • CONTENT_LENGTH – The length of the request body (as a string).
  • CONTENT_TYPE – The MIME type of the request body.
  • HTTP_ACCEPT – Acceptable content types for the response.
  • HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
  • HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
  • HTTP_HOST – The HTTP Host header sent by the client.
  • HTTP_REFERER – The referring page, if any.
  • HTTP_USER_AGENT – The client’s user-agent string.
  • QUERY_STRING – The query string, as a single (unparsed) string.
  • REMOTE_ADDR – The IP address of the client.
  • REMOTE_HOST – The hostname of the client.
  • REMOTE_USER – The user authenticated by the Web server, if any.
  • REQUEST_METHOD – A string such as "GET" or "POST".
  • SERVER_NAME – The hostname of the server.
  • SERVER_PORT – 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 MIDDLEWARE.

HttpRequest.session

From the SessionMiddleware: 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:

1
2
3
4
if request.user.is_authenticated:
... # Do something for logged-in users.
else:
... # Do something for anonymous users.

Methods

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

HttpRequest.get_host()

返回网站服务器地址,Example: "127.0.0.1:8000"

HttpRequest.get_port()

返回服务器主机端口

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请求

HttpResponse objects

class HttpResponse[source]

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

The HttpResponse class lives in the django.http module.

Usage

Passing strings

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

>>> from django.http import HttpResponse
>>> response = HttpResponse("Here's the text of the Web page.")
>>> response = HttpResponse("Text only, please.", content_type="text/plain")

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

>>> response = HttpResponse()
>>> response.write("<p>Here's the text of the Web page.</p>")
>>> response.write("<p>Here's another paragraph.</p>")

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 content_type argument and set the Content-Disposition header. For example, this is how you might return a Microsoft Excel spreadsheet:

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

Attributes

HttpResponse.content

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

HttpResponse.charset

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

HttpResponse.status_code

The HTTP status code for the response.

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

HttpResponse.reason_phrase

The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases.

Unless explicitly set, reason_phrase is determined by the value of status_code.

HttpResponse.streaming

This is always False.

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

HttpResponse.closed

True if the response has been closed.

  

Methods

HttpResponse.__init__(content=''content_type=Nonestatus=200reason=Nonecharset=None)[source]

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

content 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.

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

status is the HTTP status code for the response.

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

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

HttpResponse.set_cookie(keyvalue=''max_age=Noneexpires=Nonepath='/'domain=Nonesecure=Nonehttponly=False)

Sets a cookie.

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

  • expires should either be a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT" or a datetime.datetime object in UTC. If expires is a datetime object, the max_age will be calculated.

  • Use domain if you want to set a cross-domain cookie. For example, domain="example.com" 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.

  • Use httponly=True if you want to prevent client-side JavaScript from having access to the cookie.

    HTTPOnly is a flag included in a Set-Cookie HTTP response header. It is not part of the RFC 2109 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.

HttpResponse.delete_cookie(keypath='/'domain=None)

Deletes the cookie with the given key. Fails silently if the key doesn’t exist.

Due to the way cookies work, path and domain should be the same values you used in set_cookie() – otherwise the cookie may not be deleted.

HttpResponse subclasses

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

class HttpResponseRedirect[source]

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

url

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

class HttpResponsePermanentRedirect[source]

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

class HttpResponseNotModified[source]

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).

class HttpResponseBadRequest[source]

Acts just like HttpResponse but uses a 400 status code.

class HttpResponseNotFound[source]

Acts just like HttpResponse but uses a 404 status code.

class HttpResponseForbidden[source]

Acts just like HttpResponse but uses a 403 status code.

class HttpResponseNotAllowed[source]

Like HttpResponse, but uses a 405 status code. The first argument to the constructor is required: a list of permitted methods (e.g. ['GET', 'POST']).

class HttpResponseGone[source]

Acts just like HttpResponse but uses a 410 status code.

class HttpResponseServerError[source]

Acts just like HttpResponse but uses a 500 status code.

 

CBV(Class based views)

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

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

  • 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  • 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性
1
2
3
4
5
6
7
from django.http import HttpResponse
from django.views import View
 
class MyView(View):
    def get(self, request):
        # <view logic>
        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中,就这么写:

1
2
3
4
5
6
7
# urls.py
from django.urls import path
from myapp.views import MyView
 
urlpatterns = [
    path('about/', MyView.as_view()),
]

cbv视图属性设置

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

1
2
3
4
5
6
7
8
from django.http import HttpResponse
from django.views import View
 
class GreetingView(View):
    greeting = "Good Day"
 
    def get(self, request):
        return HttpResponse(self.greeting)

子类中只需继承

1
2
class MorningGreetingView(GreetingView):
    greeting = "Morning to ya"

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

在url中设置类的属性Python

1
2
3
urlpatterns = [
    path('about/', GreetingView.as_view(greeting="G'day")),
]

  

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 dispatch() 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 method_decorator decorator transforms a function decorator into a method decorator so that it can be used on an instance method. For example:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
1
2
3
4
5
6
<br>class MyView(View):
 
    @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 name:

1
2
3
4
5
6
7
@method_decorator(login_required,name='dispatch')
class MyView(View):
 
    def get(self,request):
 
        print("get request...",request)
        return HttpResponse("result")

  

Django之 Views组件的更多相关文章

  1. Django之Form组件

    Django之Form组件 本节内容 基本使用 form中字段和插件 自定义验证规则 动态加载数据到form中 1. 基本使用 django中的Form组件有以下几个功能: 生成HTML标签 验证用户 ...

  2. Python之路【第二十一篇】:Django之Form组件

    Django之Form组件   Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 小试牛刀 1. ...

  3. 第十一篇:web之Django之Form组件

    Django之Form组件   Django之Form组件 本节内容 基本使用 form中字段和插件 自定义验证规则 动态加载数据到form中 1. 基本使用 django中的Form组件有以下几个功 ...

  4. python Django之Form组件

    python Django之Form组件 Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 小试 ...

  5. Django之ContentType组件

    一.理想表结构设计 1.初始构建 1. 场景刚过去的双12,很多电商平台都会对他们的商品进行打折促销活动的,那么我们如果要实现这样的一个场景,改如何设计我们的表? 2. 初始表设计 注释很重要,看看吧 ...

  6. python框架之Django(10)-Form组件

    介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来.与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否输入,输入 ...

  7. 〖Python〗-- Django的Form组件

    [Django的Form组件] Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 Form类的使 ...

  8. Django之Form组件验证

    今天来谈谈Django的Form组件操作 Django中的Form一般有两种功能: ·输入html ·验证用户输入 Form验证流程 ·定义规则(是一个类)    ·前端把数据提交过来 ·匹配规则 · ...

  9. web之Django之Form组件

    Django之Form组件 本节内容 基本使用 form中字段和插件 自定义验证规则 动态加载数据到form中 1. 基本使用 django中的Form组件有以下几个功能: 生成HTML标签 验证用户 ...

随机推荐

  1. MATLAB读取和保存nifti文件

    介绍 分析核磁数据时,数据的读取和保存是两个基本的操作.虽然大部分工具包都对这些功能进行了封装,但是如果你不了解如何使用这些工具包或者说当前的任务太简单不值得去使用这些庞大的工具包的时候就需要我们自己 ...

  2. 素数筛 : Eratosthenes 筛法, 线性筛法

    这是两种简单的素数筛法, 好不容易理解了以后写篇博客加深下记忆 首先, 这两种算法用于解决的问题是 : 求小于n的所有素数 ( 个数 ) 比如 这道题 在不了解这两个素数筛算法的同学, 可能会这么写一 ...

  3. 如何利用Excel设计一个唱票统计系统?

    具体操作如下: 首先需要一个如下的数据结构. 唱票数G列区域,不能手动输入候选人票数,这样很不方便,所以我们需要一个窗体控件,用点击鼠标的方法来实现唱票.在“开发工具-插入-数值调节钮”下图3处,然后 ...

  4. 《Redis开发与运维》

    第1章 初识Redis 1. Redis介绍: Redis是一种基于键值对(key-value)的NoSQL数据库. 与很多键值对数据库不同的是,Redis中的值可以是由string(字符串).has ...

  5. Windows程序设计(2) -API-01 初识

    Windows 程序原理 一,CPU的保护模式和windows操作系统 [x] windows 是多任务实现 [x] 虚拟内存和 各个进程的地址空间安排:2G系统空间,2G用户空间,2G用户空间是各个 ...

  6. .Net Core踩坑记:读取txt中文乱码

    迁移.net framework的项目,有块读取txt中文转码的问题,普通的不能再普通的代码,想都没想直接copy过去,也没测,结果今天就被坑了.Core是3.1版本,这是原来的代码: string ...

  7. <用户输入url按下回车,一直到用户看到界面,这期间经历了什么>

    用户输入url按下回车,一直到用户看到界面,这期间都经历什么? 一.  DNS解析缓存: 1. 找到浏览器缓存解析域名: 2. 找到和 DNS 缓存 ; 3. 找到路由器 DNS 缓存: 4. 找到查 ...

  8. Java操作RockeMQ

    RocketMQ是阿里巴巴在2012年开源的分布式消息中间件,目前已经捐赠给Apache基金会,已经于2016年11月成为 Apache 孵化项目,相信RocketMQ的未来会发挥着越来越大的作用,将 ...

  9. 39 _ 队列5 _ 循环队列需要几个参数来确定 及其含义的讲解.swf

    上面讲解都是循环队列,如果是链表实现的话就很简单,队列只有循环队列才比较复杂 此时队列中只存储一个有效元素3,当在删除一个元素的时候,队列为空,pFont向上移动,pFont等于pRear,但是此时p ...

  10. netty解决TCP的拆包和粘包的解决办法

    TCP粘包.拆包问题 熟悉tcp编程的可能知道,无论是服务端还是客户端,当我们读取或者发送数据的时候,都需要考虑TCP底层的粘包个拆包机制. tcp是一个“流”协议,所谓流就是没有界限的传输数据,在业 ...