python django環境配置 (二)

統一資源的配置:

接着上一篇的Django服務器配置,這裏主要修改默認路徑,將前端資源進行統一管理。首先,我們先來看一下Django下運行statapp後的文件目錄樹(form.py爲隨後單獨創建)

├─account
│  ├─assets
│  │  ├─css
│  │  ├─fonts
│  │  ├─js
│  │  └─sass
│  │      ├─base
│  │      ├─components
│  │      ├─layout
│  │      └─libs
│  ├─migrations
│  │  └─__pycache__
│  └─__pycache__
├─static
│  ├─assets
│  │  ├─css
│  │  ├─fonts
│  │  ├─js
│  │  └─sass
│  │      ├─base
│  │      ├─components
│  │      ├─layout
│  │      └─libs
│  └─images
│      └─gallery
│          ├─fulls
│          └─thumbs
└─templates
    ├─account
    ├─admin
    │  ├─auth
    │  │  └─user
    │  ├─edit_inline
    │  ├─includes
    │  └─widgets
    └─registration

這裏template主要用來存放前端的HTML文件,static主要用於存放一些圖片以及CSS格式信息。在創建好一個app功能之後,修改setting.py和urls.py文件,定位到相應的文件夾功能之上。

#setting.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates'),],#這裏自定義HTML文件存放位置
        'APP_DIRS': False,#這裏修改則不允許系統按照默認方式尋找模板文件。
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',

            ],
        },
    },
]
#這裏修正靜態資源的配置
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR,"static"),
)

文件的作用:

model.py:定義保存到數據庫中數據字段的類型,性質(unique,主鍵,外鍵)
admin.py:在django默認的後臺用戶管理界面進行數據內容的註冊以及可視化管理(數據庫的視圖層)
forms.py:定義了在網頁中POST字段提交上來的表單字段以及格式,注意前端label的name要和forms表單中的一致。
model.py:涉及到數據庫所保存的字段類型。Django對於數據庫的操作統一採用ORM格式。
url.py:綁定了統一資源定位符和其所調用的功能。
views.py:最重要的一個函數,是對於後端邏輯功能的主要實現模塊,一般請求分爲POST與GET。可分別針對實現相應功能。

這裏在forms或model常用內部類Meta對模型進行行爲功能上的補充,其中可以定義數據庫中表的名字,也可以定義排序等功能。

class Foo(models.Model): 
    bar = models.CharField(maxlength=30)

    class Meta: 
    #

在實戰的項目之中,form.py有兩種繼承方式,代碼如下:

from django import forms
from django.contrib.auth.models import User
from .models import UserProfile
class LoginForm(forms.Form):
    """docstring for LoginForm"""
    username = forms.CharField()
    password = forms.CharField(widget = forms.PasswordInput)


class RegistrationForm(forms.ModelForm):##
    password = forms.CharField(label="Password",widget=forms.PasswordInput)
    password2 = forms.CharField(label="Confirm Password",widget=forms.PasswordInput)

    class Meta:
        model = User###這裏申明的類型
        fields = ("username", "email")

    def clean_password2(self):#隨後在調用is_valid()會自動調用這種方法
        cd =self.cleaned_data
        if cd['password'] !=cd['password2']:
            raise forms.ValidationError("passwords do not match")
        return cd['password2']

class UserProfile(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ("phone", "birth")

上述代碼分別定義了註冊以及登陸的兩種表單,其中forms.Form中的數據繼承後無需寫入數據庫,相反,forms.ModelForm繼承後的數據是需要寫入數據庫之中的,就流程上而言,我們是先寫好model中保存到數據庫的字段,隨後再來定義forms,定義好以後,在admin.py中註冊代碼如下:

from django.contrib import admin
from .models import UserProfile

# Register your models here.
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'birth', 'phone')
    list_filter = ('phone',)

admin.site.register(UserProfile,UserProfileAdmin)

views.py內容:

對於前端過來的HTTP請求通常分爲四種:

POST:(改)POST表示可能修改變服務器上的資源的請求
GET:(查)GET用於信息獲取,而且應該是安全的和冪等的
PUT:
DELETE:(刪)

get/post區別:
1、GET請求的數據會附在URL之後(就是把數據放置在HTTP協議頭中),以?分割URL和傳輸數據,參數之間以&相連,如果數據是英文字母/數字,原樣發送,如果是空格,轉換爲+,如果是中文/其他字符,則直接把字符串用BASE64加密。POST把提交的數據則放置在是HTTP包的包體中,以FORM表單形式提交。
2、POST的安全性要比GET的安全性高。
這裏很重要的一點應用就是爬蟲:

