笔记-django- HttpRequest/Response

1.      HttpRequest/Response

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.

This document explains the APIs for HttpRequest and HttpResponse objects, which are defined in the django.httpmodule.

重点django.http module

1.1.     HttpRequest

HttpRequest objects

class HttpRequest

Attributes,所有属性可以被认为是只读的,除非另有说明

All attributes should be considered read-only, unless stated otherwise.

HttpRequest.scheme

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

HttpRequest.body

The raw HTTP request body as a bytestring. This is useful for processing data in different ways than conventional HTML forms: binary images, XML payload etc. For processing conventional form data, use HttpRequest.POST.

You can also read from an HttpRequest using a file-like interface. See HttpRequest.read().

HttpRequest.path

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

Example: "/music/bands/the_beatles/"

HttpRequest.path_info

Under some Web server configurations, the portion of the URL after the host name is split up into a script prefix portion and a path info portion. The path_info attribute always contains the path info portion of the path, no matter what Web server is being used. Using this instead of path can make your code easier to move between test and deployment servers.

For example, if the WSGIScriptAlias for your application is set to "/minfo", then path might be "/minfo/music/bands/the_beatles/" and path_info would be "/music/bands/the_beatles/".

HttpRequest.method:http请求方法

HttpRequest.encoding:请求编码模式

A string representing the current encoding used to decode form submission data (or None, which means the DEFAULT_CHARSET setting is used). You can write to this attribute to change the encoding used when accessing the form data. Any subsequent attribute accesses (such as reading from GET or POST) will use the new encoding value. Useful if you know the form data is not in the DEFAULT_CHARSET encoding.

HttpRequest.content_type

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

HttpRequest.content_params

A dictionary of key/value parameters included in the CONTENT_TYPE header.

HttpRequest.GET

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

需要注意它是QueryDict objects,一般情况下可视为dict。

HttpRequest.POST

A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.

It’s possible that a request can come in via POST with an empty POST dictionary – if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn’t use if request.POST to check for use of the POST method; instead, use if request.method == "POST" (see HttpRequest.method).

POST does not include file-upload information. See FILES.

HttpRequest.COOKIES:cookie,dict

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.

See Managing files for more information.

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

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META keyHTTP_X_BENDER.

Note that runserver strips all headers with underscores in the name, so you won’t see them in META. This prevents header-spoofing based on ambiguity between underscores and dashes both being normalizing to underscores in WSGI environment variables. It matches the behavior of Web servers like Nginx and Apache 2.4+.

HttpRequest.headers is a simpler way to access all HTTP-prefixed headers, plus CONTENT_LENGTH and CONTENT_TYPE.

HttpRequest.headers:头部,引用变量时大小写不敏感

New in Django 2.2:

A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type) from the request.

The name of each header is stylized with title-casing (e.g. User-Agent) when it’s displayed. You can access headers case-insensitively:

>>> request.headers

