本節對Python Web框架學習
一、MTV
Model: 存放所有資料庫相關檔案
Template:模板檔案,存放html檔案
View: 業務處理,即函式檔案
二、MVC
model: 存放資料庫相關檔案
view: 存放所有的html檔案
controler: 存放所有的函式檔案
三、Django
Django基於MTV模式的web框架
1、下載安裝
https://www.djangoproject.com/download/
2、建立專案
django-admin startproject django_p01
./django_p01
/django_p01
__init__.py
settings.py
urls.py
wsgi.py
/manage.py
3、啟動專案
python manage.py runserver 127.0.0.1:8000 Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. December 18, 2017 - 22:42:56 Django version 1.8.17, using settings 'django_p01.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
4、訪問專案
瀏覽器輸入:127.0.0.1:8000顯示以下內容表示專案啟動成功
5、專案流程
django訪問流程如圖:
a.建立Django工程
django-admin startproject django_p01 ./django_p01 ##專案名稱 /django_p01 ##和專案同名二級目錄,用於整個程式配置 __init__.py ## settings.py ##程式配置檔案 urls.py ##URL對應關係配置檔案 wsgi.py ##Socket內部建立,遵循一定wsgi規則,線上UWSGI+Nginx /manage.py ##Django程式管理(python manage.py /python manage.py startapp xx/python manage.py migrate/python manage.py makemigrations) manage.py——>settings——>urls——>views
b.建立app
python manage.py startapp cmdb admin.py ##後臺管理介面 migrations ##記錄資料庫相關變更(DDL) models.py ##資料庫相關檔案內容,資料庫字典定義,ORM tests.py ##單元測試 views.py ##函式內容,實際操作業務邏輯程式碼 __init__.py apps.py ##配置當前app
新加app,需要在settings載入app名稱
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cmdb', )
c.靜態檔案路徑配置
配置檔案:settings.py STATICFILES_DIR=( os.path.join(BASE_DIR,'static'), )
d.模板路徑配置
配置檔案:settings.py TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR, 'templates')], }, ]
e.相關內容註釋
配置檔案:settings.py 註釋CSRF 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', 'django.middleware.security.SecurityMiddleware', )
f.定義路由規則
需要在urls.py中匯入相應應用模組(from cmdb import views),然後在urls.py中建立索引、函式對應關係
配置檔案:urls.py from cmdb import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^login/',views.login) ]
g.定義檢視函式
配置檔案:views.py from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import HttpResponse # Create your views here. def login(request): if request.method=='POST': user=request.POST['user'] password=request.POST['password'] if user=='tom' and password=='123456': return redirect('http://www.baidu.com') else: return render(request,'login.html') ##request.method有兩種獲取請求資料的方式:get/post request.GET.get('',None) ##獲取請求傳送來的資料 request.POST.get('',None) ##獲取請求傳送來的資料 ##返回請求資料的方式 return HttpResponse("字串") return render(request,"HTML模板路徑") return redirect("URL") ##本地URL需要加/URL名稱
h.模板渲染
函式內容: return render(request,'login.html',{'username':"tom",list=[1,2,3]}) 模板內容: {{變數名}} {{dict.k1}} {% for row in user_list%} xxx {% endfor %} {{% if true %}} xxx {{% else %}} xxx {{ endif }}
6、其他說明
a.settings.py內容說明
""" Django settings for django_p01 project. Generated by 'django-admin startproject' using Django 1.8.17. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os
##專案基目錄
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#(scd$4xhwyv35o37-ud)5+ctz_629-afv9u42==_n7f^+^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition APP列表 INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cmdb', ) 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', 'django.middleware.security.SecurityMiddleware', )
##URLS根目錄
ROOT_URLCONF = 'django_p01.urls'
##templates路徑
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, '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', ], }, }, ] WSGI_APPLICATION = 'django_p01.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases
##資料來源配置
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ ##靜態檔案路徑,js/css等 STATIC_URL = '/static/'
STATICFILES_DIR=(
os.path.join(BASE_DIR,'static'),
)
b.urls.py內容說明
主要配置函式、檢視對映關係
"""django_p01 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from cmdb import views ##需匯入專案函式檔名稱 urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^login/',views.login) ]
c.views.py內容說明
from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import HttpResponse # Create your views here. def login(request): if request.method=='POST': user=request.POST['user'] password=request.POST['password'] if user=='tom' and password=='123456': return redirect('http://www.baidu.com') else: return render(request,'login.html')