###get
def search_info(value):
#所謂的get方法其實就是直接改變url裏面search_text的關鍵字來獲得查詢
#注意Python2.x的區別
    url_values=urllib.parse.urlencode(value)#我知道了,這裏的數據封裝就是吧/0X的形式轉化爲%以便和網頁形式相符合
    url="https://movie.douban.com/subject_search?"+url_values+"&cat=1002"
    bsobj=BeautifulSoup(urllib.request.urlopen(url).read().decode('UTF-8'),'lxml')
    return bsobj
import urllib.request
import urllib.parse
import json

content = input("請輸入需要翻譯的內容:")

url = "XX翻譯網站"
data = {}
data['type'] = 'AUTO'
data['i'] = content
data['doctype'] = 'json'
data['xmlVersion'] = '1.6'
data['keyfrom'] = 'fanyi.web'
data['ue'] = 'UTF-8'
data['typoResult'] = 'true'
data = urllib.parse.urlencode(data).encode('utf-8')

response = urllib.request.urlopen(url, data)##在此處將post數據提交
html = response.read().decode('utf-8')
target = json.loads(html)#這其實是一種jason結構,

隨後我們來看在網頁之中views後端如何處理前端的請求:

def user_register(request):
    if request.method == "POST":
        user_form = RegistrationForm(request.POST)
        userprofile_form=  UserProfile(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit= False)##數據並沒有被保存到數據庫
            new_user.set_password(user_form.cleaned_data['password'])##再次設置對象的密碼
            new_user.save()
            new_profile = userprofile_form.save(commit= False)
            new_profile.user = new_user
            new_profile.save()
            return HttpResponse('succesfully')
        else:
            return HttpResponse('sorry , your can not register.')
    else:
        user_form=RegistrationForm()
        return render(request,"account/register.html",{'form':user_form})

這裏需要注意的是if/else分別處理了request.POST&request.GET請求,提交上來的form表單形式如下:

<tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" value="sad" maxlength="150" required id="id_username" /><br /><span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span></td></tr>
<tr><th><label for="id_email">Email address:</label></th><td><input type="email" name="email" value="[email protected]" maxlength="254" id="id_email" /></td></tr>
<tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" required id="id_password" /></td></tr>
<tr><th><label for="id_password2">Confirm Password:</label></th><td><input type="password" name="password2" required id="id_password2" /></td></tr>
[25/Oct/2017 10:21:40] "POST /account/register/ HTTP/1.1" 200 11

這裏調用form表單類讀取POST數據後,有兩個很重要的方法:is_valid()查詢數據是否有空缺或不和要求返回TRUE/FALSE。cleaned_data()返回K-V字典。都是在後端數據處理需要時常用到的功能。
此外,這裏需要對比三個歷史函數:1、HttpResponse 2、render 3、render_to_response的區別
我們的類方法:objects.all()、objects.get()方法都是一種與數據庫交互的ORM,其作用是對數據庫進行查詢操作。高級語言對數據庫的操作有兩種方式:1、嵌入式的SQL的語言。2、ORM
相比於嵌入式的SQL,ORM雖然在定義時候稍微麻煩,但是其優點也很明顯:

1、可移植性性強。 2、安全性好。 3、查詢語法簡單。

前端部分:

不知道大家有沒有注意到setting.py中定義的中間件:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

這裏所有前端的form表單都需要在其後加上{% csrf_token %}以規避跨站點請求僞造。

            <form action="#" method="post">{% csrf_token %}
                <input type="text" Name="username" placeholder="用戶名" required="">
                <input type="text" Name="email" placeholder="郵箱" required="">
                <input type="password" Name="password" placeholder="密碼" required="",id="password">
                <input type="password" Name="password2" placeholder="確認密碼" required="",id="password2">
                <input type="date" Name="birth" placeholder="出生日期" required="",id="birth">
                <input type="text" Name="phone" placeholder="手機號碼" required="",id="phone">
            <ul class="actions">
                <li><input type="submit" value="Login" class="button special" /></li>
            </ul>
            </form><!-- 這裏有一點需要注意的是提交按鈕也必須在表單之中 -->

此外,這些靜態代碼塊也可以用來替代絕對地址,使代碼具有好的移植性。

<!-- 一定要讀取這些中間件(setting.py中) -->
{% load static %}
{% load staticfiles %}
    <!-- Style --> <link rel="stylesheet" href="{% static '/assets/css/style.css' %}" type="text/css" media="all">

網頁快速搭建的基本流程:1、在setting.py中註冊。2、在urls.py中定義統一資源定位符和其跳轉的功能模塊。3、model定義存入數據庫的模型,forms繼承model模板,定義POST傳來的數據格式。4、views.py設置後端功能。5、前端模塊。

框架:

MVC VS MTV(Django)

MVC

MTV
其實之間區別並不大,無非使python將後端業務邏輯view.py與templete分開來,鬆耦合。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章