{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> request.headers['User-Agent']

>>> request.headers['user-agent']

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')

>>> request.headers.get('user-agent')

上面的方式都是合法的。

HttpRequest.resolver_match

An instance of ResolverMatch representing the resolved URL. This attribute is only set after URL resolving took place, which means it’s available in all views but not in middleware which are executed before URL resolving takes place (you can use it in process_view() though).

还有一些方法未列出。

1.2.    HttpResponse objects

class HttpResponse

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 or bytestring, to the HttpResponse constructor:

>>> fromdjango.httpimport HttpResponse
>>> response = HttpResponse("Here's the text of the Web page.")
>>> response = HttpResponse("Text only, please.", content_type="text/plain")
>>> response = HttpResponse(b'Bytestrings are also accepted.')

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

Setting header fields设置头部

To set or remove a header field in your response, treat it like a dictionary:

>>> response = HttpResponse()
>>> response['Age'] = 120
>>> del response['Age']

.注意del不会返回keyerror

from django.http import HttpResponse

res = HttpResponse(b'<p>httpresponse class test</p>', content_type='text/plain')
res['age'] = 45
print(res)

在测试时发现必需指定content_type参数,否则报错。

常用属性:

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.

笔记-django- HttpRequest/Response的更多相关文章

  1. Django——20141014深入理解Django HttpRequest HttpResponse的类和实例

    深入理解Django HttpRequest HttpResponse的类和实例 了解META选项 了解中间件 理清所有模板传输模板变量的方式,并作出选择 Django模板系统:如何利用Django模 ...

  2. 《玩转Django2.0》读书笔记-Django配置信息

    <玩转Django2.0>读书笔记-Django配置信息 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 项目配置是根据实际开发需求从而对整个Web框架编写相应配置信息. ...

  3. 笔记-django第一个项目

    笔记-django第一个项目 1.      创建项目 安装 Django 之后,现在有了可用的管理工具 django-admin.可以使用 django-admin 来创建一个项目: 看下djang ...

  4. python学习笔记--Django入门四 管理站点--二

    接上一节  python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...

  5. 《玩转Django2.0》读书笔记-Django建站基础

    <玩转Django2.0>读书笔记-Django建站基础 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.网站的定义及组成 网站(Website)是指在因特网上根据一 ...

  6. python学习笔记--Django入门一 网页显示时间

    我的笔记是学习http://djangobook.py3k.cn/ 课程时做的,这个上边的文章讲的确实是非常的详细,非常感谢你们提供的知识. 上一篇随笔中已经配置好了Django环境,现在继续跟随ht ...

  7. Vue学习笔记-Django REST framework3后端接口API学习

    一  使用环境 开发系统: windows 后端IDE: PyCharm 前端IDE: VSCode 数据库: msyql,navicat 编程语言: python3.7  (Windows x86- ...

  8. VS2013中Python学习笔记[Django Web的第一个网页]

    前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...

  9. Php 笔记1-----request和 response

    不能大于2KB 第一次学习 php,  因为以前习惯了 .net, 所以 刚开始总是按照.net的  思路去思考, 怎么获取 客户端发过来的  request对象啊,  怎么设置response啊.. ...

  10. python学习笔记--Django入门0 安装dangjo

    经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...

随机推荐

  1. C++默认值。

    类成员变量: char :� //随机int :2685372 //随机string :size:0length:0 vector :0map :0 结构体 //取决于成员自己的类型 类成员静态变量: ...

  2. 【2D游戏引擎】WIP反思

    WIP(Working In Progress)是我初学游戏引擎开发时候开发的一个2D游戏引擎,当时计划为它实现类似Unity一样的编辑器,具有和Unity相似的工作流,但是由于水平不够,走了很多弯路 ...

  3. 代码注释模板(把内容保存为xml文件,导入eclipse中即可)

    <?xml version="1.0" encoding="UTF-8" standalone="no"?><templa ...

  4. 解决SpringMVC拦截器拦截静态资源的问题。

    在使用SpringMVC进行开发的时候,遇到了以下代码不能执行的情况.而且我已经正确导入了JQuery框架. <script type="text/javascript"&g ...

  5. AsyncTask使用实例,异步加载图片

    在上一篇,详细介绍了AsynTask的基础知识.没有读过的朋友可以点击下面的链接: http://www.cnblogs.com/fuly550871915/p/4892310.html 那么在这篇文 ...

  6. Java---页面之间传值跳转

    从首页A进入页面B,然后从B页面登录,成功后跳转到A页面,并打印一句话“登录成功”,传值需要用的后台的. 在B页面写: <%     session.setAttribute("key ...

  7. BZOJ2342:[SHOI2011]双倍回文(Manacher)

    Description   Input 输入分为两行,第一行为一个整数,表示字符串的长度,第二行有个连续的小写的英文字符,表示字符串的内容. Output 输出文件只有一行,即:输入数据中字符串的最长 ...

  8. 蓝牙BLE4.0的LL层数据和L2CAP层数据的区分与理解

    一直搞不太清楚蓝牙BLE协议,不知道LL层和L2CAP层是如何划分的,后来博士给我讲了讲就理解了,写下来,做个记录: 1. 我们知道,除了蓝牙5.1新出的CTE,所有的BLE都是如下类型的包: 对于连 ...

  9. 集合HashMap和HashSet中迭代器的使用

    package setTest; import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import ...

  10. HIDU 2094

    传送门: http://acm.hdu.edu.cn/showproblem.php?pid=2094 产生冠军 Time Limit: 1000/1000 MS (Java/Others)    M ...