MVC和MTV模式


二 MVC和MTV模式

著名的MVC模式:所謂MVC就是把web應用分為模型(M),控制器(C),視圖(V)三層;他們之間以一種插件似的,松耦合的方式連接在一起。

模型負責業務對象與數據庫的對象(ORM),視圖負責與用戶的交互(頁面),控制器(C)接受用戶的輸入調用模型和視圖完成用戶的請求。

                  

Django的MTV模式本質上與MVC模式沒有什么差別,也是各組件之間為了保持松耦合關系,只是定義上有些許不同,Django的MTV分別代表:

       Model(模型):負責業務對象與數據庫的對象(ORM)

       Template(模版):負責如何把頁面展示給用戶

       View(視圖):負責業務邏輯,並在適當的時候調用Model和Template

       此外,Django還有一個url分發器,它的作用是將一個個URL的頁面請求分發給不同的view處理,view再調用相應的Model和Template

django的流程和命令行工具

django
    #安裝: pip3 install django

          添加環境變量

    #1  創建project
       django-admin startproject mysite

       ---mysite

          ---settings.py
          ---url.py
          ---wsgi.py

       ---- manage.py(啟動文件)  

    #2  創建APP       
       python mannage.py startapp  app01

    #3  settings配置
    
       TEMPLATES

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

       STATIC_URL = '/static/' 
       #  我們只能用 STATIC_URL,但STATIC_URL會按着你的STATICFILES_DIRS去找#4  根據需求設計代碼
           url.py
           view.py

    #5  使用模版
       render(req,"index.html")   

    #6  啟動項目
       python manage.py runserver  127.0.0.1:8090

    #7  連接數據庫,操作數據
       model.py

django的命令行工具

django-admin.py 是Django的一個用於管理任務的命令行工具,manage.py是對django-admin.py的簡單包裝,每一個Django Project里都會有一個mannage.py。

<1> 創建一個django工程 : django-admin.py startproject mysite

        當前目錄下會生成mysite的工程,目錄結構如下:

       

 

  • manage.py ----- Django項目里面的工具,通過它可以調用django shell和數據庫等。
  • settings.py ---- 包含了項目的默認設置,包括數據庫信息,調試標志以及其他一些工作的變量。
  • urls.py ----- 負責把URL模式映射到應用程序。

<2>在mysite目錄下創建blog應用: python manage.py startapp blog

       

<3>啟動django項目:python manage.py runserver 8080

       這樣我們的django就啟動起來了!當我們訪問:http://127.0.0.1:8080/時就可以看到:

       

<4>生成同步數據庫的腳本:python manage.py makemigrations  

                     同步數據庫:  python manage.py migrate   

       注意:在開發過程中,數據庫同步誤操作之后,難免會遇到后面不能同步成功的情況,解決這個問題的一個簡單粗暴方法是把migrations目錄下

                的腳本(除__init__.py之外)全部刪掉,再把數據庫刪掉之后創建一個新的數據庫,數據庫同步操作再重新做一遍。            

<5>當我們訪問http://127.0.0.1:8080/admin/時,會出現:

<5>當我們訪問http://127.0.0.1:8080/admin/時,會出現:

       

       所以我們需要為進入這個項目的后台創建超級管理員:python manage.py createsuperuser設置好用戶名和密碼后便可登錄啦!

<6>清空數據庫:python manage.py  flush

<7>查詢某個命令的詳細信息: django-admin.py  help  startapp

       admin 是Django 自帶的一個后台數據庫管理系統。

<8>啟動交互界面 :python manage.py  shell

     這個命令和直接運行 python 進入 shell 的區別是:你可以在這個 shell 里面調用當前項目的 models.py 中的 API,對於操作數據,還有一些小測試非常方便。

<9> 終端上輸入python manage.py 可以看到詳細的列表,在忘記子名稱的時候特別有用

實例練習1-提交數據並展示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>創建個人信息</h1>

<form action="/userInfor/" method="post">

    <p>姓名<input type="text" name="username"></p>
    <p>性別<input type="text" name="sex"></p>
    <p>郵箱<input type="text" name="email"></p>
    <p><input type="submit" value="submit"></p>

