10000 Use decorator to memoize. by jerjou · Pull Request #598 · GoogleCloudPlatform/python-docs-samples · GitHub
[go: up one dir, main page]

Skip to content

Use decorator to memoize. #598

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 21, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions appengine/bigquery/main_flask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Sample appengine app demonstrating 3-legged oauth."""
import cgi
import json
import os
import sys

from flask import Flask

from googleapiclient.discovery import build

from oauth2client.appengine import OAuth2DecoratorFromClientSecrets

# The project id whose datasets you'd like to list
PROJECTID = '<myproject_id>'

# Create the method decorator for oauth.
decorator = OAuth2DecoratorFromClientSecrets(
os.path.join(os.path.dirname(__file__), 'client_secrets.json'),
scope='https://www.googleapis.com/auth/bigquery')

# Create the bigquery api client
service = build('bigquery', 'v2')

# Create the Flask app
app = Flask(__name__)
app.config['DEBUG'] = True

# Create the endpoint to receive oauth flow callbacks
app.route(decorator.callback_path)(decorator.callback_handler())


@app.route('/')
@decorator.oauth_required
def list_datasets():
"""Lists the datasets in PROJECTID"""
http = decorator.http()
datasets = service.datasets()

try:
response = datasets.list(projectId=PROJECTID).execute(http)

return ('<h3>Datasets.list raw response:</h3>'
'<pre>%s</pre>' % json.dumps(response, sort_keys=True,
indent=4, separators=(',', ': ')))
except:
e = cgi.escape(sys.exc_info()[0], True)
return '<p>Error: %s</p>' % e
1 change: 1 addition & 0 deletions appengine/standard/firebase/firetactoe/creds.json
43 changes: 25 additions & 18 deletions appengine/standard/firebase/firetactoe/firetactoe.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
"""Tic Tac Toe with the Firebase API"""

import base64
try:
from functools import lru_cache
except ImportError:
from functools32 import lru_cache
import json
import os
import re
Expand Down Expand Up @@ -51,33 +55,36 @@
app = flask.Flask(__name__)


def _get_firebase_db_url(_memo={}):
# Memoize the value, to avoid parsing the code snippet every time
@lru_cache()
def _get_firebase_db_url():
"""Grabs the databaseURL from the Firebase config snippet. Regex looks
scary, but all it is doing is pulling the 'databaseURL' field from the
Firebase javascript snippet"""
if 'dburl' not in _memo:
# Memoize the value, to avoid parsing the code snippet every time
regex = re.compile(r'\bdatabaseURL\b.*?["\']([^"\']+)')
cwd = os.path.dirname(__file__)
regex = re.compile(r'\bdatabaseURL\b.*?["\']([^"\']+)')
cwd = os.path.dirname(__file__)
try:
with open(os.path.join(cwd, 'templates', _FIREBASE_CONFIG)) as f:
url = next(regex.search(line) for line in f if regex.search(line))
_memo['dburl'] = url.group(1)
return _memo['dburl']
except StopIteration:
raise ValueError(
'Error parsing databaseURL. Please copy Firebase web snippet '
'into templates/{}'.format(_FIREBASE_CONFIG))
return url.group(1)


# Memoize the authorized http, to avoid fetching new access tokens
@lru_cache()
# [START authed_http]
def _get_http(_memo={}):
def _get_http():
"""Provides an authed http object."""
if 'http' not in _memo:
# Memoize the authorized http, to avoid fetching new access tokens
http = httplib2.Http()
# Use application default credentials to make the Firebase calls
# https://firebase.google.com/docs/reference/rest/database/user-auth
creds = GoogleCredentials.get_application_default().create_scoped(
_FIREBASE_SCOPES)
creds.authorize(http)
_memo['http'] = http
return _memo['http']
http = httplib2.Http()
# Use application default credentials to make the Firebase calls
# https://firebase.google.com/docs/reference/rest/database/user-auth
creds = GoogleCredentials.get_application_default().create_scoped(
_FIREBASE_SCOPES)
creds.authorize(http)
return http
# [END authed_http]


Expand Down
3 changes: 1 addition & 2 deletions appengine/standard/firebase/firetactoe/firetactoe_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ def request(self, url, method, content='', *args, **kwargs):
@pytest.fixture
def app(testbed, monkeypatch, login):
# Don't let the _get_http function memoize its value
orig_get_http = firetactoe._get_http
monkeypatch.setattr(firetactoe, '_get_http', lambda: orig_get_http({}))
firetactoe._get_http.cache_clear()

# Provide a test firebase config. The following will set the databaseURL
# databaseURL: "http://firebase.com/test-db-url"
Expand Down
3 changes: 2 additions & 1 deletion appengine/standard/firebase/firetactoe/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask==0.11.1
requests==2.11.1
requests_toolbelt==0.7.0
oauth2client==4.0.0
oauth2client==2.2.0
functools32==3.2.3.post2 ; python_version < '3'
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<script src="https://www.gstatic.com/firebasejs/3.4.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyC3gJDK1r-8nZuJGdmXntJR4E8cqH8qSTk",
authDomain: "channels-api-deprecation.firebaseapp.com",
databaseURL: "https://channels-api-deprecation.firebaseio.com",
storageBucket: "channels-api-deprecation.appspot.com",
messagingSenderId: "542117602304"
};
firebase.initializeApp(config);
</script>
0