Django入門(五)

1、Django中python的虛擬環境

  需求:假如公司只有一臺服務器,開發的項目基於Django1.5的。如今卻要基於Django2.0開發一套程序,且Django1.5不能卸載,必須還要安裝新版本。html

  這時候就須要用到虛擬環境了。前端

一、經過PyCharm建立

  File-->New Project-->Django-->出現下圖,如圖所示進行建立。python

二、經過命令建立

  安裝:
           -pip3 install virtualenv
      建立虛擬環境:
           -(1)virtualenv env_django(建立虛擬環境)正則表達式

           -(2)virtualenv --system-site-packages env_django(建立環境,繼承原安裝的模塊)
      激活該虛擬環境:
           -windows進到目錄裏,的Script文件夾輸入:activate
      退出虛擬環境:
           -deactivate
      在pycharm中使用虛擬環境
           -files--settings--Project--Project Interpreter--add選擇虛擬環境路徑下的python.exe便可django

2、Django 2.0 和Django 1.0 路由層的區別

  惟一的區別就是1.0版本路由層使用的是URL() ,而2.0使用的是re_path和path

  re_path

  與URL的用法相同,而且分組出來的數據也是字符串類型json

re_path('正則表達式',視圖函數,參數,別名)

  path

  path是屬於2.0新增的,傳的路徑,是準確路徑windows

path('準確路徑 | 轉化器', 視圖函數,參數,別名),
#轉化器由<>包裹,包含<轉化器類型:變量>,若沒有轉化器,將匹配任何字符串
path('test/<path:mouth>', views.re_test),

#轉化器類型
#str,匹配除了路徑分隔符(/)以外的非空字符串,這是默認的形式
#int,匹配正整數,包含0。
#slug,匹配字母、數字以及橫槓、下劃線組成的字符串。
#uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
#path,匹配任何非空字符串,包含了路徑分隔符(/)

自定義轉換器

對於一些複雜或者複用的須要,能夠自定義本身的轉換器。轉換器是一個類或接口,它的要求有三點:瀏覽器

  • regex 類屬性,字符串類型服務器

  • to_python(self, value) 方法,value是由類屬性 regex 所匹配到的字符串,返回具體的Python變量值,以供Django傳遞到對應的視圖函數中。
  • to_url(self, value) 方法,和 to_python 相反,value是一個具體的Python變量值,返回其字符串,一般用於url反向引用。app

# 編寫自定義轉換器
class MyCon:
        # 寫一個正則表達式
        regex = '[0-9]{4}'
        # 匹配出來的數據,會傳到這裏,retrun回去的,會被視圖函數接收
        def to_python(self, value):
        return int(value)
        # 反向解析用的
    def to_url(self, value):
        return '%04d' % value
# 註冊自定義轉換器
from django.urls import register_converter
register_converter(MyCon,'yyy')
# 使用自定義轉換器
path('test/<yyy:year>', views.re_test,name='test'), 

3、視圖層

HTTPRequest對象

Django將請求報文中的請求行、首部信息、內容主體封裝成 HttpResquest 類中的屬性

#經常使用屬性
# 前臺Post傳過來的數據,包裝到POST字典中
request.POST

# 前臺瀏覽器窗口裏攜帶的數據,包裝到GET字典中
request.GET

# 前臺請求的方式
request.method

# post提交的數據,body體的內容,前臺會封裝成:name=lqz&age=18&sex=1。適合處理非表單數據
request.body

# 取出請求的路徑,取不到數據部分
request.path

# 取出請求的路徑,能取到數據部分
request.get_full_path()

#取出表單請求方法爲POST,並編寫方式是enctype="multipart/form-data"的全部上傳文件信息
request.FILES

#包含全部的HTTP 首部信息,以字典的形式
request.META
#注意:request.META['HTTP_REFERER']  表示上一個跳轉頁面

HTTPResponse對象

響應對象主要有三種形式:

  1. HttpResponse():括號內直接跟一個具體的字符串做爲響應體返回
  2. render():將一個模板頁面中的模板語法進行渲染,最終渲染成一個html頁面做爲響應體。
  3. redirect():重定向

render()

#render(請求對象,模板名,模板須要的參數(字典形式))
render(request, template_name[, context])

#要知道render和redircet都是HttpResponse的對象
#render的內部原理
from django.template import Template,Context
#調用Template,傳入html標籤
temp=Template('<h1>{{ user }}</h1>')
#調用Context,傳入數據標籤
con=Context({'user':'lqz'})
#兩者合一
ret=temp.render(con)
#最後用HttpResponse傳出去
return HttpResponse(ret)

JsonRespons對象

向前端返回一個json格式字符串

from django.http import JsonResponse
def test(request):
    dic={'name':'xgp','age':18}
    return JsonResponse(dic)

    ll = ['name', 'age']
    # 報錯,默認不支持列表形式
    return JsonResponse(ll)

    # 支持列表形式
    return JsonResponse(ll,safe=False)

#JsonResponse方法內部實際上是調用了json模塊,在內部進行了轉換
import json
dic={'name':'lqz','age':18}
# 把字典轉換成json格式,返回到前臺
return HttpResponse(json.dumps(dic))

4、CBV和FBV

CBV是基於類的視圖(Class base view)和FBV基於函數的視圖(Function base view)

from django.views import View
class AddPublish(View):
    def dispatch(self, request, *args, **kwargs):
        print(request)
        print(args)
        print(kwargs)
        # 能夠寫相似裝飾器的東西,在先後加代碼
        obj=super().dispatch(request, *args, **kwargs)
        return obj

    def get(self,request):
        return render(request,'index.html')
    def post(self,request):
        request
        return HttpResponse('post')

5、簡單的文件上傳

前端

<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>

後臺

 
 
from django.shortcuts import render, HttpResponse, redirect

def
fileupload(request): if request.method == "GET": return render(request,"fileupload.html") if request.method == "POST": # 從字典種根據名字,把文件取出來 myfile = request.FILES.get("myfile") name = myfile.name # 打開文件,把上傳過來的文件保存到本地 with open(name,"wb") as f: for line in myfile: f.wirte(line) return HttpResponse('ok')
相關文章
相關標籤/搜索