Python之路【第十六篇】:Django【基礎篇】

http://www.cnblogs.com/wupeiqi/articles/5237704.htmljavascript

 

Python的WEB框架有Django、Tornado、Flask 等多種,Django相較與其餘WEB框架其優點爲:大而全,框架自己集成了ORM、模型綁定、模板引擎、緩存、Session等諸多功能。css

基本配置

1、建立django程序html

  • 終端命令:django-admin startproject sitename
  • IDE建立Django程序時,本質上都是自動執行上述命令

其餘經常使用命令:java

  python manage.py runserver 0.0.0.0
  python manage.py startapp appname
  python manage.py syncdb
  python manage.py makemigrations
  python manage.py migratepython

  python manage.py createsuperusermysql

2、程序目錄web

3、配置文件sql

一、數據庫數據庫

1
2
3
4
5
6
7
8
9
10
DATABASES  =  {
     'default' : {
     'ENGINE' 'django.db.backends.mysql' ,
     'NAME' : 'dbname' ,
     'USER' 'root' ,
     'PASSWORD' 'xxx' ,
     'HOST' : '',
     'PORT' : '',
     }
}

二、模版django

1
2
3
TEMPLATE_DIRS  =  (
         os.path.join(BASE_DIR, 'templates' ),
     )

三、靜態文件

1
2
3
STATICFILES_DIRS  =  (
         os.path.join(BASE_DIR, 'static' ),
     )

路由系統

一、單一路由對應

1
url(r '^index$' , views.index),

二、基於正則的路由

1
2
url(r '^index/(\d*)' , views.index),
url(r '^manage/(?P<name>\w*)/(?P<id>\d*)' , views.manage),

三、添加額外的參數

1
url(r '^manage/(?P<name>\w*)' , views.manage,{ 'id' : 333 }),

四、爲路由映射設置名稱

1
2
url(r '^home' , views.home, name = 'h1' ),
url(r '^index/(\d*)' , views.index, name = 'h2' ),

設置名稱以後,能夠在不一樣的地方調用,如:

  • 模板中使用生成URL     {% url 'h2' 2012 %}
  • 函數中使用生成URL     reverse('h2', args=(2012,))      路徑:django.urls.reverse
  • Model中使用獲取URL  自定義get_absolute_url() 方法
      View Code

獲取請求匹配成功的URL信息:request.resolver_match

五、根據app對路由規則進行分類

1
url(r '^web/' ,include( 'web.urls' )),

六、命名空間

a. project.urls.py

1
2
3
4
5
6
from  django.conf.urls  import  url,include
 
urlpatterns  =  [
     url(r '^a/' , include( 'app01.urls' , namespace = 'author-polls' )),
     url(r '^b/' , include( 'app01.urls' , namespace = 'publisher-polls' )),
]

b. app01.urls.py

1
2
3
4
5
6
7
from  django.conf.urls  import  url
from  app01  import  views
 
app_name  =  'app01'
urlpatterns  =  [
     url(r '^(?P<pk>\d+)/$' , views.detail, name = 'detail' )
]

c. app01.views.py

1
2
3
def  detail(request, pk):
     print (request.resolver_match)
     return  HttpResponse(pk)

以上定義帶命名空間的url以後,使用name生成URL時候,應該以下:

  • v = reverse('app01:detail', kwargs={'pk':11})
  • {% url 'app01:detail' pk=12 pp=99 %}

django中的路由系統和其餘語言的框架有所不一樣,在django中每個請求的url都要有一條路由映射,這樣才能將請求交給對一個的view中的函數去處理。其餘大部分的Web框架則是對一類的url請求作一條路由映射,從而是路由系統變得簡潔。

經過反射機制,爲django開發一套動態的路由系統Demo: 點擊下載

模板

一、模版的執行

模版的建立過程,對於模版,其實就是讀取模版(其中嵌套着模版標籤),而後將 Model 中獲取的數據插入到模版中,最後將信息返回給用戶。

  View Code
  View Code
  View Code
  View Code
  View Code

