1. 程式人生 > >Django之視圖層介紹

Django之視圖層介紹

lose scrip odin rip ase ret spa lap virt

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(‘上傳成功‘)
‘‘‘
簡單實現文件上傳功能

Django之視圖層介紹