8、Django 开发与进阶
1、Django开发-基础篇
1-1 Django 概述
优点:
自主管理后台
自带ORM
Django的错误提示
安装:
Win:pip install django==1.7.5
Lin: sudo pip install django
升级:
pipinstall -U django
配置环境变量:
在Win中,C:\Python27\Lib\site-packages\django\bin
>django-adminstartproject myProject // 创建项目名
>cd myProject
>django-admin startapp myApp // 创建应用
在myProject目录中settings.py添加应用'myApp':
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myApp',
)
启动:
>python manage.pyrunserver
localhost:8000
>python manage.py runserver 0.0.0.0:8000
192.168.245.132:8000
0.0.0.0让其它电脑可连接到开发服务器,8000为端口号。如果不说明,那么端口号默认为8000
1-2视图开发及URL配置
Django可识别的视图需要满足两个条件:
1)第一个参数的类型:HttpRequest
2)返回HttpRespnse实例
视图函数开发实例演示:
代码:
from django.http import HttpResponse
# Create your views here.
def hello(request):
returnHttpResponse("hello world")
从输入url地址到产生页面内容的流程:
在浏览器地址中输入url地址
访问settings.py中 ROOT_URLCONF= 'myProject.urls'
查找匹配urls.py中的路径,(r'^hello/$',hello)
在views.py中找到视图函数,返回一个HttpRespnse对象
转为合适的形式,在网页中展示
在url中的动态配置– 正则
在settings.py中设置出错页面:
#SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
1-3 Django 模板语法及使用
模板– 文本,用于分离文档的表现形式和内容,通常用于生产HTML
使用:
可以模板代码字符串创建一个Template对象
调用模板对象的render方法,并且传入一套变量context
代码:
C:\Users\Administrator\work\PythonSpace\Django\myProject>pythonmanage.py shell
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or"license" for more information.
(InteractiveConsole)
>>> from django import template
>>> t = template.Template('hello{{name}}')
>>> c = template.Context({'name':'django'})
>>> print t.render(c)
hello django
>>>
在settings.py中添加如下代码– 告诉项目你要使用'templates'
import os
TEMPLATE_DIRS = os.path.join(os.path.dirname(__file__), 'templates')
验证:
>>> from django.template.loader import get_template
>>> t = get_template('2.html')
>>> t
>>>
方法二:一个简单的方法
直接在views.py中,添加
from django.shortcuts importrender_to_response
def views(request):
returnrender_to_response('2.html',{"name":"hello"})
模板继承
//2.html
<
{% block content %}
Hello World
{% endblock %}
//3.html
{% extends 2.html %}
{% block content %}
{% endblock %}
模板语法:
<
Hello {{name}}
{%for item in itemList%}
{% endfor %}
{% if status %}
I like python
{% else %}
I like django
{% endif %}
{% ifequal a b %}
{% endifequal%}
{{ name | upper }} //过滤器,管道字符
{{ name | lower }}
1-4 模型开发与数据库交互
在myProject -> settings.py中,配置数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'USER': 'root',
'PASSWORD': 'root',
'NAME': djangodb,
'HOST': 'localhost',
}
}
实现一个数据模型
代码:
#models.py
from django.db import models
# Create your models here.
class Mysite(models.Model):
tile= models.CharField(max_length=100)
url= models.URLField()
author= models.CharField(max_length=100)
num= models.IntegerField(max_length=10)
在工程目录下,
>python manage.py validate //验证
>python manage.py sqlall myAPP //所执行的SQL语句
>python manage.py syncdb //同步数据库
数据处理:
1)基本数据访问
2)插入和更新数据
3)数据过滤
4)数据排序
5)更新多个对象,删除对象
C:\Users\Administrator\work\PythonSpace\Django\myProject>pythonmanage.py shell
Python 2.7.11 (v2.7.11:6d1b6a68f775,Dec 5 2015, 20:32:19) [MSC v.1500 32 bit(
Intel)] on win32
Type "help","copyright", "credits" or "license" for moreinformation.
(InteractiveConsole)
>>> from myApp.models import *
>>> m =Mysite.objects.all()
>>> m
[]
//插入
>>> m =Mysite(title='django',num=2)
>>> m.save()
//查询
>>> m = Mysite.objects.all()
>>> m
[
>>> m[0].title
u'django'
>>>
//数据过滤
>>> m=Mysite.objects.get(num=2)
>>> m
>>> m.title
u'django'
>>>
//排序
>>> m =Mysite(title='django',num=1)
>>> m.save()
>>> m = Mysite(title='django',num=3)
>>> m.save()
>>> m =Mysite(title='django',num=9)
>>> m.save()
>>> m = Mysite.objects.all()
>>> m
[ ite: Mysite object>] >>> >>> m[0].num 2L >>> m = Mysite.objects.all().order_by("num") >>> m [ ite: Mysite object>] >>> m[0].title u'django' >>> m[0].num 1L >>> //降序 >>> m =Mysite.objects.all().order_by("-num") >>> m[0].num 9L >>> //更新 >>> m = Mysite.objects.get(num=2) >>> m >>> m.title = 'python' >>> m.save() >>> m = Mysite.objects.get(num=2) >>> m.title u'python' >>> //删除 >>> m.delete() >>> m = Mysite.objects.get(num=2) Traceback (most recent call last): File " File"C:\Python27\lib\site-packages\django\db\models\manager.py", line 92,in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File"C:\Python27\lib\site-packages\django\db\models\query.py", line 357,in g et self.model._meta.object_name) DoesNotExist: Mysite matching query doesnot exist. >>> //查询结果的条件限制 >>> m=Mysite.objects.all() >>> m [ >>> m=Mysite.objects.all()[0:2] >>> m [ >>> 1-5 Django 的后台管理及表单类介绍 Django 的自动管理界面 通过读取你模式中的元数据,提供一个强大而且可以使用的界面。 1)在后台管理中添加用户 2)修改用户权限 3)管理模型数据 代码: // admin.py from django.contrib import admin from myApp.models import * # Register your models here. admin.site.register(Mysite) //models.py def__unicode__(self): returnself.title 4)使用django自有的表单类 //forms.py from django import forms class Mybook(forms.Form): name= forms.CharField() author= forms.CharField() date= forms.CharField() //views.py from myApp.forms import * from django.http import HttpResponse from django.shortcuts importrender_to_response def book(request): ifrequest.method == 'POST': form= Mybook(request.POST) ifform.is_valid(): data= form.cleaned_data name= data["name"] returnHttpResponse(name) form= Mybook() returnrender_to_response('book.html',{'form':form}) //urls.py from django.conf.urls import patterns,include, url from django.contrib import admin from myApp.views import * urlpatterns = patterns('', #Examples: #url(r'^$', 'myProject.views.home', name='home'), #url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), (r'^book/$',book) ) //book.html <
{{form.as_p }}
2、Django开发 - 进阶篇
2-1 高级视图及URL配置
1)URL简写
导入视图函数的方法
# urls.py
# frommyApp.views import * //传统的导入视图函数方法
urlpatterns = patterns('myApp.views', //随着后期视图函数的增多,使用新的导入方法,便于后期URL的管理
(r'^hello/$',hello),
)
+= //使url配置变得结构化
# hello
urlpatterns += patterns('',
(r'^hello/$',hello),
(r'hello/(\d+)/$',hello1),
)
# book
urlpatterns += patterns('',
(r'^book/$',book),
)
2)URL命名组 – 为url配置添加一个相关的名字,让这个路径显得更加直观
urlpatterns += patterns('',
(r'^book/(?P
)
请求时:
hello(request,year=2016,month=3)
3)高级视图
法一:
//views.py
#def view1(request):
# returnrender_to_response('1.html')
#def view2(request):
# returnrender_to_response('2.html')
def views(request,template_name):
returnrender_to_response(template_name)
//urls.py
urlpatterns += patterns('',
# (r'^view1/$',view1),
# (r'^view2/$',view2),
(r'^view1/$',views,{'template_name':1.html}),
(r'^view2/$',views,{'template_name':2.html}),
)
法二:利用Python中嵌套函数
提取公共部分,而不影响每个视图函数的各自的逻辑
//views.py
def view1(request):
returnrender_to_response('1.html')
def view2(request):
returnrender_to_response('2.html')
def views(func):
defview(request):
#do something
returnfunc(request)
returnview
//urls.py
urlpatterns += patterns('',
(r'^view1/$',views(view1)),
(r'^view2/$',views(view2)),
)
2-2 高级模型
1)外键的获取 - forignkey
2)多对多的获取 – many-to-many
3)自定义Manager – 对经常使用的查询结果进行封装
4)自定义QuerySet - 对经常使用的查询对象进行封装
2-3 高级模板
创建模板库的步骤:
1. 决定模板库的位置,将它作为app来使用
2. 创建templatetags目录
3. 创建__init__.py和extras.py文件
__init__.py是来告诉python程序这里面装的是Python代码
extras.py是来写模板库代码
1)过滤器的实现
from django import template
register = template.Library()
@register.filter(name="cut")
def myCut(value,arg):
returnvalue.replace(arg,"!")
2)自定义标签
标签内容:
{{current_time %Y-%m-%d %H:%M:%S }}
2-4 通用视图
1)对静态页面 - 减少了代码量,不必写视图函数
# urls.py
from django.views.generic import TemplateView //简单的静态页面的路径
urlpatterns += patterns('',
(r'^about/$',TemplateView.as_view(template_name='hello.html')),
)
2)对渲染页面 – 将数据库的简单数据渲染到模板上
# urls.py
from django.views.generic.list importListView
from myApp.models import *
book_info = {
'queryset':Mysite.objects.all,
'template_name':'hello.html'
}
urlpatterns += patterns('',
(r'^about/$',ListView.as_view(**book_info)),
)
3)处理数据过滤 – 写一个自己的类
2-5 缓存系统
1)内存缓存
# settings.py
CACHE_BACKEND = 'memcache://127.0.0.1:12111/'
2)数据库缓存
>python manage.py createcachetablemycache
# settings.py
CACHE_BACKEND = 'db://mycache'
3)文件缓存
# settings.py
CACHE_BACKEND = 'file:///usr/local/tmp'
4)缓存系统应用
>ab –n 1000 http://localhost:8000/hello # 测试访问1000个连接需要多长时间
# 2-5-1 django自带的小缓存
from django.core.cache import cache
def view(request):
ifcache.get('book'):
b=cache.get('book')
else:
b=Book.objects.all()
cache.set('book',b)
returnrender_to_response('1.html',{'book':b})
# 可以缓存整个视图的方法
from django.decorators.cache importcache_page
@cache_page(60*15) #配置过期的时间
def view(request):
b=Book.objects.all()
returnrender_to_response('1.html',{'book':b})
2-6 中间件
常见的中间件
MIDDLEWARE_CLASSES = (
'myApp.myMiddleware.MyMiddleware', #自定义中间件
'django.contrib.sessions.middleware.SessionMiddleware',#用来支持django中会话操作,只有打开了这个中间件才能在项目中使用会话
'django.middleware.common.CommonMiddleware',#可以很方便的使用一些功能
#'django.middleware.csrf.CsrfViewMiddleware', #防止Csrf的攻击
'django.contrib.auth.middleware.AuthenticationMiddleware', #认证浏览器的User登录一些信息
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware', #用来压缩浏览器返回的内容,减少服务器使用的带宽
#'django.middleware.http.SetRemoteAddrFromForwardedFor', # 处理反向代理,若要获得反向代理的IP值,就需要这个中间件去获得
解析中间件:
1.__init__ #初始化的操作
2.process_request #视图函数请求之前的操作
3.process_view #视图函数接受了request请求之后
4.process_response #处理完view逻辑后的response
5.process_exception #处理异常的
自定义中间件实例演示
# myMiddleware.py
class MyMiddleware(object):
def__init__(self):
print'Hello, this is my middleware!'
defprocess_view(self,request,func, args,kwargs):
printfunc
3、Django开发 - API 设计
3-1 Rest-Framework概述
restful简介
一种软件架构风格,设计风格而不是标准,只是提供了一种设计原则和约束条件
>pip install djangorestframework
Add 'rest_framework' toyour INSTALLED_APPS setting.
INSTALLED_APPS = (
...
'rest_framework',
)
3-2 序列化——第一个API,返回JSON数据
//models.py
class Book(models.Model):
name= models.CharField(max_length=100)
title= models.CharField(max_length=100)
author= models.CharField(max_length=100)
// serializers.py
from myApp.models import Book
from rest_framework import serializers
classBookSerializer(serializers.Serializer):
classMeta:
model= Book
field= ('name','title','author')
#name = serializers.CharField(max_length=100)
#title = serializers.CharField(max_length=100)
#author = serializers.CharField(max_length=100)
defrestore_object(self,attrs,instance=None):
ifinstance:
instance.title= attrs['title']
instance.name= attrs['name']
instance.author= attrs['author']
returninstance
returnBook(**attrs)
在python shell中进行实验:
C:\Users\Administrator\work\PythonSpace\Django\myProject>pythonmanage.py syncdb
C:\Users\Administrator\work\PythonSpace\Django\myProject>pythonmanage.py shell
Python 2.7.11 (v2.7.11:6d1b6a68f775,Dec 5 2015, 20:32:19) [MSC v.1500 32 bit(
Intel)] on win32
Type "help","copyright", "credits" or "license" for moreinformation.
(InteractiveConsole)
>>> from myApp.models import Book
>>> b = Book(name='django1',title=’DJ1’,author=’yx’)
>>> b.save()
>>> from myApp.serializers import*
>>> from rest_framework.renderersimport JSONRenderer
>>> from rest_framework.parsersimport JSONParser
>>> b = Book.objects.get(id=1)
>>> book = BookSerializer(b)
>>> book.data
{'author': u'yx', 'name': u'django1','title': u'DJ1'}
>>> c =JSONRenderer().render(book.data)
>>> c
'{"name":" django1","title":"DJ1","author":" yx"}'
>>>
//views.py
from django.http importStreamingHttpResponse
from rest_framework.renderers importJSONRenderer
from myApp.models import Book
from myApp.serializers importBookSerializer
class JSONResponse(StreamingHttpResponse):
def__init__(self,data,**kwargs):
content= JSONRenderer().render(data)
kwargs['content_type']= 'application/json'
super(JSONResponse,self).__init__(content,**kwargs)
def book_list(request,num):
ifrequest.method == 'GET':
b= Book.objects.get(id=num)
ser= BookSerializer(b)
returnJSONResponse(ser.data)
3-3 基于类的视图
1)将视图函数改写为基于类的视图
//views.py
from rest_framework import APIView
from rest_framework import Response
class BookList(APIView):
defget(self,request,format=None):
books= Book.objects.all()
ser= BookSerializer(books,many=True)
returnResponse(ser.data)
defpost(self,request,format=None):
ser= BookSerializer(request.DATA)
ifser.is_valid():
ser.save()
returnResponse(ser.data)
returnResponse(ser.errors)
class BookDetail(APIView):
defget(self,request,num,format=None):
books= Book.objects.all(id=num)
ser= BookSerializer(b)
returnResponse(ser.data)
//urls.py
urlpatterns += patterns('',
(r'^book/$',BookList.as_view()),
(r'^book/(\d+)',BookDetail.as_view()),
)
好处:将get和post分离,利于后期的拓展和维护
2)通用视图
from rest_framework import generics
class BookList(APIView):
queryset=Book.objects.all()
serializer_class=BookSerializer
3-4 API权限管理和设置