Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2CouchDB backend storage upload via AJAX.
4Install
5-------
7The ``couchdb`` package is required: ``pip install couchdb``
9.. note::
10 According to the `couchdb github page`_, the package is no longer maintained.
12.. _couchdb github page: https://github.com/djc/couchdb-python/
14Setup
15-----
17Add the host URL of the database to your ``settings.py`` file:
19.. code-block:: python
21 SUPERDJANGO_AJAX_UPLOAD_COUCHDB_HOST = "http://localhost"
22 SUPERDJANGO_AJAX_UPLOAD_COUCHDB_PORT = 5984
24Usage
25-----
27Specify the backend for the AJAX upload:
29.. code-block:: python
31 # views.py
32 from superdjango.ajax.views import AjaxFileUploader
33 from superdjango.storage.backends.ajax.couch import CouchDBAjaxStorage
35 ajax_uploader = AjaxFileUploader(CouchDBAjaxStorage, database="my_file_database")
37"""
38# Imports
40from django.conf import settings
41from uuid import uuid4
42from tempfile import TemporaryFile
43from .base import BaseAjaxStorage
44from .compat import CouchServer as Server
46# Exports
48__all__ = (
49 "CouchDBAjaxStorage",
50)
52# Constants
54COUCHDB_HOST = getattr(settings, "SUPERDJANGO_AJAX_UPLOAD_COUCHDB_HOST", 'http://localhost')
55COUCHDB_PORT = getattr(settings, "SUPERDJANGO_AJAX_UPLOAD_COUCHDB_PORT", 5984)
57# Classes
60class CouchDBAjaxStorage(BaseAjaxStorage):
61 """Stores the file in a CouchDB Backend."""
63 def __init__(self, **kwargs):
64 """Initialize the storage.
66 :param database: The name of the database within CouchDB.
67 :type database: str
69 kwargs are passed to the base ``__init__()``.
71 """
72 self.connection = None
73 self.database = kwargs.pop('database')
74 self._dest = None
76 super().__init__(**kwargs)
78 def setup(self, filename, *args, **kwargs):
79 host = "%s:%s" % (COUCHDB_HOST, COUCHDB_PORT)
80 self.connection = Server(host)[self.database]
81 self._dest = TemporaryFile()
83 def upload_chunk(self, chunk, *args, **kwargs):
84 self._dest.write(chunk)
86 def upload_complete(self, request, filename, *args, **kwargs):
87 self._dest.seek(0)
88 doc_id = uuid4().hex
89 # create doc by self defined uuid. We need the _rev for attachment
90 doc = self.connection[doc_id] = {'_id':doc_id,
91 # append anything you like maybe from
92 # request
93 }
94 # mimetype is guessed by extension.
95 # We don't put the whole document back in the put_attachment request
96 self.connection.put_attachment(
97 {'_id':doc['_id'], '_rev':doc['_rev']},
98 self._dest,
99 filename=filename
100 )
101 self._dest.close()