第三章 Django 视图系统
第一章 Django 基本使用
第二章 Django URL路由系统
第三章 Django 视图系统
第四章 Django 模板系统
第五章 Django 数据模型系统(基本使用)
第六章 Django 数据模型系统(多表操作)
第七章 Django 用户认证与会话技术
第八章 Django CSRF防护
Django内建函数与HTTP请求流程
Django内建函数
HTTP请求流程
- 建立TCP连接:三次握手
- 发送HTTP请求:进行分装了浏览器信息(方法\URL\浏览器信息等)
- 相应HTTP请求:浏览器进行解析,获取信息
- 关闭TCP连接
Django请求流程
- pc发起请求
- django根据路由转发到不通视图,转发时候会包含浏览器信息(request)
- 视图会httpResponse发给django
- django响应给pc
HttpResponse常用属性和方法
常用属性
Django会建立一个包含请求源数据的HttpResquest对象,当Django加载对应的视图时,HttpRequest对象将作为函数视图的第一个参数(request),每个视图负责返回一个HttpResponse对象
例如:
def index(request):
return HttpResponse("首页")
属性 | 描述 |
---|---|
request.scheme | 表示请求协议的字符串(http或https) |
request.body | 原始HTTP请求正文 |
request.path | 一个字符串,请求页面的完整路径,不包含域名 |
request.method | 一个字符串,请求的HTTP方法,比如GET/POST等 |
request.GET | GET请求所有参数,返回QueryDict类型 |
request.POST | POST请求所有参数,返回QueryDict类型 |
request.COOKIES | 以字典格式返回Cookie |
request.session | 可读写的类似于字典的对象,表示当前的会话 |
request.FILES | 所有上传的文件 |
request.META | 所有上传的文件 |
路由
# devops/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('index/',views.index),
]
视图
# myapp/views.py
from django.shortcuts import render,HttpResponse
def index(request):
print('scheme:',request.scheme)
print('body',request.body)
print('path:',request.path)
print('method:',request.method)
print('GET:',request.GET)
print('POST:',request.POST)
print('COOKIES:',request.COOKIES)
print('session:',request.session)
print('FILES:',request.FILES)
# print(request.META)
print(request.META['TERM_PROGRAM'])
return HttpResponse("<h1>首页</h1>")
验证
http://49.232.221.200:8888/index/?id=123
GET:<QueryDict: {‘id’: [‘123’]}> 会有一个参数传进来
常用方法
属性 | 描述 |
---|---|
request.get_host() | 服务器主机地址和端口 |
request.get_port() | 服务器端口 |
request.get_full_path() | 请求页面后缀 |
request.get_raw_uri() | 请求页面URL所有信息,报货主机名、路径和参数 |
路由
# devops/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('index/',views.index),
]
视图
# myapp/views.py
from django.shortcuts import render,HttpResponse
def index(request):
print(request.get_host())
print(request.get_port())
print(request.get_full_path())
# print(request.get_raw_uri())
return HttpResponse("<h1>首页</h1>")
验证
处理URL参数
http://49.232.221.200:8888/index/?id=123&value=100
路由
# devops/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('index/',views.index),
]
视图
# myapp/views.py
from django.shortcuts import render,HttpResponse
def index(request):
A = request.GET['id']
B = request.GET['value']
print(A)
print(B)
return HttpResponse("<h1>首页</h1>")
验证
HttpRequest对象:QueryDic对象
QueryDic对象介绍
reuqest.GET和request.POST返回的都是一个QueryDict对象,类似于字典
def index(request):
req = request.GET
print(type(req))
return HttpResponse("首页")
属性 | 描述 |
---|---|
req.get(key,default) | 返回key的值,如果key不存在返回default |
req.items() | 返回迭代器,键值 |
req.values() | 返回迭代器,所有键的值 |
req.keys() | 返回所有键 |
req.getlist(key,deafult) | 返回key的值作为列表,如果key不存在返回default |
req.lists() | 返回迭代器,所有键的值作为列表 |
req.dict() | 返回字典 |
# devops/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('index/',views.index),
]
视图
def index(request):
A = request.GET['id']
B = request.GET['value']
# value = request.GET.get('value',None)
# print(value)
req = request.GET
for i in req.items():
print(i)
# print(A)
# print(B)
return HttpResponse("<h1>首页</h1>")
验证
http://49.232.221.200:8888/index/?id=123&value=100
示例1:搜索
路由
# devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('^search/$',views.search),
]
视图
# myapp/views.py
def search(request):
# key = request.GET.get('key')
key = request.GET.get('key',None)
if key is None:
result = "<h1>请输入想要查询的</h1>"
else:
result = "<h1>你是想要查询 %s 是不是</h1>" %key
return HttpResponse(result)
验证
示例2:登录页面
先关闭django防跨站机制进行注释
devops/devops/settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
路由
# devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('login/$',views.login,name="login"),
path('index/',views.index),
]
视图
# myapp/views.py
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
def login(request):
if request.method == "GET":
return render(request,"login.html")
elif request.method == "POST":
# 获取用户通过post提交的用户名和密码
username = request.POST.get('username',None)
password = request.POST.get('password',None)
if username == "wang" and password == "123456":
# 登录成功
# return HttpResponse("登录成功")
return redirect("/index")
else:
# 登录失败
msg = "用户名或密码输入错误!!!"
return render(request,"login.html",{"msg":msg})
# return render(request,"login.html")
def index(request):
return HttpResponse("<h1>首页</h1>")
网页
# templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="{% url "login" %}" method="post">
用户名: <input type="text" name="username">
密码: <input type="text" name="password">
<button type="submit">登录</button>
</form>
<span style="color: red">{{ msg }}</span>
</body>
</html>
验证
http://49.232.221.200:8888/login/
错误示范:
正确示范:
示例3:上传文件头像图片
mkdir -p /data/devops/upload
路由
# devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('user/$',views.user,name="user"),
]
视图
# myapp/views.py
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
def user(request):
if request.method == "GET":
return render(request,'user.html')
elif request.method == "POST":
obj = request.FILES.get('touxiang')
import os
file_path = os.path.join('upload',obj.name)
with open(file_path,mode="wb") as f:
for i in obj.chunks():
f.write(i)
msg = "上传文件成功"
return render(request,"user.html",{"msg":msg})
网页
# templates/user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
</head>
<body>
<form action="{% url "user" %}" method="post", enctype="multipart/form-data">
<input type="file" name="touxiang">
<button type="submit">提交头像</button>
</form>
<span style="color: red">{{ msg }}</span>
</body>
</html>
验证
函数
HttpResponse函数
给浏览器返回数据
语法:HTTPResponse(content=响应体,content_type=相应体数据类型,status=状态码)
示例
返回HTML内容
from django.http import HtttpResponse
def hello(request):
return HttpResponse("<h1>Hello Django!</h1>")
设置响应头
from django.http import HttpResponse
def hello(request):
res = HttpResponse("Hello APP!")
res['name'] = "aliang"
res.status_code = 302
路由
# devops/devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('index/$',views.index),
]
视图
# devops/devops/views.py
from django.shortcuts import render,HttpResponse,redirect
def index(request):
res = HttpResponse("<h1>首页</h1>")
res['username'] = "wq"
res.status_code = 700
return res
验证
URL:http://49.232.221.200:8888/index/
render函数
render指定模板,返回一个渲染后的HttpResponse对象
语法: render(request,template_name,context=None,content_type=None,status=None,using=None)
- request:固定参数,django封装的要求
- template_name:返回html模板
- context:传入模板中的内容,用于渲染模板,默认空字典
示例
from django.shortcuts import render
from datetime import datetime
def current_datetime(request):
now = datetime.now()
return render(request,'demo.html',{'datetime':now})
路由
# devops/devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('date/$',views.date),
]
视图
# devops/devops/views.py
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
def date(request):
from datetime import datetime
now = datetime.now()
return render(request,'date.html',{'now':now})
网页
# devops/templates/date.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>显示当前时间</title>
</head>
<body>
{{ now }}
</body>
</html>
验证
URL:http://49.232.221.200:8888/date/
redrict函数
redrict函数:重定向,发起第二次其你去
语法: redirect(to,*args,**kwargs)
参数可以是:
- 一个视图
- 一个绝对的或者相对的URL
- 一个模型,对象是重定向的URL
示例
from django.shortcuts import redirect
def test)redirect(request):
return redirect('https://www.baidu.com')
路由
# devops/devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('date/$',views.date),
]
视图
# devops/devops/views.py
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
def date(request):
from datetime import datetime
now = datetime.now()
# return render(request,'date.html',{'now':now})
# return redirect('http://www.baidu.com')
return redirect('/index')
def index(request):
res = HttpResponse("<h1>首页</h1>")
res['username'] = "wq"
res.status_code = 700
return res
验证
访问:http://49.232.221.200:8888/date
会跳到:http://49.232.221.200:8888/index/
流处理函数,实现图片下载
StreamingHttpResponse函数
StreamingHttpResponse函数:流式响应可迭代对象
路由
# devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('upload_list/$',views.upload_list),
re_path('download/(?P<filename>.*)$',views.download,name="download")
]
视图
# myapp/views.py
from django.shortcuts import render,HttpResponse,redirect
import os
from django.http import StreamingHttpResponse
# Create your views here.
def upload_list(request):
file_list=os.listdir('upload')
return render(request,"upload_list.html",{'file_list':file_list})
def download(request,filename):
file_path=os.path.join('upload',filename) # 使用os拼接可以有效的防止windwos反斜杠路径
res=StreamingHttpResponse(open(file_path,'rb'))
# 因为没有定义头部信息,浏览器读取出来是乱码,所以定义下
# 传输流
res['Content-Type']='application/octet-stream'
# 加描述
res['Content-Disposition']='attachment: filename=%s' %(os.path.basename(file_path))
return res
网页
# templates/upload_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件列表</title>
</head>
<body>
{% for i in file_list %}
<a href="{% url 'download' i %}">{{ i }}</a><br>
{% endfor %}
</body>
</html>
验证
FileResponse函数
FileResponse函数:如果提供文件下载建议方法
路由
# devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('upload_list/$',views.upload_list),
re_path('download/(?P<filename>.*)$',views.download,name="download")
]
视图
# myapp/views.py
from django.shortcuts import render,HttpResponse,redirect
import os
from django.http import StreamingHttpResponse,FileResponse
# Create your views here.
def upload_list(request):
file_list=os.listdir('upload')
return render(request,"upload_list.html",{'file_list':file_list})
def download(request,filename):
file_path=os.path.join('upload',filename) # 使用os拼接可以有效的防止windwos反斜杠路径
res=FileResponse(open(file_path,'rb'))
# 因为没有定义头部信息,浏览器读取出来是乱码,所以定义下
# 传输流
res['Content-Type']='application/octet-stream'
# 加描述
res['Content-Disposition']='attachment: filename=%s' %(os.path.basename(file_path))
return res
网页
# templates/upload_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件列表</title>
</head>
<body>
{% for i in file_list %}
<a href="{% url 'download' i %}">{{ i }}</a><br>
{% endfor %}
</body>
</html>
验证
JsonResponse函数
响应一个JSON对象
示例
from django.http import JsonResponse
def test_response(request):
res={ 'foo' : 'bar' }
return JsonResponse(res)
路由
# devops/urls.py
from django.urls import path,re_path
from myapp import views
urlpatterns = [
re_path('api/$',views.api)
]
视图
# myapp/views.py
from django.http import JsonResponse
def api(request):
res={ 'foo':'bar','age':'30'}
return JsonResponse(res)
验证
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!