8000 Re-add firebase rest_api examples. (#607) · devlance/python-docs-samples@ee89cf6 · GitHub
[go: up one dir, main page]

Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit ee89cf6

Browse files
authored
Re-add firebase rest_api examples. (GoogleCloudPlatform#607)
Also - remove unnecssary region tags.
1 parent a6f61d2 commit ee89cf6

File tree

3 files changed

+118
-19
lines changed

3 files changed

+118
-19
lines changed

appengine/standard/firebase/firetactoe/creds.json

Lines changed: 0 additions & 1 deletion
This file was deleted.

appengine/standard/firebase/firetactoe/firetactoe.py

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ def _get_firebase_db_url():
7575

7676
# Memoize the authorized http, to avoid fetching new access tokens
7777
@lru_cache()
78-
# [START authed_http]
7978
def _get_http():
8079
"""Provides an authed http object."""
8180
http = httplib2.Http()
@@ -85,10 +84,8 @@ def _get_http():
8584
_FIREBASE_SCOPES)
8685
creds.authorize(http)
8786
return http
88-
# [END authed_http]
8987

9088

91-
# [START send_msg]
9289
def _send_firebase_message(u_id, message=None):
9390
"""Updates data in firebase. If a message is provided, then it updates
9491
the data at /channels/<channel_id> with the message using the PATCH
@@ -101,10 +98,8 @@ def _send_firebase_message(u_id, message=None):
10198
return _get_http().request(url, 'PATCH', body=message)
10299
else:
103100
return _get_http().request(url, 'DELETE 10000 ')
104-
# [END send_msg]
105101

106102

107-
# [START create_token]
108103
def create_custom_token(uid, valid_minutes=60):
109104
"""Create a secure token for the given id.
110105
@@ -135,7 +130,6 @@ def create_custom_token(uid, valid_minutes=60):
135130
# Sign the jwt using the built in app_identity service
136131
return '{}.{}'.format(to_sign, base64.b64encode(
137132
app_identity.sign_blob(to_sign)[1]))
138-
# [END create_token]
139133

140134

141135
class Game(ndb.Model):
@@ -152,20 +146,16 @@ def to_json(self):
152146
d['winningBoard'] = d.pop('winning_board')
153147
return json.dumps(d, default=lambda user: user.user_id())
154148

155-
# [START send_update]
156149
def send_update(self):
157150
"""Updates Firebase's copy of the board."""
158151
message = self.to_json()
159152
# send updated game state to user X
160153
_send_firebase_message(
161-
self.userX.user_id() + self.key.id(),
162-
message=message)
154+
self.userX.user_id() + self.key.id(), message=message)
163155
# send updated game state to user O
164156
if self.userO:
165157
_send_firebase_message(
166-
self.userO.user_id() + self.key.id(),
167-
message=message)
168-
# [END send_update]
158+
self.userO.user_id() + self.key.id(), message=message)
169159

170160
def _check_win(self):
171161
if self.moveX:
@@ -187,7 +177,6 @@ def _check_win(self):
187177
if ' ' not in self.board:
188178
self.winner = 'Noone'
189179

190-
# [START make_move]
191180
def make_move(self, position, user):
192181
# If the user is a player, and it's their move
193182
if (user in (self.userX, self.userO)) and (
@@ -202,7 +191,6 @@ def make_move(self, position, user):
202191
self.put()
203192
self.send_update()
204193
return
205-
# [END make_move]
206194

207195

208196
# [START move_route]
@@ -224,8 +212,7 @@ def delete():
224212
if not game:
225213
return 'Game not found', 400
226214
user = users.get_current_user()
227-
_send_firebase_message(
228-
user.user_id() + game.key.id(), message=None)
215+
_send_firebase_message(user.user_id() + game.key.id(), message=None)
229216
return ''
230217
# [END route_delete]
231218

@@ -266,8 +253,7 @@ def main_page():
266253
# Firebase's data security rules will be able to decrypt the
267254
# token and prevent unauthorized access
268255
client_auth_token = create_custom_token(channel_id)
269-
_send_firebase_message(
270-
channel_id, message=game.to_json())
256+
_send_firebase_message(channel_id, message=game.to_json())
271257

272258
# game_link is a url that you can open in another browser to play
273259
# against this player
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Copyright 2016 Google Inc. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Demonstration of the Firebase REST API in Python"""
16+
17+
try:
18+
from functools import lru_cache
19+
except ImportError:
20+
from functools32 import lru_cache
21+
# [START rest_writing_data]
22+
import json
23+
24+
import httplib2
25+
from oauth2client.client import GoogleCredentials
26+
27+
_FIREBASE_SCOPES = [
28+
'https://www.googleapis.com/auth/firebase.database',
29+
'https://www.googleapis.com/auth/userinfo.email']
30+
31+
32+
# Memoize the authorized http, to avoid fetching new access tokens
33+
@lru_cache()
34+
def _get_http():
35+
"""Provides an authed http object."""
36+
http = httplib2.Http()
37+
# Use application default credentials to make the Firebase calls
38+
# https://firebase.google.com/docs/reference/rest/database/user-auth
39+
creds = GoogleCredentials.get_application_default().create_scoped(
40+
_FIREBASE_SCOPES)
41+
creds.authorize(http)
42+
return http
43+
44+
45+
def firebase_put(path, value=None):
46+
"""Writes data to Firebase.
47+
48+
An HTTP PUT writes an entire object at the given database path. Updates to
49+
fields cannot be performed without overwriting the entire object
50+
51+
Args:
52+
path - the url to the Firebase object to write.
53+
value - a json string.
54+
"""
55+
response, content = _get_http().request(path, method='PUT', body=value)
56+
return json.loads(content)
57+
58+
59+
def firebase_patch(path, value=None):
60+
"""Update specific children or fields
61+
62+
An HTTP PATCH allows specific children or fields to be updated without
63+
overwriting the entire object.
64+
65+
Args:
66+
path - the url to the Firebase object to write.
67+
value - a json string.
68+
"""
69+
response, content = _get_http().request(path, method='PATCH', body=value)
70+
return json.loads(content)
71+
72+
73+
def firebase_post(path, value=None):
74+
"""Add an object to an existing list of data.
75+
76+
An HTTP POST allows an object to be added to an existing list of data.
77+
A successful request will be indicated by a 200 OK HTTP status code. The
78+
response content will contain a new attribute "name" which is the key for
79+
the child added.
80+
81+
Args:
82+
path - the url to the Firebase list to append to.
83+
value - a json string.
84+
"""
85+
response, content = _get_http().request(path, method='POST', body=value)
86+
return json.loads(content)
87+
# [END rest_writing_data]
88+
89+
90+
def firebase_get(path):
91+
"""Read the data at the given path.
92+
93+
An HTTP GET request allows reading of data at a particular path.
94+
A successful request will be indicated by a 200 OK HTTP status code.
95+
The response will contain the data being retrieved.
96+
97+
Args:
98+
path - the url to the Firebase object to read.
99+
"""
100+
response, content = _get_http().request(path, method='GET')
101+
return json.loads(content)
102+
103+
104+
def firebase_delete(path):
105+
"""Removes the data at a particular path.
106+
107+
An HTTP DELETE removes the data at a particular path. A successful request
108+
will be indicated by a 200 OK HTTP status code with a response containing
109+
JSON null.
110+
111+
Args:
112+
path - the url to the Firebase object to delete.
113+
"""
114+
response, content = _get_http().request(path, method='DELETE')

0 commit comments

Comments
 (0)
0