视图层

反向解析;用在视图层,模板层

名称空间:名称最好取app名字_名字

伪静态:伪装成静态文件,但不是静态文件

根路径响应到指定视图函数

url(r'^$',views.book)

没有配置的路径响应到错误的视图:

url(r'', views.errors)

1、虚拟环境

创建: 选NEW environment using      

Name中填写新虚拟环境的名字,或者使用默认名字,方便以后安装第三方包和其他项目使用;

在Location中填写新环境的文件目录;

在Base interpreter下拉框中选择Python解释器;

勾选Inherit global site-packages可以使用base interpreter中的第三方库,不选将和外界完全隔离;

勾选Make available to all projects可将此虚拟环境提供给其他项目使用。

安装:
        -pip3 install virtualenv
    创建虚拟环境:
        -(1)virtualenv env_django(创建虚拟环境)

   -(2)virtualenv  env_django(创建纯净环境)
        -(2)virtualenv --system-site-packages env_django(创建环境,继承原安装的模块)
    激活该虚拟环境:
        -windows进到目录里,的Script文件夹输入:activate
        -linux:soruse env1/Script/activate
    退出虚拟环境:
        -deactivate
    在pycharm中使用虚拟环境
        -files--settings--Project--Project Interpreter--add选择虚拟环境路径下的python.exe即可

2、django 2.0 和 django 1.0 路由层区别(url,re_path分组分出来的数据,是字符串)

-re_path:跟1.0的url用法相同

-path:传的路径,是准确路径

   5个转换器-->path('test/<path:year>', views.re_test),

   str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式

   int,匹配正整数,包含0。

   slug,匹配字母、数字以及横杠、下划线组成的字符串。

   uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。

   path,匹配任何非空字符串,包含了路径分隔符(/)(不能用?)

自定义转换器:

 1、定义一个类  class MyCon:  

 写一个正则表达式   regex='[0-9]{4}'   

匹配出来的数据,会传到这里,   

def to_python(self,value):    

return int(value)   

def to_url(self,value):

反向解析;用在视图层,模板层    

不够四位,用0补齐

return '%04d'%value

占8位,不够的话用0补全,多了全部显示

%08d

为假,不会加反斜杠 APPEND_SLASH=False      

 3 视图层之HttpRequest对象

前台Post传过来的数据,包装到POST字典中

request.POST

前台浏览器窗口里携带的数据,包装到GET字典中

request.GET

前台请求的方式

request.method

post提交的数据,body体的内容,前台会封装成:name=lqz&age=18&sex=1

request.body

取出请求的路径,取不到数据部分

print(request.path)

取出请求的路径,能取到数据部分

print(request.get_full_path())

print(request.META)

4 视图层之HttpResponse对象
三件套:render,HttpResponse,redirect
        render函数:
            temp=Template('<h1>{{ user }}</h1>')
            con=Context({'user':'lqz'})
            ret=temp.render(con)
            print(ret)
            # return render(request,'index.html')
            return HttpResponse(ret)
5 视图层之JsonResponse对象    
-导入:from django.http import JsonResponse
-视图函数中:
def test(request):
                import json
                # dic={'name':'lqz','age':18}
                ll = ['name', 'age']
                # 把字典转换成json格式,返回到前台
                # return HttpResponse(json.dumps(dic))
                # 把列表转换成json格式,返回到前台
                # return HttpResponse(json.dumps(ll))
                # 把字典转换成json格式,返回到前台
                # return JsonResponse(dic)
                # 报错,默认不支持列表形式
                # return JsonResponse(ll)
                # 支持列表形式
                return JsonResponse(ll,safe=False)

6 CBV和FBV    
  -基于类的视图
    -1 路由层:url(r'^test/', views.Test.as_view()),
    -2 视图层
      -导入:from django.views import View
      -写一个类:
        class Test(View):
          def get(self, request):#一定要传request对象
            return HttpResponse('get-test')
          def post(self, request):
            return HttpResponse('post-test')
   -基于函数的视图
7 简单文件上传
     前端:
            <form action="" method="post" enctype="multipart/form-data">
            {#<form action="" method="post" enctype="application/x-www-form-urlencoded">#}
                <input type="file" name="myfile">
                <input type="text" name="password">
                <input type="submit" value="提交">
            </form>
        后台:
            def fileupload(request):
                if request.method=='GET':
                    return render(request,'fileupload.html')
                if request.method=='POST':
                    # FILES
                    print(request.FILES)
                    print(type(request.FILES.get('myfile')))
                    # 从字典里根据名字,把文件取出来
                    myfile=request.FILES.get('myfile')
                    from django.core.files.uploadedfile import InMemoryUploadedFile
                    # 文件名字
                    name=myfile.name
                    # 打开文件,把上传过来的文件存到本地
                    with open(name,'wb') as f:
                        # for line in myfile.chunks():
                        for line in myfile:
                            f.write(line)
                    return HttpResponse('ok')
    
        补充:*****编码方式multipart/form-data或者:application/x-www-form-urlencoded传的数据,都可以从POST中取出来
 

 render     返回模板

 redirect    重定向

 HttpResponse 返回字符串

原文地址:https://www.cnblogs.com/zhouhao123/p/9931222.html