一个视图函数(类)简称视图,是一个简单的Python 函数(类),包含的是业务逻辑,它接受Web请求并且返回Web响应。
一般放在 project 或 APP 的 views.py 中
获取用户请求数据
request.environ 中封装了所有用户请求信息
request.GET
request.POST
request.FILES # 获取上传文件
request.COOKIES # 获取COOKIES
request.path_info # 获取当前请求URL
request.environ['HTTP_USER_AGENT'] # 获取用户设备信息
示例:
html:
<form action="/login.html" method="post">
<input type="text" name="user_name" placeholder="User Name" required/>
<input type="password" name="password" placeholder="Password" required/>
</form>
views.py:
if request.method == 'POST':
username = request.POST.get('user_name')
password = request.POST.get('password')
checkbox等多选的内容(列表)
request.POST.getlist()
示例:
html:
<form method="post" action="/test/">
<p>1:<input type="checkbox" name="choose" value="1"></p>
<p>2:<input type="checkbox" name="choose" value="2"></p>
<p>3:<input type="checkbox" name="choose" value="3"></p>
<input type="submit">
</form>
views.py:
if request.method == 'POST':
res = request.POST.getlist('gender', None)
print(res)
输出结果:
['2', '3']
上传文件
示例:
html:
<form method="post" action="/test/" enctype="multipart/form-data">
<input type="file" name="fname">
<input type="submit">
</form>
views.py
import os
if request.method == 'POST':
file = request.FILES.get('fname', None) # 获取上传的文件
print(file.name, file.size)
file_path = os.path.join('upload', file.name) # 找到储存文件的位置
f = open(file_path, 'wb') # 创建空文件
for i in file.chunks(): # 循环读取文件
f.write(i) # 循环写入
f.close()
之后文件就上传到了项目目录下 upload 中
FBV & CBV
function base view
class base view
url.py:
from django.urls import path
urlpatterns = [
path('login/', views.login),
path('home/', views.Home.as_view()),
]
views.py:
from django.shortcuts import HttpResponse
from django.views import View
def login(request):
if request.method == 'GET':
return HttpResponse(get)
if request.method == 'POST':
return HttpResponse(post)
class Home(View):
# 先执行的函数
def dispatch(self, request, *args, **kwargs):
# 获取请求之前
print('before')
# 调用父类中的dispatch,获取请求
result = super(Home, self).dispatch(request, *args, **kwargs)
# 获取请求之后
print('after')
return result
@staticmethod
def get(self, request):
print(request.method)
return HttpResponse(get)
@staticmethod
def post(self, request):
print(request.method)
return HttpResponse(post)