Introduction view, HttpRequest HttpResponse introduction and use

Copyright: Changan white https://blog.csdn.net/weixin_44074810/article/details/91045437

view

Key
1, HttpRequest

    1. 位置参数和关键字参数
    2. 查询字符串
    3. 请求体:表单数据,JSON数据
    4. 请求头

2、HttpResponse

    1.HttpResponse
    2.JsonResponse
    3.redirect

3, the view class

    1.类视图的定义和使用

    2.类视图装饰器(难点)

First, try to introduce and project preparation

  1. View is the application function views.py file
  2. The first parameter view must be HttpResquset object. May also contain at parameters such as
    ① through positional parameters regex group acquired
    keyword parameters obtained by regular expression group ②

3. must return a view HttpResponse object or sub-object in response

① 子对象: JsonResponse HttpResponseRedirect

4. View the HttpRequest responsible for receiving a Web request, processing logic returns to the requestor Web response HttpResponse

① 响应内容可以是HTML内容,404错误,重定向,json数据...
  1. Two steps required when using the view, in no particular order two steps
    ① configure the URLconf
    ② is defined in view of the application /views.py

Two, URLconf

1. 浏览者通过在浏览器的地址栏中输入网址请求网站
2. 对于Django开发的网站,由哪一个视图进行处理请求,是由url匹配找到的
1. 项目中urls.py
    匹配成功后,包含到应用的urls.py
    url(正则, include('应用.urls'))

url(r'^',include('book.urls'))

2. 应用中urls.py
    匹配成功后,调用views.py对应的函数
    url(正则, views.函数名)

