Hide keyboard shortcuts

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. 

3 

4Install 

5------- 

6 

7The ``couchdb`` package is required: ``pip install couchdb`` 

8 

9.. note:: 

10 According to the `couchdb github page`_, the package is no longer maintained. 

11 

12.. _couchdb github page: https://github.com/djc/couchdb-python/ 

13 

14Setup 

15----- 

16 

17Add the host URL of the database to your ``settings.py`` file: 

18 

19.. code-block:: python 

20 

21 SUPERDJANGO_AJAX_UPLOAD_COUCHDB_HOST = "http://localhost" 

22 SUPERDJANGO_AJAX_UPLOAD_COUCHDB_PORT = 5984 

23 

24Usage 

25----- 

26 

27Specify the backend for the AJAX upload: 

28 

29.. code-block:: python 

30 

31 # views.py 

32 from superdjango.ajax.views import AjaxFileUploader 

33 from superdjango.storage.backends.ajax.couch import CouchDBAjaxStorage 

34 

35 ajax_uploader = AjaxFileUploader(CouchDBAjaxStorage, database="my_file_database") 

36 

37""" 

38# Imports 

39 

40from django.conf import settings 

41from uuid import uuid4 

42from tempfile import TemporaryFile 

43from .base import BaseAjaxStorage 

44from .compat import CouchServer as Server 

45 

46# Exports 

47 

48__all__ = ( 

49 "CouchDBAjaxStorage", 

50) 

51 

52# Constants 

53 

54COUCHDB_HOST = getattr(settings, "SUPERDJANGO_AJAX_UPLOAD_COUCHDB_HOST", 'http://localhost') 

55COUCHDB_PORT = getattr(settings, "SUPERDJANGO_AJAX_UPLOAD_COUCHDB_PORT", 5984) 

56 

57# Classes 

58 

59 

60class CouchDBAjaxStorage(BaseAjaxStorage): 

61 """Stores the file in a CouchDB Backend.""" 

62 

63 def __init__(self, **kwargs): 

64 """Initialize the storage. 

65 

66 :param database: The name of the database within CouchDB. 

67 :type database: str 

68 

69 kwargs are passed to the base ``__init__()``. 

70 

71 """ 

72 self.connection = None 

73 self.database = kwargs.pop('database') 

74 self._dest = None 

75 

76 super().__init__(**kwargs) 

77 

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() 

82 

83 def upload_chunk(self, chunk, *args, **kwargs): 

84 self._dest.write(chunk) 

85 

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()