视图,我们可以称之为函数或者叫视图类,简称为视图。 它本质上就是一个简单的Python函数或者是类,那么它接收的是一个请求对象,然后,并且返回一个响应对象。

127.0.0.1:8000无法访问

在能访问其他路径后,http://127.0.0.1:8000不知道为啥不能访问了,其他http://127.0.0.1:8000/account/login/倒是能访问

解决:
把views.py

1
2
def login(request):
return HttpResponse(‘收到了GET请求’)

改成

1
2
def login(request):
return render(request,’login.html’)

但浏览器还是显示收到了GET请求(估计是浏览器的缓存)

重新改一下views.py,改回

1
2
def login(request):
return HttpResponse(‘没有收到了GET请求’)

发现变成了没有收到了GET请求,再改成

1
2
def login(request):
return render(request,’login.html’)

就成功了

method:post注意项

把表单form的method改成post后(默认是get,提交的信息会显示在url里)
需要加一句{% csrf_token %},django里规定的

1
2
3
4
5
6
7
8
9
10
<form method="post">
{% csrf_token %}
<div>用户名:
<input type="text" name="username">
</div>
<div>密码:
<input type="password" name="password">
</div>
<button>登录</button>
</form>

f-string

Python中的f-string(也称为format string)可以用于将变量或表达式的值直接嵌入到字符串中,f不能缺

1
2
3
4
5
6
7
def login(request):
if request.method='POST':
username=request.POST.get('username')
password=request.POST.get('password')
return HttpResponse(f"用户{username}的密码是{password}")
elif request.method='GET':
return render(request,'login.html')

else if可以写成elif

请求头HttpRequest.META

HttpRequest.META可以获取很多的参数

CONTENTLENGTH:请求体的长度(字符串)
CONTENT_TYPE:请求体的MIME类型
HTTP_ACCEPT:可接受的响应内容类型
HTTP_ACCEPT_ENCODING:可接受的响应编码
HTTP_ACCEPT_LANGUAGE:可接受的响应语言
HTTP_HOST:客户端发送的HTTP主机头
HTTP_REFERER:referrer页面,如果有的话
HTTP_USER_AGENT:客户端的用户代理字符串
QUERY_STRING:查询字符串,是一个单一的(未解析的)字符串
REMOTE_ADDR:客户机的IP地址
REMOTE_HOST:客户机的主机名
REQUEST_METHOD:”GET”或”POST”等字符串
SERVER_NAME:服务器的主机名
SERVER_PORT:服务器的端口(字符串)

这里用request.META.get(‘REMOTE_ADDR’)来获取访问的ip地址,判断是否在黑名单
注意大小写,

1
2
3
4
5
6
7
#业务逻辑判断
return HttpResponse(f"用户{username}的密码是{password}")
elif request.method == 'GET':
FORBIDDEN_IP=['127.0.0.1', "0.0.0.0"]
if request.META.get('REMOTE_ADDR') in FORBIDDEN_IP:
return HttpResponse('请求异常')
return render(request, 'login.html')
1
Prinrt(request.MEAT)

可以看到所有属性参数

请求头HttpRequest.headers

除了META还有headers,headers的User-Agent可以看请求是不是来自爬虫

通过Http请求查看网页的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
import requests

url = "http://127.0.0.1:8000/hello/"
res = requests.get(url)

# 尝试自动检测编码,如果失败则使用UTF-8
try:
res.encoding = res.apparent_encoding
except AttributeError:
# 如果apparent_encoding属性不存在(在requests的老版本中),则手动设置为UTF-8
res.encoding = 'utf-8'

print(res.text)