Django基礎

1、HTTP協議

一、請求協議:
  請求首行(請求方式、請求路徑、協議版本號)
  請求頭(鍵值對)
  \r\n\r\n\
  請求體(向服務器發送的數據)html

二、響應協議:
  響應首行(響應協議,版本號、狀態碼、狀態的簡單描述)
  響應頭
  響應體(hello,world!)python

ps、狀態碼:web

  數字 1 開頭 > 服務器正在處理請求
  數字 2 開頭 > 處理成功
  數字 3 開頭 > 重定向
  數字 4 開頭 > 客戶端錯誤
  數字 5 開頭 > 服務器錯誤ajax

2、web框架

一、wsgiref模塊

  wsgiref模塊按照某種協議,封裝了socket

python中三大主流框架:正則表達式

一、socket-------> 二、路由與視圖函數的映射關係-------->三、模板的替換sql

django數據庫

1:用了別人的  2:本身的  3:本身的django

flaskjson

1:用了別人的  2:本身的  3:用了別人的:jianjia2flask

tornado

1:本身的      2:本身的  3:本身的

二、Django的安裝和項目的建立

一、cmd安裝django:

pip3 install django==1.11.9 指定版本號
pip3 install django==1.11.9 -i http://pypi.hustunique.org/simple 指定版本號,指定國內鏡像

二、pycharm安裝django

file ----> setting----> project interpreter

ps:!!!全部項目,包括文件夾,不能出現中文
  電腦名字也不能出現中文
  一個工程(project)就是一個項目

三、建立項目

3.1 cmd方式

  建立django(到指定的目錄下):

指定的目錄下 : django-admin startproject 項目名字

  建立APP:

python3 manage.py startapp app(名字)

  運行項目:

python3 manage.py runserver 127.0.0.0:9898 #host:端口號

3.2 pycharm方式:

  new project 選擇 django (能夠指定APP的名字)

  運行項目:點擊pycharm上方的綠箭頭

 

3、Django目錄結構與路由層

 一、目錄結構

app名字的文件夾:
    -migrations文件夾:放數據庫遷移的數據
    -admin.py :後臺管理相關
    -apps.py  :app配置相關
    -models   :ORM相關(數據庫)
    -test     :測試相關
    -views    :視圖函數(前期主要寫這個)
項目名字的文件夾:
    -settings :項目全局配置相關
    -urls     :路由和視圖函數的映射關係
    -wsgi     :socket 服務相關
templates :
    -全部模板文件(html頁面)
manage.py : 
    -全部命令的入口
db.sqlite3
    -數據庫文件

二、路由層(urls的配置)

一、路由的做用

  url地址和視圖函數的對應關係

二、簡單路由配置

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/', views.test),
    url(r'^index/', views.my_index),
    url(r'^time/', views.know_time),
]
#第一個參數:傳一個正則表達式,第二個參數:視圖函數

三、無名分組

#瀏覽器輸入:
127.0.0.1:8008/time/0000/00      #4位0-9數字/2位0-9數字

#
urls: url(r'^time/([0-9]{4})/([0-9]{2})$', views.know_time), #views: def know_time(request,year,mon): print(year) print(mon) import time ctime=time.strftime("%Y-%m-%d %X") return HttpResponse(ctime)

(一個括號一個分組)分組分出幾個數據,視圖函數就要用幾個參數接收!

四、有名分組

#瀏覽器地址欄輸入:
127.0.0.1:8008/time/2010/03     #同無名分組

#urls:
url(r'^time/(?P<year>[0-9]{4})/(?P<mon>[0-9]{2})$', views.know_time),
# 分組出幾個數據,會以關鍵字參數形式(例如上面的year和mon),傳到視圖
函數

#views:
def know_time(request,mon,year):#第二和第三個參數需對應上方
    print(year)
    print(mon)
    import time
    ctime=time.strftime("%Y-%m-%d %X")
    return HttpResponse(ctime)

