Skip to content
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

Move bigquery 3lo sample on GAE to github. #53

Merged
merged 1 commit into from
Jul 17, 2015
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
19 changes: 19 additions & 0 deletions bigquery/samples/appengine_auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
## Google App Engine accessing BigQuery using OAuth2

This sample demonstrates [authenticating to BigQuery in App Engine using OAuth2](https://cloud.google.com/bigquery/authorization).

### Setup

* To install dependencies for this sample, run:

$ pip install -t lib -r requirements.txt

* You must then update `main.py` and replace `<myproject_id>` with your project's
id.
* You'll need a client id from your project - instructions
[here](https://cloud-dot-devsite.googleplex.com/bigquery/authorization#clientsecrets).
Once you've downloaded the client's json secret, copy it to the root directory
of this project, and rename it to `client_secrets.json`.
* You can then run the sample on your development server:

$ dev_appserver.py .
Empty file.
9 changes: 9 additions & 0 deletions bigquery/samples/appengine_auth/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
application: cloud-samples-tests
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: .*
script: main.app
4 changes: 4 additions & 0 deletions bigquery/samples/appengine_auth/appengine_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from google.appengine.ext import vendor

# Add any libraries installed in the "lib" folder.
vendor.add('lib')
3 changes: 3 additions & 0 deletions bigquery/samples/appengine_auth/client_secrets.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{"web":{
"client_id":"NOTE: this is just a placeholder for unit tests. See the README for what to replace this file with.",
"auth_uri":"TODO","token_uri":"TODO","auth_provider_x509_cert_url":"TODO","client_email":"","client_x509_cert_url":"","client_secret":"TODO","redirect_uris":["TODO","TODO"],"javascript_origins":["TODO","TODO"]}}
60 changes: 60 additions & 0 deletions bigquery/samples/appengine_auth/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START all]
"""Sample appengine app demonstrating 3-legged oauth."""
import json
import os

from googleapiclient.discovery import build

from oauth2client.appengine import OAuth2DecoratorFromClientSecrets

import webapp2


# 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')


class MainPage(webapp2.RequestHandler):

@decorator.oauth_required
def get(self):
"""Lists the datasets in PROJECTID"""
http = decorator.http()
datasets = service.datasets()

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

self.response.out.write('<h3>Datasets.list raw response:</h3>')
self.response.out.write('<pre>%s</pre>' %
json.dumps(response, sort_keys=True, indent=4,
separators=(',', ': ')))


# Create the webapp2 application
app = webapp2.WSGIApplication([
('/', MainPage),
# Create the endpoint to receive oauth flow callbacks
(decorator.callback_path, decorator.callback_handler())
], debug=True)
# [END all]
1 change: 1 addition & 0 deletions bigquery/samples/appengine_auth/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
google-api-python-client
14 changes: 14 additions & 0 deletions bigquery/tests/resources/datasets-list.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"datasets": [
{
"datasetReference": {
"datasetId": "test_dataset_java",
"projectId": "cloud-samples-tests"
},
"id": "cloud-samples-tests:test_dataset_java",
"kind": "bigquery#dataset"
}
],
"etag": "\"ZduQht1tG1odVP6IPm66xfuN2eI/HmGRlylAN_zCB6N4JDeX_XDO0R0\"",
"kind": "bigquery#datasetList"
}
88 changes: 88 additions & 0 deletions bigquery/tests/test_appengine_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import re

from apiclient.http import HttpMock

from bigquery.samples.appengine_auth import main

import mock

import tests

import webapp2


RESOURCE_PATH = os.path.join(
os.path.abspath(os.path.dirname(__file__)), 'resources')


class TestAuthSample(tests.DatastoreTestbedCase, tests.CloudBaseTest):

def setUp(self):
tests.DatastoreTestbedCase.setUp(self)
tests.CloudBaseTest.setUp(self)

self.testbed.init_user_stub()

def loginUser(self, email='user@example.com', id='123', is_admin=False):
self.testbed.setup_env(
user_email=email,
user_id=id,
user_is_admin='1' if is_admin else '0',
overwrite=True)

def test_anonymous_get(self):
request = webapp2.Request.blank('/')
response = request.get_response(main.app)

# Should redirect to login
self.assertEqual(response.status_int, 302)
self.assertRegexpMatches(response.headers['Location'],
r'.*accounts.*Login.*')

def test_loggedin_get(self):
self.loginUser()

request = webapp2.Request.blank('/')
response = request.get_response(main.app)

# Should redirect to login
self.assertEqual(response.status_int, 302)
self.assertRegexpMatches(response.headers['Location'], r'.*oauth2.*')

@mock.patch.object(main.decorator, 'has_credentials', return_value=True)
def test_oauthed_get(self, *args):
self.loginUser()

request = webapp2.Request.blank('/')

mock_http = HttpMock(
os.path.join(RESOURCE_PATH, 'datasets-list.json'),
{'status': '200'})
with mock.patch.object(main.decorator, 'http', return_value=mock_http):
original_projectid = main.PROJECTID
try:
main.PROJECTID = self.constants['projectId']
response = request.get_response(main.app)
finally:
main.PROJECTID = original_projectid

# Should make the api call
self.assertEqual(response.status_int, 200)
self.assertRegexpMatches(
response.body,
re.compile(r'.*datasets.*datasetReference.*etag.*', re.DOTALL))