Django之视图层介绍

1. 伪静态设置:

路由层:
url('^index/$', views.index),
url('^article/(?P<id>(\d+)).html/$', views.article, name='article')
#只有在正则表达式后面添加 ".html" 就可以成为伪静态的页面文件

2. rquest 获取对象

'''
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: 数据大汇总的字典
'''

3. Django的FBV与CBV的区别

FBV:function base views 函数方式完成视图响应
CBV:class base views 类方式完成视图响应 
'''
'''
视图层:
from django.shortcuts import HttpResponse
from django.views import View
class RegisterView(View):    #使用CBV要继承View这个类
    def get(self, request):
        return HttpResponse("响应get请求")
    def post(self, request):
        return HttpResponse("响应post请求")
路由层:
url('^path/$', views.RegisterView.as_views())    #注意使用CBV后面一定给要上.as_views()

4.Django的虚拟环境配置:

1.通过pip3安装虚拟环境:
    -- pip3 install virtualenv
2.前往目标文件夹:
    -- cd 目标文件夹  (C:\Virtualenv)
3.创建纯净虚拟环境:
    -- virtualenv 虚拟环境名 (py3-env1)
了解:创建非纯净环境:
    -- virtualenv-clone 本地环境 虚拟环境名
4.终端启动虚拟环境:
    -- cd py3-env1\Scripts
    -- activate
5.进入虚拟环境下的python开发环境
    -- python3
6.关闭虚拟环境:
    -- deactivate
7.PyCharm的开发配置
    添加:创建项目 -> Project Interpreter -> Existing interpreter -> Virtualenv Environment | System Interpreter -> 目标路径下的python.exe
    删除:Setting -> Project -> Project Interpreter -> Show All
Django创建虚拟环境使用,不懂就要看视频了

5.Django的简单实现文件上传功能

'''
前端: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/gukai/p/10771049.html