</form>

<hr>

<h1>信息展示</h1>

<table border="1">

    <tr>
        <td>姓名</td>
        <td>性別</td>
        <td>郵箱</td>
    </tr>
    {% for i in info_list %}

        <tr>
            <td>{{ i.username }}</td>
            <td>{{ i.sex }}</td>
            <td>{{ i.email }}</td>
        </tr>

    {% endfor %}

</table>

</body>
</html>


-----------------------url.py---------------------------------------
url(r'^userInfor/', views.userInfor)

-----------------------views.py--------------------------------------

info_list=[]

def userInfor(req):

    if req.method=="POST":
        username=req.POST.get("username",None)
        sex=req.POST.get("sex",None)
        email=req.POST.get("email",None)

        info={"username":username,"sex":sex,"email":email}
        info_list.append(info)

    return render(req,"userInfor.html",{"info_list":info_list})

實例練習2-提交數據並展示(數據庫)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>創建個人信息</h1>

<form action="/userInfor/" method="post">

    <p>姓名<input type="text" name="username"></p>
    <p>性別<input type="text" name="sex"></p>
    <p>郵箱<input type="text" name="email"></p>
    <p><input type="submit" value="submit"></p>

</form>

<hr>

<h1>信息展示</h1>

<table border="1">

    <tr>
        <td>姓名</td>
        <td>性別</td>
        <td>郵箱</td>
    </tr>
    {% for i in info_list %}

        <tr>
            <td>{{ i.username }}</td>
            <td>{{ i.sex }}</td>
            <td>{{ i.email }}</td>
        </tr>

    {% endfor %}

</table>

</body>
</html>


----------------------------------------------models.py
from django.db import models

# Create your models here.


class UserInfor(models.Model):

    username=models.CharField(max_length=64)
    sex=models.CharField(max_length=64)
    email=models.CharField(max_length=64)

----------------------------------------------views.py

from django.shortcuts import render

from app01 import models
# Create your views here.


def userInfor(req):

    if req.method=="POST":
        u=req.POST.get("username",None)
        s=req.POST.get("sex",None)
        e=req.POST.get("email",None)


       #---------表中插入數據方式一
            # info={"username":u,"sex":e,"email":e}
            # models.UserInfor.objects.create(**info)

       #---------表中插入數據方式二
        models.UserInfor.objects.create(
            username=u,
            sex=s,
            email=e
        )

        info_list=models.UserInfor.objects.all()

        return render(req,"userInfor.html",{"info_list":info_list})

    return render(req,"userInfor.html")

四 Django的配置文件(settings)

靜態文件設置:

一、概述:

     #靜態文件交由Web服務器處理,Django本身不處理靜態文件。簡單的處理邏輯如下(以nginx為例):

     #          URI請求-----> 按照Web服務器里面的配置規則先處理,以nginx為例,主要求配置在nginx.
                             #conf里的location

                         |---------->如果是靜態文件,則由nginx直接處理

                         |---------->如果不是則交由Django處理,Django根據urls.py里面的規則進行匹配

    # 以上是部署到Web服務器后的處理方式,為了便於開發,Django提供了在開發環境的對靜態文件的處理機制,方法是這樣:

    #1、在INSTALLED_APPS里面加入'django.contrib.staticfiles',

    #2、在urls.py里面加入
       if settings.DEBUG:  
           urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', 
           'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),   
            url(r'^static/(?P<path>.*)$',
          'django.views.static.serve',{'document_root':settings.STATIC_ROOT}), )  

    # 3、這樣就可以在開發階段直接使用靜態文件了。

