Python/Django开发笔记(2) --- CouchDB

来源:互联网 发布:网络语灌水是什么意思 编辑:程序博客网 时间:2024/06/05 20:24

接上例:http://blog.csdn.net/kunshan_shenbin/article/details/7668566

这次将介绍Django下操作CouchDB的例子,工程仍将使用PyDev来创建。

本文示例代码参考自:

http://lethain.com/an-introduction-to-using-couchdb-with-django/

https://github.com/lethain/comfy-django-example

不过由于Django已经升级至1.4,很多地方需要改动。

首先要进行一些准备工作:

a. 安装并启动CouchDB。

b. 安装Python/django以及eazy_install (windows下可参考:http://blog.csdn.net/kunshan_shenbin/article/details/7663187).

c. 安装couchdb-python组件:

easy_install couchdb

操作步骤:

1. 新建PyDev项目comfy_django_example。

2. 在comfy_django_example里新建应用couch_docs。

3. 修改comfy_django_example\settings.py 如下:

# Django settings for comfy_django_example project.DEBUG = TrueTEMPLATE_DEBUG = DEBUGADMINS = (    # ('Your Name', 'your_email@example.com'),)MANAGERS = ADMINSDATABASES = {    'default': {        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.        'NAME': 'D:\\Work\\Aptana Studio 3\\Workspace\\comfy_django_example\\sqlite.db',                      # 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.htmlLANGUAGE_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# If you set this to False, Django will not use timezone-aware datetimes.USE_TZ = 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 = ''# URL prefix for static files.# Example: "http://media.lawrence.com/static/"STATIC_URL = '/static/'# Additional locations of static filesSTATICFILES_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 = '-k76t*s+kl4c5-9-l@&dmg7537qc!-5vdjijzm14rc77o!y)7&'# 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',    # Uncomment the next line for simple clickjacking protection:    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',        #'django.middleware.csrf.CsrfViewMiddleware',)ROOT_URLCONF = 'comfy_django_example.urls'# Python dotted path to the WSGI application used by Django's runserver.WSGI_APPLICATION = 'comfy_django_example.wsgi.application'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.)INSTALLED_APPS = (    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.sites',    'django.contrib.messages',    'django.contrib.staticfiles',    # Uncomment the next line to enable the admin:    # 'django.contrib.admin',    # Uncomment the next line to enable admin documentation:    # 'django.contrib.admindocs',        'couch_docs',)# 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 when DEBUG=False.# 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,    'filters': {        'require_debug_false': {            '()': 'django.utils.log.RequireDebugFalse'        }    },    'handlers': {        'mail_admins': {            'level': 'ERROR',            'filters': ['require_debug_false'],            'class': 'django.utils.log.AdminEmailHandler'        }    },    'loggers': {        'django.request': {            'handlers': ['mail_admins'],            'level': 'ERROR',            'propagate': True,        },    }}
4. 修改comfy_django_example\urls.py 如下:
from django.conf.urls import patterns, include, url# Uncomment the next two lines to enable the admin:# from django.contrib import admin# admin.autodiscover()urlpatterns = patterns('',    # Examples:    # url(r'^$', 'comfy_django_example.views.home', name='home'),    # url(r'^comfy_django_example/', include('comfy_django_example.foo.urls')),    # Uncomment the admin/doc line below to enable admin documentation:    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),    # Uncomment the next line to enable the admin:    # url(r'^admin/', include(admin.site.urls)),)urlpatterns += patterns('couch_docs.views',    (r'^doc/(?P<id>\w+)/','detail'),    (r'^$','index'),)

5. 修改couch_docs\views.py 如下:

# Create your views here.from django.views.decorators.csrf import csrf_protectfrom django.http import Http404,HttpResponseRedirectfrom django.shortcuts import render_to_responsefrom couchdb import *from couchdb.client import *from django.core.context_processors import csrfSERVER = Server('http://127.0.0.1:5984')if (len(SERVER) == 0):    SERVER.create('docs')@csrf_protectdef index(request):    docs = SERVER['docs']    if request.method == "POST":        title = request.POST['title'].replace(' ','')        docs[title] = {'title':title,'text':""}        return HttpResponseRedirect(u"/doc/%s/" % title)        c = {'rows':docs}    c.update(csrf(request))    return render_to_response('couch_docs/index.html', c)@csrf_protectdef detail(request,id):    docs = SERVER['docs']    try:        doc = docs[id]    except ResourceNotFound:        raise Http404            if request.method =="POST":        doc['title'] = request.POST['title'].replace(' ','')        doc['text'] = request.POST['text']        docs[id] = doc            c = {'row':doc}    c.update(csrf(request))    return render_to_response('couch_docs/detail.html',c)

6. 在应用couch_docs目录下新建templates\couch_docs,里面放置两个模板文件。

index.html

<html><head><title>Comfy Django</title></head><body><h1>CouchDB in Django</h1><form method="post" action=".">{% csrf_token %}<table><tr><td> Title for new document </td><td><input type="text" name="title"></td><td><input type="submit"></td></tr></table></form><hr><ol>{% for row in rows %}<li><a id="title" href="/doc/{{ row }}/">{{ row }}</a></li>{% endfor %}</ol></body></html>
detail.html
<html><head><title>CouchDB in Django: {{ row.title }}</title></head><body><h1>CouchDB in Django: {{ row.title }}</h1><a href="/">Return to index</a><table><tr><td> Title </td><td id="title">{{ row.title }}</td></tr><tr><td> Text </td><td id="text">{{ row.text }}</td></tr></table><hr><form method="post" action=".">{% csrf_token %}<table><tr><td> Title for new document </td><td><input type="text" name="title" value="{{ row.title }}"></td></tr><tr><td> Text </td><td><textarea name="text">{{ row.text }}</textarea></td><tr><td><input type="submit"></td></tr></table></form></body></html>

接下来只要启动并运行即可。

这里还有对该couchdb组件的封装类。

http://wiki.apache.org/couchdb/Getting_started_with_Python


另付:Cross Site Request Forgery protection

https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/

从Django1.2起加入了防止CSRF攻击的模块, 在上面的代码中已经包含了这部分的内容。