Database Reference
In-Depth Information
def
def
update_photo_content
(
input_file
,
parent_id
,
slug
):
fs
=
GridFS
(
db
,
'cms.assets'
)
# Delete the old version if it's unlocked or was locked more than 5
# minutes ago
file_obj
=
db
.
cms
.
assets
.
find_one
(
{
'metadata.parent_id'
:
parent_id
,
'metadata.slug'
:
slug
,
'metadata.locked'
:
None
})
iif
file_obj
iis
None
:
threshold
=
datetime
.
utcnow
()
-
timedelta
(
seconds
=
300
)
file_obj
=
db
.
cms
.
assets
.
find_one
(
{
'metadata.parent_id'
:
parent_id
,
'metadata.slug'
:
slug
,
'metadata.locked'
: {
'$lt'
:
threshold
} })
iif
file_obj
iis
None
:
raise
raise
FileDoesNotExist
()
fs
.
delete
(
file_obj
[
'_id'
])
# update content, keep metadata unchanged
file_obj
[
'locked'
]
=
datetime
.
utcnow
()
with
with
fs
.
new_file
(
**
file_obj
):
while
while
True
:
chunk
=
input_file
.
read
(
upload_file
.
chunk_size
)
iif
not
break
upload_file
.
write
(
chunk
)
# unlock the file
db
.
assets
.
files
.
update
(
{
'_id'
:
upload_file
.
_id
},
{
'$set'
: {
'locked'
:
None
} } )
not
chunk
:
break
Note that we need to invoke the
delete
method on the
GridFS
rather than just use
our normal
remove
MongoDB functionality. This is because we need to make sure
that both the document in
cms.assets.files
is removed
and
the corresponding
chunks in
cms.assets.chunks
.
As with the basic operations, editing tags is almost trivial:
db
.
cms
.
assets
.
files
.
update
(
{
'metadata.parent_id'
:
parent_id
,
'metadata.slug'
:
slug
},
{
'$addToSet'
: {
'metadata.tags'
: {
'$each'
: [
'interesting'
,
'funny'
]}}})