二、MEDIA_ROOT和MEDIA_URL

        #而靜態文件的處理又包括STATIC和MEDIA兩類,這往往容易混淆,在Django里面是這樣定義的:

        #MEDIA:指用戶上傳的文件,比如在Model里面的FileFIeld,ImageField上傳的文件。如果你定義

        #MEDIA_ROOT=c:\temp\media,那么File=models.FileField(upload_to="abc/")#,上傳的文件就會被保存到c:\temp\media\abc  
        #eg:
            class blog(models.Model):  
                   Title=models.charField(max_length=64)  
                   Photo=models.ImageField(upload_to="photo") 
        #     上傳的圖片就上傳到c:\temp\media\photo,而在模板中要顯示該文件,則在這樣寫
        #在settings里面設置的MEDIA_ROOT必須是本地路徑的絕對路徑,一般是這樣寫:
                 BASE_DIR= os.path.abspath(os.path.dirname(__file__))  
                 MEDIA_ROOT=os.path.join(BASE_DIR,'media/').replace('\\','/') 

        #MEDIA_URL是指從瀏覽器訪問時的地址前綴,舉個例子:
            MEDIA_ROOT=c:\temp\media\photo  
            MEDIA_URL="/data/"
        #在開發階段,media的處理由django處理:

        #    訪問http://localhost/data/abc/a.png就是訪問c:\temp\media\photo\abc\a.png

        #    在模板里面這樣寫<img src="{{MEDIA_URL}}abc/a.png">

        #    在部署階段最大的不同在於你必須讓web服務器來處理media文件,因此你必須在web服務器中配置,
        #  以便能讓web服務器能訪問media文件
        #    以nginx為例,可以在nginx.conf里面這樣:

                 location ~/media/{
                       root/temp/
                       break;
                    }

        #    具體可以參考如何在nginx部署django的資料。

三、STATIC_ROOT和STATIC_URL、
    STATIC主要指的是如css,js,images這樣文件,在settings里面可以配置STATIC_ROOT和STATIC_URL,
    配置方式與MEDIA_ROOT是一樣的,但是要注意

    #STATIC文件一般保存在以下位置:

    #1、STATIC_ROOT:在settings里面設置,一般用來放一些公共的js,css,images等。

    #2、app的static文件夾,在每個app所在文夾均可以建立一個static文件夾,然后當運行collectstatic時,
    #    Django會遍歷INSTALL_APPS里面所有app的static文件夾,將里面所有的文件復制到STATIC_ROOT。因此,
    #   如果你要建立可復用的app,那么你要將該app所需要的靜態文件放在static文件夾中。

    # 也就是說一個項目引用了很多app,那么這個項目所需要的css,images等靜態文件是分散在各個app的static文件的,比
    #  較典型的是admin應用。當你要發布時,需要將這些分散的static文件收集到一個地方就是STATIC_ROOT。

    #3、STATIC文件還可以配置STATICFILES_DIRS,指定額外的靜態文件存儲位置。
    #  STATIC_URL的含義與MEDIA_URL類似。

    # ----------------------------------------------------------------------------
    #注意1:
        #為了后端的更改不會影響前端的引入,避免造成前端大量修改

        STATIC_URL = '/static/'               #引用名
        STATICFILES_DIRS = (
            os.path.join(BASE_DIR,"statics")  #實際名 ,即實際文件夾的名字
        )

        #django對引用名和實際名進行映射,引用時,只能按照引用名來,不能按實際名去找
        #<script src="/statics/jquery-3.1.1.js"></script>
        #------error-----不能直接用,必須用STATIC_URL = '/static/':
        #<script src="/static/jquery-3.1.1.js"></script>

    #注意2(statics文件夾寫在不同的app下,靜態文件的調用):

        STATIC_URL = '/static/'

        STATICFILES_DIRS=(
            ('hello',os.path.join(BASE_DIR,"app01","statics")) ,
        )

        #<script src="/static/hello/jquery-1.8.2.min.js"></script>

    #注意3:
        STATIC_URL = '/static/'
        {% load staticfiles %}
       # <script src={% static "jquery-1.8.2.min.js" %}></script>

其它重要參數設置:

APPEND_SLASH
       Default: True
       When set to True, if the request URL does not match any of the patterns in the URLconf and it 
       doesn’t end in a slash, an HTTP redirect is issued to the same URL with a slash appended. Note 
       that the redirect may cause any data submitted in a POST request to be lost.

五 Django URL (路由系統)

  URL配置(URLconf)就像Django 所支撐網站的目錄。它的本質是URL模式以及要為該URL模式調用的視圖函數之間的映射表;你就是以這種方式告訴Django,對於這個URL調用這段代碼,對於那個URL調用那段代碼。