二、模版語言

 模板中也有本身的語言,該語言能夠實現數據展現

  • {{ item }}
  • {% for item in item_list %}  <a>{{ item }}</a>  {% endfor %}
      forloop.counter
      forloop.first
      forloop.last 
  • {% if ordered_warranty %}  {% else %} {% endif %}
  • 母板:{% block title %}{% endblock %}
    子板:{% extends "base.html" %}
       {% block title %}{% endblock %}
  • 幫助方法:
    {{ item.event_start|date:"Y-m-d H:i:s"}}
    {{ bio|truncatewords:"30" }}
    {{ my_list|first|upper }}
    {{ name|lower }}

三、自定義simple_tag

a、在app中建立templatetags模塊

b、建立任意 .py 文件,如:xx.py

c、在使用自定義simple_tag的html文件中導入以前建立的 xx.py 文件名

1
{ %  load xx  % }

d、使用simple_tag

1
2
{ %  my_simple_time  1  2  3 % }
{ %  my_input  'id_username'  'hide' % }

e、在settings中配置當前app,否則django沒法找到自定義的simple_tag  

更多見文檔:https://docs.djangoproject.com/en/1.10/ref/templates/language/

中間件

django 中的中間件(middleware),在django中,中間件其實就是一個類,在請求到來和結束後,django會根據本身的規則在合適的時機執行中間件中相應的方法。

在django項目的settings模塊中,有一個 MIDDLEWARE_CLASSES 變量,其中每個元素就是一箇中間件,以下圖。

與mange.py在同一目錄下的文件夾 wupeiqi/middleware下的auth.py文件中的Authentication類

中間件中能夠定義四個方法,分別是:

  • process_request(self,request)
  • process_view(self, request, callback, callback_args, callback_kwargs)
  • process_template_response(self,request,response)
  • process_exception(self, request, exception)
  • process_response(self, request, response)

以上方法的返回值能夠是None和HttpResonse對象,若是是None,則繼續按照django定義的規則向下執行,若是是HttpResonse對象,則直接將該對象返回給用戶。

自定義中間件

一、建立中間件類

1
2
3
4
5
6
7
8
9
10
11
12
class  RequestExeute( object ):
      
     def  process_request( self ,request):
         pass
     def  process_view( self , request, callback, callback_args, callback_kwargs):
         = 1
         pass
     def  process_exception( self , request, exception):
         pass
      
     def  process_response( self , request, response):
         return  response

二、註冊中間件

1
2
3
4
5
6
7
8
9
10
MIDDLEWARE_CLASSES  =  (
     'django.contrib.sessions.middleware.SessionMiddleware' ,
     'django.middleware.common.CommonMiddleware' ,
     'django.middleware.csrf.CsrfViewMiddleware' ,
     'django.contrib.auth.middleware.AuthenticationMiddleware' ,
     'django.contrib.auth.middleware.SessionAuthenticationMiddleware' ,
     'django.contrib.messages.middleware.MessageMiddleware' ,
     'django.middleware.clickjacking.XFrameOptionsMiddleware' ,
     'wupeiqi.middleware.auth.RequestExeute' ,
)

admin

django amdin是django提供的一個後臺管理頁面,改管理頁面提供完善的html和css,使得你在經過Model建立完數據庫表以後,就能夠對數據進行增刪改查,而使用django admin 則須要如下步驟:

  • 建立後臺管理員
  • 配置url
  • 註冊和配置django admin後臺管理頁面

一、建立後臺管理員

1
python manage.py createsuperuser

二、配置後臺管理url

1
url(r '^admin/' , include(admin.site.urls))

三、註冊和配置django admin 後臺管理頁面

a、在admin中執行以下配置

b、設置數據表名稱

c、打開表以後,設定默認顯示,須要在model中做以下配置

d、爲數據表添加搜索功能

e、添加快速過濾

更多:http://docs.30c.org/djangobook2/chapter06/

相關文章
相關標籤/搜索