|
1 #!/usr/bin/python2.5 |
|
2 # |
|
3 # Copyright 2008 the Melange authors. |
|
4 # |
|
5 # Licensed under the Apache License, Version 2.0 (the "License"); |
|
6 # you may not use this file except in compliance with the License. |
|
7 # You may obtain a copy of the License at |
|
8 # |
|
9 # http://www.apache.org/licenses/LICENSE-2.0 |
|
10 # |
|
11 # Unless required by applicable law or agreed to in writing, software |
|
12 # distributed under the License is distributed on an "AS IS" BASIS, |
|
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
14 # See the License for the specific language governing permissions and |
|
15 # limitations under the License. |
|
16 |
|
17 """Document (Model) query functions. |
|
18 """ |
|
19 |
|
20 __authors__ = [ |
|
21 '"Pawel Solyga" <pawel.solyga@gmail.com>', |
|
22 ] |
|
23 |
|
24 from google.appengine.ext import db |
|
25 |
|
26 import soc.models.document |
|
27 import soc.logic.model |
|
28 |
|
29 def getDocumentFromPath(path): |
|
30 """Returns Document entity for a given path, or None if not found. |
|
31 |
|
32 Args: |
|
33 id: a Google Account (users.User) object |
|
34 """ |
|
35 # lookup by Doc:path key name |
|
36 key_name = getDocumentKeyNameForPath(path) |
|
37 |
|
38 if key_name: |
|
39 document = soc.models.document.Document.get_by_key_name(key_name) |
|
40 else: |
|
41 document = None |
|
42 |
|
43 return document |
|
44 |
|
45 def getDocumentKeyNameForPath(path): |
|
46 """Return a Datastore key_name for a Document from the path. |
|
47 |
|
48 Args: |
|
49 path: a request path of the Document that uniquely identifies it |
|
50 """ |
|
51 if not path: |
|
52 return None |
|
53 |
|
54 return 'Doc:%s' % path |
|
55 |
|
56 |
|
57 def updateOrCreateDocumentFromPath(path, **document_properties): |
|
58 """Update existing Document entity, or create new one with supplied properties. |
|
59 |
|
60 Args: |
|
61 path: a request path of the Document that uniquely identifies it |
|
62 **document_properties: keyword arguments that correspond to Document entity |
|
63 properties and their values |
|
64 |
|
65 Returns: |
|
66 the Document entity corresponding to the path, with any supplied |
|
67 properties changed, or a new Document entity now associated with the |
|
68 supplied path and properties. |
|
69 """ |
|
70 # attempt to retrieve the existing Document |
|
71 document = getDocumentFromPath(path) |
|
72 |
|
73 if not document: |
|
74 # document did not exist, so create one in a transaction |
|
75 key_name = getDocumentKeyNameForPath(path) |
|
76 document = soc.models.document.Document.get_or_insert( |
|
77 key_name, **document_properties) |
|
78 |
|
79 # there is no way to be sure if get_or_insert() returned a new Document or |
|
80 # got an existing one due to a race, so update with document_properties anyway, |
|
81 # in a transaction |
|
82 return soc.logic.model.updateModelProperties(document, **document_properties) |
|
83 |
|
84 |
|
85 |