from django.conf.urls import url
from book.views import bookList(

urlpatterns = [

    # 匹配书籍列表信息的URL,调用对应的bookList视图
    url(r'^booklist/$',bookList)
]

note:

  1. Regular part of the recommended r, a string that represents not escape, so regular
    use expressions \ write only one on it

  2. Can not begin with a backslash, backslash recommended at the end of the
    right: path /
    correct: path
    error: / path
    error: / path /

  3. Excluding the domain name, post or GET request url parameter is seen as a normal python strings, matching

 3.1 如请求地址如下:
          http://127.0.0.1:8000/18/?a=10
 3.2 去掉域名和参数部分后,只剩下如下部分与正则匹配
          18/

Description:
While the end of the route with / can bring these benefits, but contrary to the HTTP URL represents a design resource location path.
Whether the end of band / company to define your style prevail.

Third, the reverse route to the named anti-analytic (reverse)

  1. Routing named
    in the definition of the route when the route can be named, easier to find specific path view specific information.
  1. When using the function definition include routing namespace namespace may be used to define routing parameters, such as the
    url (r '^', include ( 'book.urls', namespace = 'book'))

Namespace said all routes book.urls defined, belong to the namespace name specified in the book.
The role of the namespace: Avoid routes of different applications using the same name conflicts, use namespaces to distinguish.

  1. When defining normal route, the route using the specified parameter name name such as
urlpatterns = [
    url(r'^$',index),
    # 匹配书籍列表信息的URL,调用对应的bookList视图
    url(r'^booklist/$',bookList,name='index'),
    url(r'^testproject/$',views.testproject,name='test'),
]

  1. reverse anti-analytic

Using the reverse function, according to the name of the route, the specific return path, such as:

urlpatterns = [
    url(r'^$',index),
    # 匹配书籍列表信息的URL,调用对应的bookList视图
    url(r'^booklist/$',bookList,name='index'),
    url(r'^testproject/$',views.testproject,name='test'),
]

2 reverse anti-analytic

Using the reverse function, according to the name of the route, the specific return path, such as:

from django.core.urlresolvers import reverse
#或者
from django.urls import reverse

def testproject(request):

    return HttpResponse("OK")

# 定义视图:提供书籍列表信息
def bookList(request):

    url = reverse('book:test')
    print(url)
    return HttpResponse('index')

    1. 对于未指明namespace的,reverse(路由name)
    2. 对于指明namespace的,reverse(命名空间namespace:路由name)

Four, HttpRequest objects

1. 提取URL的特定部分,如/weather/beijing/2018,可以在服务器端的路由中用正则表达式截取;
2. 查询字符串(query string),形如key1=value1&key2=value2;
3. 请求体(body)中发送的数据,比如表单数据、json、xml;
4. 在http报文的头(header)中。

1 URL path parameters

  1. If you want to get the value from the URL, you need to use the grouping in regular expressions,

  2. Gets the value is divided into two ways

     1.位置参数
          1. 参数的位置不能错
     2.关键字参数
          2. 参数的位置可以变,跟关键字保持一致即可
    

3. Note: Do not mix parameters are two ways to use, can use only one parameter in a way regular expression
4 were used to obtain the URL value of two or more ways to extract 188 18 is
of http://127.0.0.1: 8000/18/188 /

Positional parameters

1. 应用中urls.py
 url(r'^(\d+)/(\d+)/$', views.index),

2. 视图中函数: 参数的位置不能错
def index(request, value1, value2):
      # 构造上下文
      context = {'v1':value1, 'v2':value2}
      return render(request, 'Book/index.html', context)

Keyword arguments

1. 应用中urls.py
       ①  其中?P<value1>部分表示为这个参数定义的名称为value1
       ②  可以是其它名称,起名要做到见名知意
利用正则进行分组,起别名
    url(r'^(?P<value1>\d+)/(?P<value2>\d+)/$', views.index),

2. 视图中函数: 参数的位置可以变,跟关键字保持一致即可

def index(request, value2, value1):
      # 构造上下文
      context = {'v1':value1, 'v2':value2}
      return render(request, 'Book/index.html', context)

2 Django objects in QueryDict

https://www.baidu.com/s?ie=utf-8&wd=itcast&rsv_pq=fdf543ed000f8688&rsv_t=8862Eb1lxc9858Ihke7VdJylicTyYs%2F3EuFyVPKcOBnv9wmTxLdhwlYL6%2F8&rqlang=cn&rsv_enter=1&rsv_sug3=5&rsv_sug1=4&rsv_sug7=100

以? 作为一个分隔
    ?前边 表示 路由
    ?后边 表示 get方式传递的参数 称之为 查询字符串
    ?key=value&key=value...

我们在登陆的时候会输入用户名和密码 理论上 用户名和密码都应该以POST方式进行传递
只是为了让大家好理解,我们接下来 用 get方式来传递用户名和密码

GET HttpRequest property of the object, the object is QueryDict POST type
to python dictionary different objects QueryDict (dictionary) for handling of the same type having a plurality of key values

  1. Method get (): Get value according to the key

    If a key has multiple values ​​at the same time you will get the last value

    If the key does not exist None value is returned, the default value may be provided for subsequent processing

  2. get ( 'key', the default)

    Method getlist (): Get value according to the key, can return multiple values, values ​​returned list, have access to all specified key

    If the key does not exist is returned empty list [], the default value may be provided for subsequent processing

    GetList ( 'key', the default)

  3. The query string Query String

Acquiring a query string parameter request path (the form? K1 = v1 & k2 = v2 ), may be obtained by request.GET property
returns QueryDict object.

# /get/?a=1&b=2&a=3

def get(request):
    a = request.GET.get('a')
    b = request.GET.get('b')
    alist = request.GET.getlist('a')
    print(a)  # 3
    print(b)  # 2
    print(alist)  # ['1', '3']
    return HttpResponse('OK')

Important: The query string is not case-request mode, that is, if the client requests POST method,
can still get the query string data request by request.GET.

4 requests body

  1. Request body data format is not fixed, form type may be a string, the string may be JSON,
    may be an XML string, it should be treated differently.

  2. Mode request may send a request to have the volume data POST, PUT, PATCH, DELETE.

  3. Django CSRF protection is enabled by default, it has the above-described manner CSRF protection authentication request,
    when the test can be closed CSRF protection mechanism, the method is commented CSRF middleware settings.py file,

4.1 Form Type Form Data

Form type data request body distal transmitted may be acquired by request.POST property returns QueryDict object.

def post(request):
a = request.POST.get(‘a’)
b = request.POST.get(‘b’)
alist = request.POST.getlist(‘a’)
print(a)
print(b)
print(alist)
return HttpResponse(‘OK’)

4.2 Non-Type Non-Form Data Form

Non-form volume data type of request, Django can not be resolved automatically, may acquire the most primitive data request body request.body properties,
their request is parsed in accordance with body format (JSON, XML, etc.). request.body return bytes type.

For example, to obtain the following data in the request body JSON
{ "a": 1, " b": 2}

Operation may be performed as follows:

import json

def post_json(request):
    json_str = request.body
    json_str = json_str.decode()  
    req_data = json.loads(json_str)
    print(req_data['a'])
    print(req_data['b'])
    return HttpResponse('OK')

    # json.damps 将字典转换成json形式的字符串
    # json.loads 将json形式的字符串转换为字典

5 request header
data may be obtained by the request header headers request.META property, request.META as a dictionary type.

The common request header:

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

Specific use such as:

def get_headers(request):
    print(request.META['CONTENT_TYPE'])
    return HttpResponse('OK')

6 Other common HttpRequest object properties

method:一个字符串,表示请求使用的HTTP方法,常用值包括:'GET'、'POST'。
user:请求的用户对象。
path:一个字符串,表示请求的页面的完整路径,不包含域名和参数部分。

encoding:一个字符串,表示提交的数据的编码方式。
    如果为None则表示使用浏览器的默认设置,一般为utf-8。
    这个属性是可写的,可以通过修改它来修改访问表单数据使用的编码,接下来对属性的任何访问将使用新的encoding值。

FILES:一个类似于字典的对象,包含所有的上传文件。

HttpResponse object

Upon receiving the request and view process, you must return HttpResponse object or sub-object. HttpRequest object is created by Django,
HttpResponse objects are created by the developer.

1 HttpResponse
may be used to construct django.http.HttpResponse response object.

HttpResponse (content = response body, content_type = the volume data in response to the type, status = status code)

May also be provided by the body in response HttpResponse object attribute data in response to body type, status code:

1. content:表示返回的内容。传递字符串  不要传递 对象,字典等数据
2. status:HTTP status code must be an integer from 100 to 599.   只能使用系统规定的 
3. status_code:返回的HTTP响应状态码。
4. content_type:是一个MIME 类型
	语法形式是:大类/小类
5.text/html, text/css   text/javascript
   image/png    image/gif    image/jpeg

Response header may be directly HttpResponse object as a response to the first key-value dictionary of the settings:

1. response = HttpResponse()
2. response['itcast'] = 'Python'  # 自定义响应头Itcast, 值为Python

Example:

from django.http import HttpResponse

def response(request):
    return HttpResponse('itcast python', status=400)
    或者
    response = HttpResponse('itcast python')
    response.status_code = 400
    response['itcast'] = 'Python'
    return response

2 HttpResponse子类

Django provides a series HttpResponse subclass can quickly set the status code

HttpResponseRedirect 301
HttpResponsePermanentRedirect 302
HttpResponseNotModified 304
HttpResponseBadRequest 400
HttpResponseNotFound 404
HttpResponseForbidden 403
HttpResponseNotAllowed 405
HttpResponseGone 410
HttpResponseServerError 500

3 JsonResponse

To return json data, you may be used to construct JsonResponse response object, action:

1. 帮助我们将数据转换为json字符串
2. 设置响应头Content-Type为application/json

Example:

from django.http import JsonResponse

def response(request):
    return JsonResponse({'city': 'beijing', 'subject': 'python'})



实例:显示成字典
    from django.http import JsonResponse
    data = {'name':'zongwenbo'}
    
    return JsonResponse(data)

4 redirect redirection, jump page

from django.shortcuts import redirect

def response(request):
    return redirect('/get_header')

Guess you like

Origin blog.csdn.net/weixin_44074810/article/details/91045437