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"""
2MongoDB backend storage upload via AJAX.
4Install
5-------
7The ``pymongo`` and ``gridfs`` packages are required:
9```bash
10pip install pymongo;
11pip install gridfs;
12```
14Setup
15-----
17Add the host URL of the database to your ``settings.py`` file:
19.. code-block:: python
21 SUPERDJANGO_AJAX_UPLOAD_MONGODB_HOST = "localhost"
22 SUPERDJANGO_AJAX_UPLOAD_MONGODB_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 MongoDBAjaxStorage
35 ajax_uploader = AjaxFileUploader(MongoDBAjaxStorage)
37"""
38# Imports
40from django.conf import settings
41import mimetypes
42from .base import BaseAjaxStorage
43from .compat import gridfs, MongoDBConnection as Connection
45# Exports
47__all__ = (
48 "MongoDBAjaxStorage",
49)
51# Constants
53MONGODB_HOST = getattr(settings, "SUPERDJANGO_AJAX_UPLOAD_MONGODB_HOST", "localhost")
54MONGODB_PORT = getattr(settings, "SUPERDJANGO_AJAX_UPLOAD_MONGODB_PORT", 27017)
55MONGODB_REPLICASET = getattr(settings, "SUPERDJANGO_AJAX_UPLOAD_MONGODB_REPLICASET", "")
57# Classes
60class MongoDBAjaxStorage(BaseAjaxStorage):
61 """
62 Stores uploaded file in Mongo's GridFS.
64 Requirements: pymongo
65 """
66 def __init__(self, **kwargs):
67 self.collection = kwargs.pop('collection', None)
68 self.connection = None
69 self.db = kwargs.pop('db')
70 self.grid = None
71 self.f = None
72 self._path = None
74 super().__init__(**kwargs)
76 def setup(self, filename, encoding='UTF-8', *args, **kwargs):
77 """Setup MongoDB connection to specified db. Collection is optional and will default to fs if not specified.
79 Create new gridFS file which returns a GridIn instance to write data to.
80 """
81 host = MONGODB_HOST
82 port = MONGODB_PORT
83 replicaset = MONGODB_REPLICASET
85 _host = "%s:%s" % (host, port)
87 self.connection = Connection(_host, replicaset=replicaset)[self.db]
89 if self.collection:
90 self.grid = gridfs.GridFS(self.connection, collection=self.collection)
91 else:
92 self.grid = gridfs.GridFS(self.connection)
94 self._path = filename
95 content_type, encoding = mimetypes.guess_type(filename)
97 _kwargs = {
98 'filname': self._path,
99 'encoding': 'UTF-8',
100 'content_type': content_type,
101 }
102 self.f = self.grid.new_file(**_kwargs)
104 def upload_chunk(self, chunk, *args, **kwargs):
105 self.f.write(chunk)
107 def upload_complete(self, request, filename, *args, **kwargs):
108 self.f.close()
109 # provide a string representation of the GridFS File ObjectId
110 # noinspection PyProtectedMember
111 return {'_id': str(self.f._id)}