-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud_datastore_admin.py
More file actions
62 lines (55 loc) · 2.16 KB
/
Copy pathcloud_datastore_admin.py
File metadata and controls
62 lines (55 loc) · 2.16 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import datetime
import httplib
import json
import logging
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import urlfetch
# Calls the Datastore export api to export data to the given bucket
class Export(webapp2.RequestHandler):
def get(self):
access_token, _ = app_identity.get_access_token(
"https://www.googleapis.com/auth/datastore"
)
app_id = app_identity.get_application_id()
timestamp = datetime.datetime.now().strftime("%Y-%m-%d")
output_url_prefix = self.request.get("output_url_prefix")
assert output_url_prefix and output_url_prefix.startswith("gs://")
if "/" not in output_url_prefix[5:]:
# Only a bucket name has been provided - no prefix or trailing slash
output_url_prefix += "/" + timestamp
else:
output_url_prefix += timestamp
entity_filter = {
"kinds": self.request.get_all("kind"),
"namespace_ids": self.request.get_all("namespace_id"),
}
request = {
"project_id": app_id,
"output_url_prefix": output_url_prefix,
"entity_filter": entity_filter,
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + access_token,
}
url = "https://datastore.googleapis.com/v1/projects/%s:export" % app_id
try:
result = urlfetch.fetch(
url=url,
payload=json.dumps(request),
method=urlfetch.POST,
deadline=60,
headers=headers,
)
if result.status_code == httplib.OK:
logging.info(result.content)
elif result.status_code >= 500:
logging.error(result.content)
else:
logging.warning(result.content)
self.response.status_int = result.status_code
except urlfetch.Error:
logging.exception("Failed to initiate export.")
self.response.status_int = httplib.INTERNAL_SERVER_ERROR
app = webapp2.WSGIApplication([("/cloud-datastore-export", Export)], debug=True)