forked from unistorage/gridfs-serve
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
46 lines (33 loc) · 1.2 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from werkzeug.wsgi import FileWrapper
from werkzeug.routing import BaseConverter, ValidationError
from pymongo import MongoClient, MongoReplicaSetClient
from bson.objectid import ObjectId
from bson.errors import InvalidId
import settings
class ObjectIdConverter(BaseConverter):
def to_python(self, value):
try:
return ObjectId(value)
except InvalidId:
raise ValidationError()
def to_url(self, value):
return str(value)
class LimitedFileWrapper(FileWrapper):
def __init__(self, file, start, end, buffer_size=8192):
super(LimitedFileWrapper, self).__init__(file, buffer_size=buffer_size)
self.file.seek(start)
self._limit = end
def next(self):
buffer_size = min(self.buffer_size, self._limit - self.file.tell())
data = self.file.read(buffer_size)
if data:
return data
raise StopIteration()
def get_mongodb_connection():
return MongoClient(settings.MONGO_DB_URL)
class MongoDBConnection(object):
def __enter__(self):
self.connection = get_mongodb_connection()
return self.connection
def __exit__(self, type, value, traceback):
self.connection.close()