一、 HTTP请求
1.1 GET方法
案例如下,此外,若一个teplates的页面中有多个input,可以通过如下方式验证某个输入框是否有数据。
#/search.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
def search(request)
request.encoding='utf-8'
if 'searchValue' in request.GET:
message = '您要搜索的内容为:'+ request.GET['searchValue']
else:
message = 你提交了空表单
return HttpResponse(message)
#/templates/search_from.html
<form action="/search" method="get">
<input type="text" name="searchValue">
<input type="submit" value="搜索">
</form>
#/urls.py
urlpatterns = [
url(r'^search',search.search)
]
1.2 POST方法
提交数据时更经常使用POST方法。
<form action="/search-post" method="post">
{% csrf_token %}
<input type="text" name="q">
<input type="submit" value="Submit"
</form>
<p>{{ rlt }}</p>
表格后面的{% csrf_token %}标签是Django用来防止伪装提交请求的功能,POST方法提交的表格必须有这个标签。
#urls.py
from views.py import search
urlpatters = [
url(r'^search',search)
]
#views.py
from django.shortcuts import render
from django.views.decorators import csrf
def search(request):
ctx = {}
if request.POST:
ctx['rlt']=request.POST['q']
return render(request,"post.html",ctx)
二、Request对象
2.1简单示例
- 每个view函数的第一个参数是一个HttpRequest对象。例如:
from django.http import HttpResponse
def hello(request):
return HttpResponse("hi")
2.2 Django中HttpRequest对象所包含当前请求url 的属性
method
:请求中所使用的HTTP方法,用券大写表示,例如:
if request.method == 'GET':
do something
elif request.method == 'POST':
do something
USER
:代表当前登陆用户、GET
:包含所有HTTP GET参数的类字典对象、POST
:包含所有HTTP POST参数的类字典对象COOKIES
:包含所有cookies的标准python字典对象,例如csrftoken和seesionid。例如:
Variable | Value |
---|---|
csrftoken | ‘ZpDdhBZtSc7OVrDKvp3nvxWrX1VnZyTQYNm8xG6bTOvXS01AqkhiZsnyNf7CSg9W’ |
sessionid | ‘vhrtcsbaas1luw5sf63zhnule2jr7cel’ |
META
:包含所有可用的HTTP头部信息。
key值 | 含义 |
---|---|
CONTENT_LENGTH | |
CONTENT_TYPE | |
QUERY_STRING | 未解析的原始查询字符串 |
REMOTE_ADDR | 客户端IP地址 |
REMOTE_HOST | 客户端主机名 |
SERVER_NAME | 服务器主机名 |
SERVER_PORT | 服务器端口 |
META 中这些头加上前缀HTTP_, 例如:
key值 | 含义 |
---|---|
HTTP_ACCEPT_ENCODING | |
HTTP_ACCEPT_LANGUAGE | |
HTTP_HOST | 客户发送的HTTP主机头信息 |
HTTP_REFERER | referring页 |
HTTP_USER_AGENT | 客户端的user-agent字 |
HTTP_X_BENDER | X-Bender头信息 |
5.Settings
:该django项目的常用设置选项。
6.注意上面的属性不一定都会有,需要根据请求的类型来使用。
2.3 Django中HttpRequest对象所包含的方法
request.GET[key]
:request.POST[key]
:request.get_full_path
:返回包含查询字段的完整请求路径。request.is_secure()
:是否为HTTPS请求。
5.has_key()
:例如request.GET.has_key(“password”),判断请求是否含有参数指定的key。