SlideShare a Scribd company logo
1 of 24
Python Web Framework 
ZaneboChen
Agenda 
2 
 Introduction 
 Model, View, Control(MVC) 
 Django Architecture(MTVC) 
 Project / Site creation 
 Settings 
 Project structure 
 Features 
 Why use it? 
 Future 
 Questions
Introduction 
3 
Django is a high-level Python Web framework that encourages rapid 
development and clean, pragmatic design.(快速,实用开发.) 
The Web framework for perfectionists with deadlines.(期限终结者) 
Django makes it easier to build better Web apps more quickly and 
with less code.(用少量地代码快速创建) 
 Encourages rapid development and clean, pragmatic design. 
 Named after famous Guitarist Django Reinhardt 
 Developed by Adrian Holovaty & Jacob Kaplan-moss 
 Created in 2003, open sourced in 2005 
 1.0 Version released in Sep 3 2008, now 1.7.1
Introduction 
Web Development Concept: 
1.用户向Web服务器请求一个文档. 
2.Web服务器随即获取或者生成这个文档. 
3.服务器再把这个结果返回给浏览器. 
4.浏览器将这个文档渲染出来. 
三个概念: 
通信: HTTP, URL, 请求, 响应. 
数据存储: SQL, NOSQL. 
表示: 将模板渲染成HTML或其他格式. 
4 
基本难题: 1.如何将一个请求路由到能够处理它的代码逻辑处? 
2.如何动态地将数据显示在HTML文件?
5 
Model, View, Control(MVC) 
Model(模型层): 
控制数据,与DB交互. 
View(表示层): 
定义显示的方法,用户可见. 
Control(控制层): 
在模型层与表示层之间斡旋,并且让用 
户以请求和操作数据.
6 
Django Architecture(MTVC) 
Models Describes your data 
Views Controls what users sees 
Templates How user sees it 
Controller URL dispatcher 
1.URL调度中心(urls.py)通过匹配相应的URL,将请求移交并调用 
相应的视图函数.若相应版本的缓存页存在则直接返回.django 
不仅提供页面级别的缓存功能,也提供更加细粒度的缓存. 
2.视图函数(views.py)一般会通过读写数据库,或者其他任务,响 
应请求. 
3.模型(models.py)定义了python中的数据结构及相关数据库交 
互操作.除了关系型数据库(Mysql, PostgreSQL,SQLite等)之外, 
其他的存储机制如XML,文本文件,LDAP等非关系型数据库也是支 
持的. 
4.执行完相应的操作后,视图函数一般会返回HTTP响应对象(数据 
一般通过模板输出)给浏览器.在返回之前,视图函数也可以选择 
把响应对象存储在缓存中. 
5.模板系统返回HTML页面.Django模板提供易于上手的语法,足以 
实现表示逻辑的所有需求.
7 
Django Architecture(MTVC) 
M 
Model 
V 
View 
C 
Controll 
er 
M 
Model 
T 
Templ 
ate 
V 
View 
C 
Contro 
ller 
Django 
Framework
8 
Django Architecture(MTVC)
9 
Django Middleware 
During the request phase : 
process_request(request) 
process_view(request, view_func, 
view_args, view_kargs) 
During the response phase: 
process_exception(request, exception) 
(only if the view raised an exception) 
process_template_response(request, 
response) 
(only for template responses) 
process_response(request, response)
10 
Installation 
Prerequisites 
 Python 
 PIP for installing Python packages (http://www.pip-installer.org/en/latest/installing.html) 
 pip install Django==1.6.5 
o OR https://www.djangoproject.com/download/ - python setup.py install 
 pip install mysql-python 
o MySQL on windows https://pypi.python.org/pypi/MySQL-python/1.2.4 
 Add Python and Django to env path 
o PYTHONPATH D:Python27 
o Path D:Python27; D:Python27Libsite-packages; D:Python27Libsite-packagesdjangobin; 
 Testing installation 
o shell> import django; django.VERSION;
11 
Project / Site Creation 
 Creating new Project 
 django-admin.py startproject demoproject 
A project is a collection of applications 
 Creating new Application 
 python manage.py startapp demosite 
An application tries to provide a single, relatively self-contained set of related functions 
 Using the built-in web server 
 python manage.py runserver 
 python manage.py runserver 80 
Runs by default at port 8000 
It checks for any error and validate the models. Throws errors/warnings for any misconfigurations and invalid 
entries.
12 
Project / Site Creation 
# urls.py 
from django.conf.urls import patterns, url 
import views 
urlpatterns = patterns('', 
url(r'^$', views.index), 
url(r'^test/P<id>(d+)/$', views.test), 
) 
# views.py 
from django.shortcuts import render 
from models import TestModel 
def index(request): 
return render(request, 'index.html', {‘text’: ‘hello world!’ }) 
def test(request, id): 
model = TestModel.objects.get_or_create(id=id) 
return render( 
request, 'test.html', {'model ': model} 
)
13 
Project / Site Creation 
# models.py 
from django.db import models 
import datetime 
Class TestModel(models.Mode): 
# admin.py 
from django.contrib import admin 
from models import TestModel 
admin.site.register(TestModel) 
username = models.CharField(max_length=20) 
create_time = models.DateTimeField(default=datetime.datetime.now)
14 
Project / Site Creation
15 
Settings 
 Project settings.py overrides from <python>/Lib/site-packgaes/django/conf/global_settings.py 
 Set DJANGO_SETTINGS_MODULE for your Project, tells django which settings to be used. (demoproject.settings) 
 export/set DJANGO_SETTINGS_MODULE=demoproject.settings 
 For server mod_wsgi: os.environ['DJANGO_SETTINGS_MODULE'] = 'demoproject.settings' 
 DEBUG True or False 
 DATABASES: {ENGINE, NAME) 'mysql', 'sqlite3' , 'oracle‘ or ‘mongodb’.. etc 
 ROOT_URLCONF 
 INSTALLED_APPS To any app you want to add into your project. Name, Lable must be unique. 
 MIDDLEWARE_CLASSES A tuple of middleware classes which process request, response, exceptions to use. 
 STATIC_ROOT To any server static files. (can add more dirs to STATICFILES_DIRS) STATICFILES_FINDERS. 
 STATIC_URL To serve static files. 
 TEMPLATE_DIRS Template directories 
Using settings in Python code 
from django.conf import settings 
if settings.DEBUG: 
# Do something
16 
Project Directory Structure 
demosite/ ---------------------------------- Just a container for your project. Its name doesn’t matter to Django; 
manage.py ------------------------- A command-line utility that lets you interact with this Django project in various ways. 
demosite/ ------------------------- Actual Python package for your project. Use this name to import anything inside it 
__init__.py ----------------- A file required for Python to treat the demosite directory as a package. 
settings.py ----------------- Settings/configuration for this Django project 
urls.py ---------------------- Root URL config, the URLs for this Django project, provides mapping to views 
wsgi.py ---------------------- An entry-point for WSGI-compatible webservers to serve your project 
demoapp/ ----------------- 
__init__.py -------- 
migrations/ -----as a version control of database schema. Packaging up your model change into individual migration files. 
urls.py ------------ URL Configuration of your app, include in Root URL. 
views.py ---------- Responsible for processing a user’s request and for returning the response 
conf.py --------- Separate Settings of your own app. Can override by project settings. By using django-appconf. 
models.py --------- A model is the single, definitive source of information about your data. 
admin.py ---------- It reads metadata in your model to provide a powerful and production-ready interface 
forms.py ----------- To create and manipulate form data 
static/demoapp/ --- Static file of your app. python manage.py collectstatic in production, copy all to STATIC_ROOT. 
templates/demoapp/ ----------- Templates file of your app. In project, loader.get_template(‘demoapp/index.html’) 
templates/ ----------------- HTML files , renders based on views. You can change to any dir, configurable in settings.py 
static/ ----------------------- CSS, JS, images.. etc, configurable in settings.py
17 
Features 
 Object Relational Mapper – ORM 
 MVC (MVTC) Architecture 
 Focuses on automating as much as possible and adhering to the DRY principle 
 Template System 
 Out of the box customizable Admin Interface, makes CRUD easy 
 Built-in light weight Web Server 
 Elegant URL design 
 Reverse resolution of URLS. 
 Custom Middleware 
 Authentication / Authorization 
 Internationalization, Time Zone support 
 Cache framework, with multiple cache mechanisms 
 Free, and Great Documentation
18 
Why use django? 
 Everything is Python Package 
 Django, Third Party Packages, Your Application, Your Site 
 monkey patch.(simply the dynamic replacement of attributes at runtime.) 
 Virtualenv虚拟环境搭建. 
 Pip 强大的库管理.setup.py,自由发布. 
 Batteries.(自带电池,各种第三方库.) 
 db, forms, templates, views, middleware, test 
 migrations, auth, admin, cache, sessions, gis. 
Bench: jinjia2, SQLALchemy, Rhetoric, django-xadmin, South. 
 文档齐全,活跃的社区. 
 https://www.djangopackages.com/ 
 https://www.djangoproject.com/ 
 http://www.django-rest-framework.org/ 
 https://djangosnippets.org/
19 
Why use django?
20 
Django admin for mongo 
django.forms(处理用户交互): 
1. 准备并处理需要被展示的数据. 
2. 为数据创建HTML的展示形式.(表单,<form>,css,js) 
3. 接收,处理并校验来自客户端的提交数据. 
django.forms.widgets: 
1. HTML元素在django中的表示, render直接返回html元素. 
2. 从相应的html元素中获取用户输入. 
区别与联系: 
Forms是对输入的验证逻辑,并且直接用于template中. 
Widgets负责渲染html元素和抽取用户原始输入. 
两者一般是结合使用,widgets需要在forms中被指定.
21 
Django admin for mongo
22 
Django admin for mongo 
权限管理: 
添加,修改,浏览,删除. 四种权限.支持分组管理 
1.利用Django自带的admin后台权 
限管理系统. 
2.每个Mongo Collection对应关系 
型数据库中的一个空表.(仅有表名) 
3.对sql表进行权限管理.
23 
About Future
24 
Questions 
Q: 
Have you considered using Django and found good reasons not to do so? 
A: 
Yeah, I am an honest guy, and the client wanted to charge by the hour. 
There was no way Django was going to allow me to make enough money.

More Related Content

What's hot

Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
 

What's hot (20)

Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Django, What is it, Why is it cool?
Django, What is it, Why is it cool?Django, What is it, Why is it cool?
Django, What is it, Why is it cool?
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
 
Django
DjangoDjango
Django
 
JSON, JSON Schema, and OpenAPI
JSON, JSON Schema, and OpenAPIJSON, JSON Schema, and OpenAPI
JSON, JSON Schema, and OpenAPI
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Spring boot
Spring bootSpring boot
Spring boot
 

Similar to Django Architecture Introduction

eXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework IntroductioneXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework Introduction
vstorm83
 

Similar to Django Architecture Introduction (20)

بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
Django framework
Django framework Django framework
Django framework
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
 
Django
DjangoDjango
Django
 
Django rest framework
Django rest frameworkDjango rest framework
Django rest framework
 
Web Development in Django
Web Development in DjangoWeb Development in Django
Web Development in Django
 
Heroku pycon
Heroku pyconHeroku pycon
Heroku pycon
 
React django
React djangoReact django
React django
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
 
Continuous Delivery w projekcie Open Source - Marcin Stachniuk - DevCrowd 2017
Continuous Delivery w projekcie Open Source - Marcin Stachniuk - DevCrowd 2017Continuous Delivery w projekcie Open Source - Marcin Stachniuk - DevCrowd 2017
Continuous Delivery w projekcie Open Source - Marcin Stachniuk - DevCrowd 2017
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
 
Django web framework
Django web frameworkDjango web framework
Django web framework
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
 
Continuous delivery w projekcie open source - Marcin Stachniuk
Continuous delivery w projekcie open source - Marcin StachniukContinuous delivery w projekcie open source - Marcin Stachniuk
Continuous delivery w projekcie open source - Marcin Stachniuk
 
Django deployment with PaaS
Django deployment with PaaSDjango deployment with PaaS
Django deployment with PaaS
 
eXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework IntroductioneXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework Introduction
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
 

Recently uploaded

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 

Django Architecture Introduction

  • 1. Python Web Framework ZaneboChen
  • 2. Agenda 2  Introduction  Model, View, Control(MVC)  Django Architecture(MTVC)  Project / Site creation  Settings  Project structure  Features  Why use it?  Future  Questions
  • 3. Introduction 3 Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.(快速,实用开发.) The Web framework for perfectionists with deadlines.(期限终结者) Django makes it easier to build better Web apps more quickly and with less code.(用少量地代码快速创建)  Encourages rapid development and clean, pragmatic design.  Named after famous Guitarist Django Reinhardt  Developed by Adrian Holovaty & Jacob Kaplan-moss  Created in 2003, open sourced in 2005  1.0 Version released in Sep 3 2008, now 1.7.1
  • 4. Introduction Web Development Concept: 1.用户向Web服务器请求一个文档. 2.Web服务器随即获取或者生成这个文档. 3.服务器再把这个结果返回给浏览器. 4.浏览器将这个文档渲染出来. 三个概念: 通信: HTTP, URL, 请求, 响应. 数据存储: SQL, NOSQL. 表示: 将模板渲染成HTML或其他格式. 4 基本难题: 1.如何将一个请求路由到能够处理它的代码逻辑处? 2.如何动态地将数据显示在HTML文件?
  • 5. 5 Model, View, Control(MVC) Model(模型层): 控制数据,与DB交互. View(表示层): 定义显示的方法,用户可见. Control(控制层): 在模型层与表示层之间斡旋,并且让用 户以请求和操作数据.
  • 6. 6 Django Architecture(MTVC) Models Describes your data Views Controls what users sees Templates How user sees it Controller URL dispatcher 1.URL调度中心(urls.py)通过匹配相应的URL,将请求移交并调用 相应的视图函数.若相应版本的缓存页存在则直接返回.django 不仅提供页面级别的缓存功能,也提供更加细粒度的缓存. 2.视图函数(views.py)一般会通过读写数据库,或者其他任务,响 应请求. 3.模型(models.py)定义了python中的数据结构及相关数据库交 互操作.除了关系型数据库(Mysql, PostgreSQL,SQLite等)之外, 其他的存储机制如XML,文本文件,LDAP等非关系型数据库也是支 持的. 4.执行完相应的操作后,视图函数一般会返回HTTP响应对象(数据 一般通过模板输出)给浏览器.在返回之前,视图函数也可以选择 把响应对象存储在缓存中. 5.模板系统返回HTML页面.Django模板提供易于上手的语法,足以 实现表示逻辑的所有需求.
  • 7. 7 Django Architecture(MTVC) M Model V View C Controll er M Model T Templ ate V View C Contro ller Django Framework
  • 9. 9 Django Middleware During the request phase : process_request(request) process_view(request, view_func, view_args, view_kargs) During the response phase: process_exception(request, exception) (only if the view raised an exception) process_template_response(request, response) (only for template responses) process_response(request, response)
  • 10. 10 Installation Prerequisites  Python  PIP for installing Python packages (http://www.pip-installer.org/en/latest/installing.html)  pip install Django==1.6.5 o OR https://www.djangoproject.com/download/ - python setup.py install  pip install mysql-python o MySQL on windows https://pypi.python.org/pypi/MySQL-python/1.2.4  Add Python and Django to env path o PYTHONPATH D:Python27 o Path D:Python27; D:Python27Libsite-packages; D:Python27Libsite-packagesdjangobin;  Testing installation o shell> import django; django.VERSION;
  • 11. 11 Project / Site Creation  Creating new Project  django-admin.py startproject demoproject A project is a collection of applications  Creating new Application  python manage.py startapp demosite An application tries to provide a single, relatively self-contained set of related functions  Using the built-in web server  python manage.py runserver  python manage.py runserver 80 Runs by default at port 8000 It checks for any error and validate the models. Throws errors/warnings for any misconfigurations and invalid entries.
  • 12. 12 Project / Site Creation # urls.py from django.conf.urls import patterns, url import views urlpatterns = patterns('', url(r'^$', views.index), url(r'^test/P<id>(d+)/$', views.test), ) # views.py from django.shortcuts import render from models import TestModel def index(request): return render(request, 'index.html', {‘text’: ‘hello world!’ }) def test(request, id): model = TestModel.objects.get_or_create(id=id) return render( request, 'test.html', {'model ': model} )
  • 13. 13 Project / Site Creation # models.py from django.db import models import datetime Class TestModel(models.Mode): # admin.py from django.contrib import admin from models import TestModel admin.site.register(TestModel) username = models.CharField(max_length=20) create_time = models.DateTimeField(default=datetime.datetime.now)
  • 14. 14 Project / Site Creation
  • 15. 15 Settings  Project settings.py overrides from <python>/Lib/site-packgaes/django/conf/global_settings.py  Set DJANGO_SETTINGS_MODULE for your Project, tells django which settings to be used. (demoproject.settings)  export/set DJANGO_SETTINGS_MODULE=demoproject.settings  For server mod_wsgi: os.environ['DJANGO_SETTINGS_MODULE'] = 'demoproject.settings'  DEBUG True or False  DATABASES: {ENGINE, NAME) 'mysql', 'sqlite3' , 'oracle‘ or ‘mongodb’.. etc  ROOT_URLCONF  INSTALLED_APPS To any app you want to add into your project. Name, Lable must be unique.  MIDDLEWARE_CLASSES A tuple of middleware classes which process request, response, exceptions to use.  STATIC_ROOT To any server static files. (can add more dirs to STATICFILES_DIRS) STATICFILES_FINDERS.  STATIC_URL To serve static files.  TEMPLATE_DIRS Template directories Using settings in Python code from django.conf import settings if settings.DEBUG: # Do something
  • 16. 16 Project Directory Structure demosite/ ---------------------------------- Just a container for your project. Its name doesn’t matter to Django; manage.py ------------------------- A command-line utility that lets you interact with this Django project in various ways. demosite/ ------------------------- Actual Python package for your project. Use this name to import anything inside it __init__.py ----------------- A file required for Python to treat the demosite directory as a package. settings.py ----------------- Settings/configuration for this Django project urls.py ---------------------- Root URL config, the URLs for this Django project, provides mapping to views wsgi.py ---------------------- An entry-point for WSGI-compatible webservers to serve your project demoapp/ ----------------- __init__.py -------- migrations/ -----as a version control of database schema. Packaging up your model change into individual migration files. urls.py ------------ URL Configuration of your app, include in Root URL. views.py ---------- Responsible for processing a user’s request and for returning the response conf.py --------- Separate Settings of your own app. Can override by project settings. By using django-appconf. models.py --------- A model is the single, definitive source of information about your data. admin.py ---------- It reads metadata in your model to provide a powerful and production-ready interface forms.py ----------- To create and manipulate form data static/demoapp/ --- Static file of your app. python manage.py collectstatic in production, copy all to STATIC_ROOT. templates/demoapp/ ----------- Templates file of your app. In project, loader.get_template(‘demoapp/index.html’) templates/ ----------------- HTML files , renders based on views. You can change to any dir, configurable in settings.py static/ ----------------------- CSS, JS, images.. etc, configurable in settings.py
  • 17. 17 Features  Object Relational Mapper – ORM  MVC (MVTC) Architecture  Focuses on automating as much as possible and adhering to the DRY principle  Template System  Out of the box customizable Admin Interface, makes CRUD easy  Built-in light weight Web Server  Elegant URL design  Reverse resolution of URLS.  Custom Middleware  Authentication / Authorization  Internationalization, Time Zone support  Cache framework, with multiple cache mechanisms  Free, and Great Documentation
  • 18. 18 Why use django?  Everything is Python Package  Django, Third Party Packages, Your Application, Your Site  monkey patch.(simply the dynamic replacement of attributes at runtime.)  Virtualenv虚拟环境搭建.  Pip 强大的库管理.setup.py,自由发布.  Batteries.(自带电池,各种第三方库.)  db, forms, templates, views, middleware, test  migrations, auth, admin, cache, sessions, gis. Bench: jinjia2, SQLALchemy, Rhetoric, django-xadmin, South.  文档齐全,活跃的社区.  https://www.djangopackages.com/  https://www.djangoproject.com/  http://www.django-rest-framework.org/  https://djangosnippets.org/
  • 19. 19 Why use django?
  • 20. 20 Django admin for mongo django.forms(处理用户交互): 1. 准备并处理需要被展示的数据. 2. 为数据创建HTML的展示形式.(表单,<form>,css,js) 3. 接收,处理并校验来自客户端的提交数据. django.forms.widgets: 1. HTML元素在django中的表示, render直接返回html元素. 2. 从相应的html元素中获取用户输入. 区别与联系: Forms是对输入的验证逻辑,并且直接用于template中. Widgets负责渲染html元素和抽取用户原始输入. 两者一般是结合使用,widgets需要在forms中被指定.
  • 21. 21 Django admin for mongo
  • 22. 22 Django admin for mongo 权限管理: 添加,修改,浏览,删除. 四种权限.支持分组管理 1.利用Django自带的admin后台权 限管理系统. 2.每个Mongo Collection对应关系 型数据库中的一个空表.(仅有表名) 3.对sql表进行权限管理.
  • 24. 24 Questions Q: Have you considered using Django and found good reasons not to do so? A: Yeah, I am an honest guy, and the client wanted to charge by the hour. There was no way Django was going to allow me to make enough money.

Editor's Notes

  1. HTTP(超文本传输协议)封装了Web页面服务的整个过程,是Web的基石.由两部分组成,请求和响应. 请求封装了第一部分,核心是URL(指向所需文档路径,同样对于服务器而言就是路由) 响应由一个正文和相应的包头(header)组成. 静态请求与动态请求, Web大部分的动态特性都是通过将数据保存在数据库中实现的. 大部分Web框架都提供了模板语言(template language, 例如Django内置模板, jinjia)来处理要显示的数据, 它混合了原始的HTML标签以及一些类似编程的语法来循环对象集合,执行逻辑操作和一些动态所需的结构。
  2. 模型层与MVC中的M相一致,然后Django里的视图却并不是显示数据的最后一步---Django中的视图其实更加接近于MVC传统意义上的控制器. 它们是用来将模型层与表示层连接在一起的python函数.按照Django团队的话来说:视图描述的是你能看到哪些数据,而不是怎么看到它. 换一种说法,Django把表示层一分为二,视图方法定义了显示模型里的什么数据,而模板则定义了最终的现实方式.而框架自身则担当起控制器的角色, 它提供决定什么视图和什么模板一起响应给定请求的机制. 视图(View)组成了django应用程序大部分甚至全部的逻辑.它们是链接到一个或多个定义URL上的python函数,这些函数都返回一个HTTP响应对象. 在Django的HTTP机制之间要执行什么操作完全在你的掌控之中。 当一个视图要返回HTML文档时,它通常会制定一个模板,提供它所要显示的信息,并在响应里使用模板渲染结果.返回格式不仅仅是HTML。
  3. 模型层与MVC中的M相一致,然后Django里的视图却并不是显示数据的最后一步---Django中的视图其实更加接近于MVC传统意义上的控制器. 它们是用来将模型层与表示层连接在一起的python函数.按照Django团队的话来说:视图描述的是你能看到哪些数据,而不是怎么看到它. 换一种说法,Django把表示层一分为二,视图方法定义了显示模型里的什么数据,而模板则定义了最终的现实方式.而框架自身则担当起控制器的角色, 它提供决定什么视图和什么模板一起响应给定请求的机制. 视图(View)组成了django应用程序大部分甚至全部的逻辑.它们是链接到一个或多个定义URL上的python函数,这些函数都返回一个HTTP响应对象. 在Django的HTTP机制之间要执行什么操作完全在你的掌控之中。 当一个视图要返回HTML文档时,它通常会制定一个模板,提供它所要显示的信息,并在响应里使用模板渲染结果.返回格式不仅仅是HTML。
  4. 利用Django中间件,我们可以做许多自定义的操作.例如Session控制,用户登陆验证,安全措施防范,特定异常处理等等.