django是基于python的一个框架,因此在此之前要先安装python环境,关于python环境的搭建,前面已写过,参考这里:http://www.the5fire.net/python-env.html。有了python环境接着就要开始安装django了。
在正式开始之前要先介绍一下django的开发环境包括哪些东西:
- 1、django的安装
- 2、mysql安装【非必须,本篇会提及】
- 3、apache安装【非必须】
另外主要是为了和大家一起使用django来作为todos的服务器端,因此还简单的介绍下如何使用django来开发。
正式开始,安装django可谓相当简单,到这:http://www.djangoproject.com/download/1.3.1/tarball/ 我自己用的django版本是1.3.1的,大家可以自行选择。
下载下来之后,通过命令行进入Django-1.3.1目录中,执行:python setup.py install即可(对于ubuntu用户可能需要加sudo)。在命令行中输入django-admin看有木有提示,如果没有你需要到你对应的C:/python2.7/Scripts中看看有没有一个django-admin.py文件,如果有, 你需要把这个目录放到系统环境变量中。
再来看mysql的安装,【对于todos这个项目不会用到mysql】
对于windows用户安装相对简单些,先现在mysql数据库安装包,然后下载对应的MySQL-python-1.2.3.win32-py2.7安装文件,先安装mysql,然后安装对应的mysql-python文件。
对于ubuntu用户需要以下操作:
1、安装mysql
sudo apt-get install mysql-server
sudo apt-get install libmysqld-dev
sudo apt-get instlal libmysqlclient-dev
sudo apt-get install libmysqld-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install libmysqlclient-dev
2、配置mysql和python
sudo apt-get install python-mysqldb
也可以参考我以前的一篇文章:http://www.the5fire.net/python-opt-mysql.html
至此,环境的搭建就完成了,简单的运用一下。
首先随便找一个地方创建一个应用,命令:django-admin.py startproject todos,然后你会发现已经有了一个todos文件夹,在你执行命令的文件中。这就是一个todos工程了, 切换到todos中,执行python manage.py runserver,命令行会输出django版本,以及服务器url。你在浏览器中访问就看到了。
我们对backbone的功能进行了分析,建立了web端的model。在本节中我们将对原先的todos进行扩展,使其能够将数据存到server端的数据库中。这里我们使用的是django+sqlite来进行实现。
现在我们应该对应着建立server端的model。不过在此之前,为了方便不熟悉django的童鞋,简单的写下开发过程:
1、创建工程
根据上一篇中介绍的django的环境安装和使用,创建一个工程:django-admin.py startproject todos,然后在cd到todos文件夹中:python manage.py startapp todo,创建一个应用(称作模块也行)。
2、配置文件
在todos根目录的settings中,主要是数据配置:
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.sqlite3′, # Add ‘postgresql_psycopg2′, ‘postgresql’, ‘mysql’, ‘sqlite3′ or ‘oracle’.
‘NAME’: ‘D:/mytodos’, # Or path to database file if using sqlite3.
‘USER’: ”, # Not used with sqlite3.
‘PASSWORD’: ”, # Not used with sqlite3.
‘HOST’: ”, # Set to empty string for localhost. Not used with sqlite3.
‘PORT’: ”, # Set to empty string for default. Not used with sqlite3.
}
}
完整的配置最后贴出来供大家参考。
有了上面的一个铺垫,开始创建model。
打开todo文件夹中的models.py文件,写入以下代码:
- from django.db import models
- class Todo(models.Model):
- content = models.CharField(max_length=128)
- done = models.CharField(max_length=1,default='N') #Y表示完成N表示未完成
- order = models.IntegerField(blank=True)
from django.db import models
class Todo(models.Model):
content = models.CharField(max_length=128)
done = models.CharField(max_length=1,default='N') #Y表示完成N表示未完成
order = models.IntegerField(blank=True)
然后再来创建views代码,关于django的mvc模式这里不介绍,大家跟着操作进行。在todo下新建一个views_todos.py文件。
这个views_todos文件是用来操作数据库的所有代码所在。关于数据库的操作,其实就是CRUD(create增加,request查询,update更新,delete删除),在django的基础上,很好写。
这里是全部代码:
- #coding=utf-8
- '''''
- author:huyang
- date: 2012-3-26
- blog:http://the5fire.net
- '''
- from models import Todo
- from django.http import HttpResponse
- from django.shortcuts import render_to_response
- from django.utils import simplejson
- '''''
- public
- @desc 加载todo首页
- @param
- @return templates
- '''
- def index(request):
- return render_to_response('todo/todos.html',{})
- '''''
- public
- @desc 控制创建和读取方法的一个跳转
- @param
- @return
- '''
- def control_cr(request):
- if request.method == 'POST':
- return create(request)
- elif request.method == 'GET':
- return getAll(request)
- else:
- return HttpResponse('
- access deny
- ')
- '''''
- public
- @desc 控制更新和删除方法的一个跳转
- @param url中的todo对象id
- @return
- '''
- def control_ud(request, todo_id):
- if request.method == 'PUT':
- return update(request,todo_id)
- elif request.method == 'DELETE':
- return delete(request,todo_id)
- else:
- return HttpResponse('
- access deny
- ')
- '''''
- protect
- @desc 获取所有的todo对象,并转为json格式,返回
- @param
- @return json格式的todo列表
- '''
- def getAll(request):
- todos = Todo.objects.all()
- todo_dict = []
- flag_dict = {'Y':True,'N':False}
- for todo in todos:
- todo_dict.append({'id':todo.id,'content':todo.content,'done':flag_dict[todo.done],'order':todo.order})
- return HttpResponse(simplejson.dumps(todo_dict), mimetype = 'application/json')
- '''''
- protect
- @desc 创建一个todo记录
- @param POST中的json格式todo对象
- @return json格式{'success':True/False}
- '''
- def create(request):
- req = simplejson.loads(request.raw_post_data)
- content = req['content']
- order = req['order']
- if not content:
- return HttpResponse(simplejson.dumps({'success':False}), mimetype = 'application/json')
- todo = Todo()
- todo.content = content
- todo.order = order
- todo.save()
- return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
- '''''
- protect
- @desc 更新一条todo记录
- @param POST中的json格式todo对象
- @return json格式{'success':True/False}
- '''
- def update(request, todo_id):
- req = simplejson.loads(request.raw_post_data)
- content = req['content']
- done = req['done']
- order = req['order']
- flag_dict = {True:'Y',False:'N'}
- todo = Todo.objects.get(id = todo_id)
- todo.content = content
- todo.done = flag_dict[done]
- todo.order = order
- todo.save()
- return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
- '''''
- protect
- @desc 删除一条todo记录
- @param url中的todo对象id
- @return json格式{'success':True/False}
- '''
- def delete(request, todo_id):
- Todo.objects.get(id = todo_id).delete()
- return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
#coding=utf-8
'''
author:huyang
date: 2012-3-26
blog:http://the5fire.net
'''
from models import Todo
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.utils import simplejson
'''
public
@desc 加载todo首页
@param
@return templates
'''
def index(request):
return render_to_response('todo/todos.html',{})
'''
public
@desc 控制创建和读取方法的一个跳转
@param
@return
'''
def control_cr(request):
if request.method == 'POST':
return create(request)
elif request.method == 'GET':
return getAll(request)
else:
return HttpResponse('
access deny
')
'''
public
@desc 控制更新和删除方法的一个跳转
@param url中的todo对象id
@return
'''
def control_ud(request, todo_id):
if request.method == 'PUT':
return update(request,todo_id)
elif request.method == 'DELETE':
return delete(request,todo_id)
else:
return HttpResponse('
access deny
')
'''
protect
@desc 获取所有的todo对象,并转为json格式,返回
@param
@return json格式的todo列表
'''
def getAll(request):
todos = Todo.objects.all()
todo_dict = []
flag_dict = {'Y':True,'N':False}
for todo in todos:
todo_dict.append({'id':todo.id,'content':todo.content,'done':flag_dict[todo.done],'order':todo.order})
return HttpResponse(simplejson.dumps(todo_dict), mimetype = 'application/json')
'''
protect
@desc 创建一个todo记录
@param POST中的json格式todo对象
@return json格式{'success':True/False}
'''
def create(request):
req = simplejson.loads(request.raw_post_data)
content = req['content']
order = req['order']
if not content:
return HttpResponse(simplejson.dumps({'success':False}), mimetype = 'application/json')
todo = Todo()
todo.content = content
todo.order = order
todo.save()
return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
'''
protect
@desc 更新一条todo记录
@param POST中的json格式todo对象
@return json格式{'success':True/False}
'''
def update(request, todo_id):
req = simplejson.loads(request.raw_post_data)
content = req['content']
done = req['done']
order = req['order']
flag_dict = {True:'Y',False:'N'}
todo = Todo.objects.get(id = todo_id)
todo.content = content
todo.done = flag_dict[done]
todo.order = order
todo.save()
return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
'''
protect
@desc 删除一条todo记录
@param url中的todo对象id
@return json格式{'success':True/False}
'''
def delete(request, todo_id):
Todo.objects.get(id = todo_id).delete()
return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
上面的代码中除了有CRUD代码之后,还有两个重要的函数:control_cr和control_ud,从名字很容易看出来,前者是控制创建和查询的,后者是控制更新和删除的。为什么这么写呢,其原因在于使用backbone在web端进行CRUD操作的时候,对应的url并不一样,因此我写了两个函数。
在control_cr中,根据GET和POST 来判断是查询还是创建爱你,在control_ud中,根据PUST和DELETE来判断是更新还是删除。
上面代码中其他函数就不详解了,都是很简单的语句。
然后我们需要做的就是配置url,在todos下面的那个urls.py文件中的配置如下:
- from django.conf.urls.defaults import patterns, include, url
- import settings
- from todo import views_todos
- urlpatterns = patterns('',
- (r'^site_media/(?P.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_DOC_ROOT,'show_indexes': False}),
- (r'^todo/control/$', views_todos.control_cr),
- (r'^todo/control/(\d*)$', views_todos.control_ud), #例如:http://127.0.0.1:8000/todo/control/1/ PUT就是更新,DELETE就是删除
- (r'^', views_todos.index),
- )
from django.conf.urls.defaults import patterns, include, url
import settings
from todo import views_todos
urlpatterns = patterns('',
(r'^site_media/(?P.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_DOC_ROOT,'show_indexes': False}),
(r'^todo/control/$', views_todos.control_cr),
(r'^todo/control/(\d*)$', views_todos.control_ud), #例如:http://127.0.0.1:8000/todo/control/1/ PUT就是更新,DELETE就是删除
(r'^', views_todos.index),
)
当然web端我们直接使用前面分析过的todos的,只需要修改一下其中的代码。
- 1、在Todo的模型中加入: urlRoot: ‘/todo/control/’
- 2、在collection TodoList中加入:url: ‘/todo/control/’,并且去掉:localStorage: new Store(“todos-backbone”),
这样就ok了。在django项目中还需要配置site_media和templates文件,结构如下:
我用的Komodo Edit这个IDE来开发的。你只要按照这样的结构来建立文件和文件夹就行了。
最后给出settings的所有代码:
- # Django settings for testbackbone project.
- DEBUG = True
- TEMPLATE_DEBUG = DEBUG
- ADMINS = (
- # ('Your Name', '[email protected]'),
- )
- MANAGERS = ADMINS
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
- 'NAME': 'D:/mytodos', # Or path to database file if using sqlite3.
- 'USER': '', # Not used with sqlite3.
- 'PASSWORD': '', # Not used with sqlite3.
- 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
- 'PORT': '', # Set to empty string for default. Not used with sqlite3.
- }
- }
- # Local time zone for this installation. Choices can be found here:
- # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
- # although not all choices may be available on all operating systems.
- # On Unix systems, a value of None will cause Django to use the same
- # timezone as the operating system.
- # If running in a Windows environment this must be set to the same as your
- # system time zone.
- TIME_ZONE = 'America/Chicago'
- # Language code for this installation. All choices can be found here:
- # http://www.i18nguy.com/unicode/language-identifiers.html
- LANGUAGE_CODE = 'en-us'
- SITE_ID = 1
- # If you set this to False, Django will make some optimizations so as not
- # to load the internationalization machinery.
- USE_I18N = True
- # If you set this to False, Django will not format dates, numbers and
- # calendars according to the current locale
- USE_L10N = True
- # Absolute filesystem path to the directory that will hold user-uploaded files.
- # Example: "/home/media/media.lawrence.com/media/"
- MEDIA_ROOT = ''
- # URL that handles the media served from MEDIA_ROOT. Make sure to use a
- # trailing slash.
- # Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
- MEDIA_URL = ''
- # Absolute path to the directory static files should be collected to.
- # Don't put anything in this directory yourself; store your static files
- # in apps' "static/" subdirectories and in STATICFILES_DIRS.
- # Example: "/home/media/media.lawrence.com/static/"
- STATIC_ROOT = './site_media/'
- # URL prefix for static files.
- # Example: "http://media.lawrence.com/static/"
- STATIC_URL = '/site_media/'
- # URL prefix for admin static files -- CSS, JavaScript and images.
- # Make sure to use a trailing slash.
- # Examples: "http://foo.com/static/admin/", "/static/admin/".
- ADMIN_MEDIA_PREFIX = '/static/admin/'
- # Additional locations of static files
- STATICFILES_DIRS = (
- # Put strings here, like "/home/html/static" or "C:/www/django/static".
- # Always use forward slashes, even on Windows.
- # Don't forget to use absolute paths, not relative paths.
- )
- # List of finder classes that know how to find static files in
- # various locations.
- STATICFILES_FINDERS = (
- 'django.contrib.staticfiles.finders.FileSystemFinder',
- 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
- # 'django.contrib.staticfiles.finders.DefaultStorageFinder',
- )
- # Make this unique, and don't share it with anybody.
- SECRET_KEY = 'q4%c$1t0@x0iaco8!8eacy5-g8t)z1549$s4049xf^2y2#!0ef'
- # List of callables that know how to import templates from various sources.
- TEMPLATE_LOADERS = (
- 'django.template.loaders.filesystem.Loader',
- 'django.template.loaders.app_directories.Loader',
- # 'django.template.loaders.eggs.Loader',
- )
- MIDDLEWARE_CLASSES = (
- 'django.middleware.common.CommonMiddleware',
- 'django.contrib.sessions.middleware.SessionMiddleware',
- #'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
- )
- ROOT_URLCONF = 'todos.urls'
- import os
- TEMPLATE_DIRS = (
- # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
- # Always use forward slashes, even on Windows.
- # Don't forget to use absolute paths, not relative paths.
- os.path.join(os.path.dirname(__file__), 'templates').replace('\','/'),
- )
- INSTALLED_APPS = (
- #'django.contrib.auth',
- #'django.contrib.contenttypes',
- #'django.contrib.sessions',
- ##'django.contrib.sites',
- #'django.contrib.messages',
- #'django.contrib.staticfiles',
- 'todos.todo',
- # Uncomment the next line to enable the admin:
- # 'django.contrib.admin',
- # Uncomment the next line to enable admin documentation:
- # 'django.contrib.admindocs',
- )
- STATIC_DOC_ROOT = './site_media'
- # A sample logging configuration. The only tangible logging
- # performed by this configuration is to send an email to
- # the site admins on every HTTP 500 error.
- # See http://docs.djangoproject.com/en/dev/topics/logging for
- # more details on how to customize your logging configuration.
- LOGGING = {
- 'version': 1,
- 'disable_existing_loggers': False,
- 'handlers': {
- 'mail_admins': {
- 'level': 'ERROR',
- 'class': 'django.utils.log.AdminEmailHandler'
- }
- },
- 'loggers': {
- 'django.request': {
- 'handlers': ['mail_admins'],
- 'level': 'ERROR',
- 'propagate': True,
- },
- }
- }
代码已经放到github上了,建议大家下载运行参考。https://github.com/the5fire/the5fire-servertodos