设为首页 收藏本站
查看: 310|回复: 0

[经验分享] Python/Django开发笔记(2) --- CouchDB

[复制链接]

尚未签到

发表于 2015-10-26 12:16:41 | 显示全部楼层 |阅读模式
  接上例:http://blog.iyunv.com/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.iyunv.com/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 = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'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.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
# 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 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 = '-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_protect
from django.http import Http404,HttpResponseRedirect
from django.shortcuts import render_to_response
from couchdb import *
from couchdb.client import *
from django.core.context_processors import csrf
SERVER = Server('http://127.0.0.1:5984')
if (len(SERVER) == 0):
SERVER.create('docs')
@csrf_protect
def index(request):
docs = SERVER['docs']
if request.method == &quot;POST&quot;:
title = request.POST['title'].replace(' ','')
docs[title] = {'title':title,'text':&quot;&quot;}
return HttpResponseRedirect(u&quot;/doc/%s/&quot; % title)
c = {'rows':docs}
c.update(csrf(request))
return render_to_response('couch_docs/index.html', c)
@csrf_protect
def detail(request,id):
docs = SERVER['docs']
try:
doc = docs[id]
except ResourceNotFound:
raise Http404        
if request.method ==&quot;POST&quot;:
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=&quot;post&quot; action=&quot;.&quot;>
{% csrf_token %}
<table>
<tr>
<td> Title for new document </td>
<td>
<input type=&quot;text&quot; name=&quot;title&quot;>
</td>
<td>
<input type=&quot;submit&quot;>
</td>
</tr>
</table>
</form>
<hr>
<ol>
{% for row in rows %}
<li>
<a id=&quot;title&quot; href=&quot;/doc/{{ row }}/&quot;>{{ 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=&quot;/&quot;>Return to index</a>
<table>
<tr>
<td> Title </td>
<td id=&quot;title&quot;>{{ row.title }}</td>
</tr>
<tr>
<td> Text </td>
<td id=&quot;text&quot;>{{ row.text }}</td>
</tr>
</table>
<hr>
<form method=&quot;post&quot; action=&quot;.&quot;>
{% csrf_token %}
<table>
<tr>
<td> Title for new document </td>
<td>
<input type=&quot;text&quot; name=&quot;title&quot; value=&quot;{{ row.title }}&quot;>
</td>
</tr>
<tr>
<td> Text </td>
<td><textarea name=&quot;text&quot;>{{ row.text }}</textarea></td>
<tr>
<td>
<input type=&quot;submit&quot;>
</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攻击的模块, 在上面的代码中已经包含了这部分的内容。
  



版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-130948-1-1.html 上篇帖子: Install Python2.5 (including tkinter) 下篇帖子: Python脚本实现Mac开机自动语音播报天气
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表