Django(4)

'''
1. 虚拟环境:处理版本共存问题 *
2. 伪静态(路由项目设置,2.x的路由分发)***
3. request *****
4. CBV *****
5. 文件上传 ****

---------------------------

虚拟环境---解决版本共存

1. 用pycharm选择virtualenv创建一个纯净环境
2. 将环境copy到需要指定长期使用的文件夹下
3. 再次创建项目时,将该环境添加到pycharm环境选择中
4. 为该环境添加需要处理的版本共存包

 2. 路由配置主页和404

  路由层:

from django.urls import path, re_path
urlpatterns = [
# 主页最上方配置
re_path('^$', root, name="root"),
re_path('^index/$', index),
re_path('^home/$', home),

# 其他路由...

# 404配在最下方
re_path('/$', error)
]
视图层:
from django.shortcuts import render, redirect, reverse
# 主页
def root(request):
return render(request, 'root.html')
def index(request):
return redirect(reverse('root'))
def home(request):
return redirect(reverse('root'))
# 404
def error(request):
return render(request, 'error.html')

3. WEI静态

动态页面:数据内容会发生变化的页面
静态页面:数据内容不会发生变化的页面
针对SEO(搜索引擎优化),静态页面更容易被搜索引擎网站收录
伪静态就是讲动态页面伪装成静态页面,容易被搜索引擎网站收录,从而增加搜索概率,提高流量


  

路由层:
url('^index/$', views.index),
url('^article/(?P<id>(\d+)).html/$', views.article, name='article')

视图函数层:
def index(request):
return render(request, 'index.html')
def article(request, id):
return render(request, 'article.html', {'id': id})

模板层:
index.html
<a href="{% url 'article' 1 %}">第一篇文章</a>
<a href="{% url 'article' 2 %}">第二篇文章</a>
<a href="{% url 'article' 3 %}">第三篇文章</a>

article.html
<h1>第{{ id }}篇文章</h1>

三,request对象

  

1. method: 请求方式
2. GET: get请求的参数
3. POST: post请求的参数(本质是从bdoy中取出来)
4. body: post提交的数据(不能直接查看)
5. path: 请求的路径,不带参数
6. request.get_full_path(): 请求路径,带参数
7. FILES: 文件数据
8. encoding: 编码格式
9. META: 数据大汇总的字典

四,FBV与CBV

FBV:function base views 函数方式完成视图响应
CBV:class base views 类方式完成视图响应
'''
'''
视图层:
from django.shortcuts import HttpResponse
from django.views import View
class CBVView(View):
def get(self, request):
return HttpResponse("响应get请求")
def post(self, request):
return HttpResponse("响应post请求")
路由层:
url('^path/$', views.CBVView.as_views())

五,文 件上传

前端:upload.html页面
1.往自身路径发送post请求,要将第四个中间件注释
2.multipart/form-data格式允许发送文件
3.multiple属性表示可以多文件操作
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple="multiple">
<input type="submit" value="上传">
</form>

后台:re_path('^upload/$', upload)
def upload(request):
if request.method == "GET":
return render(request, 'upload.html')
if request.method == "POST":
# 如果一个key对应提交了多条数据,get取最后一个数据,getlist取全部数据
last_file = request.FILES.get('files', None)
files = request.FILES.getlist('files', None)
# import django.core.files.uploadedfile.TemporaryUploadedFile
# file是TemporaryUploadedFile类型,本质是对系统file类封装,就是存放提交的文件数据的文件流对象
for file in files:
with open(file.name, 'wb') as f:
for line in file: # 从file中去数据写到指定文件夹下的指定文件中
f.write(line)
return HttpResponse('上传成功')

 

 

猜你喜欢

转载自www.cnblogs.com/chencuizhen/p/10450510.html