五、路由分發

  1. 在不一樣app中建立urls.py子路由
  2. 總路由(urls)中導入 from django.conf.urls import include
  3. url(r'^app01/',include('app01.urls')),
#總路由:
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app01/', include('app01.urls')),]

#子路由:
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/', views.test),
    url(r'^index/', views.my_index),]

#視圖函數:
from django.shortcuts import render,HttpResponse,redirect

def test(request):
    return HttpResponse('hello,world')

def my_index(request):
    return render(request,'app01/index.html')
示例

六、反向解析

#給urls中的路徑命名(此處更改,視圖函數重定向或模板中也需變動,全部須要反向解析):
url(r'^index93213219/',views.index,name='index'),

#1.在視圖函數中:
from django.shortcuts import reverse 
url=reverse('index')    #這樣就能拿到路徑

#2.在模板中使用: 
{% url 'index'%}

七、名稱空間

#不一樣app中路由名字重複(不推薦) 命名的時候最好:app01_index 或者如#下方指定名稱空間

#總路由作分發的時候,能夠指定名稱空間:
url(r'^app02/',include('app02.urls,namespace='app02')),
反向解析
模板層:{% url 'app02:index' %}
視圖層:url=reverse('app02:index')

4、Django 視圖層

視圖層 簡單來講 就是 views的配置。

一、請求對象

# 視圖函數至少要有一個參數,request對象,瀏覽器請求過來的全部數據(地址,請求頭,請求體)

def myview(request):
    # 請求方式
    print(request.method)
    # 請求體中的內容(當成字典)
    print(request.POST)
    # 瀏覽器窗口傳過來的數據http://127.0.0.1:8000/app01/myview/?name=lqz&age=18
    print(request.GET)
    # 上傳的文件
    print(request.FILES)
    # 請求的路徑,不帶數據
    print(request.path)
    #請求體原生數據
    print(request.body)
    # 方法:
    # 請求的全路徑,帶着數據
    print(request.get_full_path())
    print(request.is_ajax())

    return HttpResponse('ok')

二、請求對象的FILES(上傳文件)

def myview(request):
    if  request.method=='GET':
        return render(request,'test.html')
    elif request.method=='POST':
        file_dic=request.FILES
        print(file_dic)
        file=file_dic.get('myfile')
        print(type(file))
        # from django.core.files.uploadedfile import InMemoryUploadedFile
        # 文件名字
        name=file.name
        # 打開一個空文件
        with open(name,'wb') as f:
            # 循環上傳的文件對象
            for line in file:
                # 一行一行外空文件中寫
                f.write(line)

        return HttpResponse('ok')
views
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#1寫全路徑#}

{#<form action="http://127.0.0.1:8000/app01/myview/" method="post">#}
{#2寫請求地址---推薦第二種   enctype="multipart/form-data"  這種格式,才能提交文件#}
<form action="/app01/myview/" method="post" enctype="multipart/form-data">
{#3 寫空#}
{#<form action="" method="post">#}
    <p>用戶名:<input type="text" name="name"></p>
    <p>密碼:<input type="password" name="password"></p>
    <p><input type="file" name="myfile"></p>

    <input type="submit" value="提交">

</form>
</body>
</html>
test.html

三、響應對象的三件套

  1. HttpResponse :返回字符串形式
  2. render     : 返回html頁面形式
  3. redirect            :返回重定向的頁面(例如跳轉另外一頁面)

四、響應對象之JsonResponse

往前臺返回json格式數據

一、導入:form django.http import JsonResponse
二、視圖函數 返回: renturn JsonResponse(字典)
三、視圖函數 返回: renturn JsonResponse(列表,safe=Fales)

五、CBV(基於類的視圖)和FBV(基於函數的視圖)

上述示例的視圖函數都是FBV

#CBV : 
from django.views import View
class Test(View):
    def get(self,request):
        renturn HttpResponse('CBV-->get func')
    def post(self,request):
        renturn HttpResponse('CBV-->post func')
#urls中:
url(r'^test/',views.Test.as_view())
相關文章
相關標籤/搜索