本节对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=='':
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=='':
return redirect('http://www.baidu.com')
else:
return render(request,'login.html')