urlpatterns = [

    url(正則表達式, views視圖函數,參數,別名),

]

 

參數說明:

  • 一個正則表達式字符串
  • 一個可調用對象,通常為一個視圖函數或一個指定視圖函數路徑的字符串
  • 可選的要傳遞給視圖函數的默認參數(字典形式)
  • 一個可選的name參數

5.1 Here’s a sample URLconf:

from django.conf.urls import url
from django.contrib import admin

from app01 import views

urlpatterns = [

    url(r'^articles/2003/$', views.special_case_2003),

    #url(r'^articles/[0-9]{4}/$', views.year_archive),

    url(r'^articles/([0-9]{4})/$', views.year_archive),  #no_named group

    url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),

    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),

]

Note:

 

#1   There’s no need to add a leading slash, because every URL has that. For
#    example, it’s ^articles, not ^/articles.

#2   A request to /articles/2005/03/ would match the third entry in the list.
#    Django would call the function views.month_archive(request, '2005', '03').

#3   /articles/2005/3/ would not match any URL patterns

#4   /articles/2003/ would match the first pattern in the list, not the second one

#5   /articles/2003/03/03/ would match the final pattern. Django would call the
#    functionviews.article_detail(request, '2003', '03', '03').

 

5.2 Named groups

      The above example used simple, non-named regular-expression groups (via parenthesis) to capture bits of the URL and pass them as positional arguments to a view. In more advanced usage, it’s possible to use named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.

       In Python regular expressions, the syntax for named regular-expression groups is (?P<name>pattern), where name is the name of the group and pattern is some pattern to match.

Here’s the above example URLconf, rewritten to use named groups:

import re

ret=re.search('(?P<id>\d{3})/(?P<name>\w{3})','weeew34ttt123/ooo')

print(ret.group())
print(ret.group('id'))
print(ret.group('name'))

ready
from django.conf.urls import url
  
from . import views
  
urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail),
]

This accomplishes exactly the same thing as the previous example, with one subtle difference: The captured values are passed to view functions as keyword arguments rather than positional arguments.

5.3  Passing extra options to view functions

       URLconfs have a hook that lets you pass extra arguments to your view functions, as a Python dictionary.

The django.conf.urls.url() function can take an optional third argument which should be a dictionary of extra keyword arguments to pass to the view function.

For example:

from django.conf.urls import url
from . import views
  
urlpatterns = [
    url(r'^blog/(?P<year>[0-9]{4})/$', views.year_archive, {'foo': 'bar'}),
]

  In this example, for a request to /blog/2005/, Django will call views.year_archive(request, year='2005',foo='bar').

This technique is used in the syndication framework to pass metadata and options to views.

Dealing with conflicts

       It’s possible to have a URL pattern which captures named keyword arguments, and also passes arguments with the same names in its dictionary of extra arguments. When this happens, the arguments in the dictionary will be used instead of the arguments captured in the URL.

5.4 name param

 

urlpatterns = [
    url(r'^index',views.index,name='bieming'),
    url(r'^admin/', admin.site.urls),
    # url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/([0-9]{4})/$', views.year_archive),
    # url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    # url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),

]
###################

def index(req):
    if req.method=='POST':
        username=req.POST.get('username')
        password=req.POST.get('password')
        if username=='alex' and password=='123':
            return HttpResponse("登陸成功")



    return render(req,'index.html')

#####################

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#     <form action="/index/" method="post">#}
     <form action="{% url 'bieming' %}" method="post">
         用戶名:<input type="text" name="username">
         密碼:<input type="password" name="password">
         <input type="submit" value="submit">
     </form>
</body>
</html>


#######################

 

5.5 Including other URLconfs

#At any point, your urlpatterns can “include” other URLconf modules. This
#essentially “roots” a set of URLs below other ones.

#For example, here’s an excerpt of the URLconf for the Django website itself.
#It includes a number of other URLconfs:


from django.conf.urls import include, url

urlpatterns = [
   url(r'^admin/', admin.site.urls),
   url(r'^blog/', include('blog.urls')),
]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM