Django Architecture Introduction

24
ZaneboChen Python Web Framework

Transcript of Django Architecture Introduction

ZaneboChen

Python Web Framework

Agenda

2

Introduction

Model, View, Control(MVC)

Django Architecture(MTVC)

Project / Site creation

Settings

Project structure

Features

Why use it?

Future

Questions

3

IntroductionDjango 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或其他格式.

基本难题: 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)

MModel

VView

CController

MModel

TTemplate

VView

CController

DjangoFramework

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:\Python27\Lib\site-packages; D:\Python27\Lib\site-packages\django\bin;

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):

username = models.CharField(max_length=20)

create_time = models.DateTimeField(default=datetime.datetime.now)

# admin.py

from django.contrib import admin

from models import TestModel

admin.site.register(TestModel)

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 Structuredemosite/ ---------------------------------- 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.