本文整理汇总了Python中util.create_service函数的典型用法代码示例。如果您正苦于以下问题:Python create_service函数的具体用法?Python create_service怎么用?Python create_service使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了create_service函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _perform_post_auth_tasks
def _perform_post_auth_tasks(self, userid, creds):
"""Perform common post authorization tasks.
Subscribes the service to notifications for the user.
Creates tasks service and oauths it in.
Args:
userid: ID of the current user.
creds: Credentials for the current user.
"""
mirror_service = util.create_service('mirror', 'v1', creds)
tasks_service = util.create_service('tasks', 'v1', creds)
hostname = util.get_full_url(self, '')
# Only do the post auth tasks when deployed.
if hostname.startswith('https://'):
# Insert a subscription.
subscription_body = {
'collection': 'timeline',
# TODO: hash the userToken.
'userToken': userid,
'callbackUrl': util.get_full_url(self, '/notify')
}
mirror_service.subscriptions().insert(body=subscription_body).execute()
开发者ID:jbyeung,项目名称:glassgtasks,代码行数:25,代码来源:handler.py
示例2: post
def post(self):
"""Handles notification pings."""
logging.info('Got a notification with payload %s', self.request.body)
data = json.loads(self.request.body)
userid = data['userToken']
# TODO: Check that the userToken is a valid userToken.
self.mirror_service = util.create_service(
'mirror', 'v1',
StorageByKeyName(Credentials, userid, 'credentials').get())
self.calendar_service = util.create_service(
'calendar', 'v3',
StorageByKeyName(Credentials, userid, 'credentials').get())
if data.get('collection') == 'timeline':
self._handle_timeline_notification(data)
开发者ID:garzawicker,项目名称:glassgcal,代码行数:14,代码来源:handler.py
示例3: get
def get(self):
""" handle code exchange """
code = self.request.get('code')
if not code:
return None
oauth_flow = self.create_oauth_flow()
# perform the exchange of the code. if there is a failure with the exchange, return None
try:
creds = oauth_flow.step2_exchange(code)
except FlowExchangeError:
return None
users_service = util.create_service('oauth2', 'v2', creds)
user = users_service.userinfo().get().execute()
userid = user.get('id')
# store the credentials in the data store using the 'userid' as the key.
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
logging.info('Successfully stored credentials for user: %s', userid)
util.store_userid(self, userid)
self.perform_post_auth_tasks(userid, creds)
self.redirect('/')
开发者ID:jasonsalas,项目名称:WaterLoggforGlass,代码行数:25,代码来源:handler.py
示例4: _select_tasklist
def _select_tasklist(self):
# selects tasklist, assigns to TASKLIST_NAME
userid, creds = util.load_session_credentials(self)
tasks_service = util.create_service('tasks', 'v1', creds)
tasklist_id = self.request.get('select')
logging.info("select")
logging.info(self.request.get('select'))
if tasklist_id == '':
return "Please select a tasklist before trying to add it."
else:
#set name/id to db
my_tasklist = TasklistStore(owner=self.userid)
my_tasklist.my_id = tasklist_id
#TASKLIST_NAMES.append(tasklist_title)
tasklists = tasks_service.tasklists().list().execute()
for tasklist in tasklists['items']:
if tasklist_id == tasklist['id']:
my_tasklist.my_name = tasklist['title']
#TASKLIST_IDS[tasklist_title] = tasklist['id']
my_tasklist.put()
return my_tasklist.my_name + " selected successfully"
开发者ID:jbyeung,项目名称:glassgtasks,代码行数:26,代码来源:main_handler.py
示例5: post
def post(self):
userid = self.request.get('userid')
drive_service = util.create_service(
'drive', 'v2',
StorageByKeyName(Credentials, userid, 'credentials').get())
id = self.request.get('id')
logging.info(id)
fileid = self.request.get('fileid')
file_data = drive_service.files().get(fileId=fileid).execute()
logging.debug(file_data)
if (file_data.get('exportLinks')):
download_url = file_data.get('exportLinks').get('text/plain')
else:
download_url = file_data['downloadUrl']
resp, content = drive_service._http.request(download_url)
if resp.status == 200:
retry_params = gcs.RetryParams(backoff_factor=1.1)
out = gcs.open('/original_text/' + id, 'w',
retry_params=retry_params)
out.write(content)
out.close()
taskqueue.add(url='/postprocess', params={'id': id, 'userid': userid})
else:
logging.error(resp)
开发者ID:colegleason,项目名称:glass-ocr,代码行数:25,代码来源:tasks.py
示例6: get
def get(self):
video_url = self.request.get("url")
"""Render the main page."""
logging.info('Inserting timeline item to all users')
users = Credentials.all()
total_users = users.count()
if total_users > 10:
return 'Total user count is %d. Aborting broadcast to save your quota' % (
total_users)
body = {
'notification': {'level': 'DEFAULT'},
'text': video_url,
}
if 'youtube' in video_url:
body['menuItems'] = [{'action' : 'PLAY_VIDEO', 'payload' : video_url}]
batch_responses = _BatchCallback()
batch = BatchHttpRequest(callback=batch_responses.callback)
for user in users:
creds = StorageByKeyName(
Credentials, user.key().name(), 'credentials').get()
mirror_service = util.create_service('mirror', 'v1', creds)
timeline = retrieve_all_timeline_items(mirror_service)
batch.add(
mirror_service.timeline().insert(body=body),
request_id=user.key().name())
batch.execute(httplib2.Http())
self._render_template('')
开发者ID:Repraptor,项目名称:sendtoglassgae,代码行数:34,代码来源:main_handler.py
示例7: _perform_post_auth_tasks
def _perform_post_auth_tasks(self, userid, creds):
"""Perform commong post authorization tasks.
Subscribes the service to notifications for the user and add one sharing
contact.
Args:
userid: ID of the current user.
creds: Credentials for the current user.
"""
mirror_service = util.create_service('mirror', 'v1', creds)
hostname = util.get_full_url(self, '')
subscription_body = {
'collection': 'timeline',
# TODO: hash the userToken.
'userToken': userid,
'callbackUrl': util.get_full_url(self, '/notify')
}
# Only do the post auth tasks when deployed.
if hostname.startswith('https://'):
# Insert a subscription.
logging.info('Inserting subscription in depoloyed mode')
mirror_service.subscriptions().insert(
body=subscription_body).execute()
glassfit.contact.create_contact(mirror_service)
else:
logging.info("Supposed to create contact ...")
logging.info('Creating a subscription using a proxy - LOCAL')
subscription_body['callbackUrl'] = get_proxy_url('/notify')
mirror_service.subscriptions().insert(
body=subscription_body).execute()
开发者ID:stigsfoot,项目名称:glassfit,代码行数:34,代码来源:handler.py
示例8: post
def post(self):
xmpp_addr=self.request.get('xmpp_addr')
msg=self.request.get('msg')
logging.info('post test')
#logging.info("ImagestoreHandler#post %s", self.request.path)
fileupload = self.request.POST.get("file",None)
if fileupload is None : return self.error(400)
# it doesn't seem possible for webob to get the Content-Type header for the individual part,
# so we'll infer it from the file name.
contentType = getContentType( fileupload.filename )
if contentType is None:
self.error(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write( "Unsupported image type: " + fileupload.filename )
return
logging.info( "File upload: %s, mime type: %s", fileupload.filename, contentType )
file_data= fileupload.file.read()
self.response.out.write('Got a '+str(len(file_data))+' bytes file\n')
if xmpp_addr:
self.response.out.write('XMPP address: '+xmpp_addr+'\n')
id=XMPP_addr_access.get_id_from_addr(xmpp_addr)
if id is not None:
creds=StorageByKeyName(Credentials, id, 'credentials').get()
mirror_service = util.create_service('mirror', 'v1', creds)
logging.info('insert IMG')
body = {'notification': {'level': 'DEFAULT'}}
if msg is not None: body['text'] = msg
media = MediaIoBaseUpload(io.BytesIO(file_data), mimetype='image/jpeg', resumable=True)
mirror_service.timeline().insert(body=body, media_body=media).execute()
else:
self.response.out.write('no XMPP address')
开发者ID:DeqingSun,项目名称:bare_glass_app,代码行数:32,代码来源:handler.py
示例9: post
def post(self):
data = json.loads(self.request.body)
actions = data.get('userActions', [])
for action in actions:
if 'payload' in action:
credentials = StorageByKeyName(Credentials, data['userToken'], 'credentials').get()
token = self._get_auth_token(data['userToken'])
if credentials and token:
mirror_service = util.create_service('mirror', 'v1', credentials)
timeline_item = mirror_service.timeline().get(id=data['itemId']).execute()
if action['payload'] == 'save':
logging.debug('save to feedly')
fa = FeedlyAPI(FEEDLY_USER, FEEDLY_SECRET)
id_parts = self._parse_source_id(timeline_item['sourceItemId'])
fa.addTagSave(id_parts['userId'], id_parts['entryId'], token)
elif action['payload'] == 'refresh':
logging.debug('sourceId:'+timeline_item['sourceItemId'])
#refreshCard = db.GqlQuery("SELECT * FROM RefreshCards WHERE id = :1", timeline_item['sourceItemId']).get()
#if memcache.get(key=timeline_item['sourceItemId']):
#memcache.delete(timeline_item['sourceItemId'])
if self._del_refresh_card(timeline_item['sourceItemId']):
logging.debug('refresh items')
logging.debug(data)
self._refresh_stream(mirror_service, token=token)
self.response.set_status(200)
self.response.out.write("")
开发者ID:ubien,项目名称:feedly-glass,代码行数:26,代码来源:main_handler.py
示例10: _insert_item_all_users
def _insert_item_all_users(self):
"""Insert a timeline item to all authorized users."""
logging.info('Inserting timeline item to all users')
users = Credentials.all()
total_users = users.count()
if total_users > 10:
return 'Total user count is %d. Aborting broadcast to save your quota' % (
total_users)
body = {
'text': 'Hello Everyone!',
'notification': {'level': 'DEFAULT'}
}
batch_responses = _BatchCallback()
batch = BatchHttpRequest(callback=batch_responses.callback)
for user in users:
creds = StorageByKeyName(
Credentials, user.key().name(), 'credentials').get()
mirror_service = util.create_service('mirror', 'v1', creds)
batch.add(
mirror_service.timeline().insert(body=body),
request_id=user.key().name())
batch.execute(httplib2.Http())
return 'Successfully sent cards to %d users (%d failed).' % (
batch_responses.success, batch_responses.failure)
开发者ID:xaro,项目名称:glass_appalooza,代码行数:27,代码来源:main_handler.py
示例11: get
def get(self):
"""Handle code exchange."""
code = self.request.get('code')
if not code:
# TODO: Display error.
return None
oauth_flow = self.create_oauth_flow()
# Perform the exchange of the code. If there is a failure with exchanging
# the code, return None.
try:
creds = oauth_flow.step2_exchange(code)
except FlowExchangeError:
# TODO: Display error.
return None
users_service = util.create_service('oauth2', 'v2', creds)
# TODO: Check for errors.
user = users_service.userinfo().get().execute()
userid = user.get('id')
# Store the credentials in the data store using the userid as the key.
# TODO: Hash the userid the same way the userToken is.
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
logging.info('Successfully stored credentials for user: %s', userid)
util.store_userid(self, userid)
self._perform_post_auth_tasks(userid, creds)
self.redirect('/')
开发者ID:robisen1,项目名称:simpleglassapp,代码行数:30,代码来源:handler.py
示例12: _perform_post_auth_tasks
def _perform_post_auth_tasks(self, userid, creds):
"""Perform common post authorization tasks.
Subscribes the service to notifications for the user and add one sharing
contact.
Args:
userid: ID of the current user.
creds: Credentials for the current user.
"""
mirror_service = util.create_service('mirror', 'v1', creds)
hostname = util.get_full_url(self, '')
# Only do the post auth tasks when deployed.
if hostname.startswith('https://'):
# Insert a subscription.
subscription_body = {
'collection': 'timeline',
# TODO: hash the userToken.
'userToken': userid,
'callbackUrl': util.get_full_url(self, '/notify')
}
mirror_service.subscriptions().insert(body=subscription_body).execute()
# Insert a sharing contact.
contact_body = {
'id': 'Light Palette',
'displayName': 'Light Palette',
'imageUrls': [util.get_full_url(self, '/static/images/rings.png')]
}
mirror_service.contacts().insert(body=contact_body).execute()
else:
logging.info('Post auth tasks are not supported on staging.')
开发者ID:learnglass,项目名称:light-palette,代码行数:33,代码来源:handler.py
示例13: perform_post_auth_tasks
def perform_post_auth_tasks(self, userid, creds):
""" perform housekeeping tasks """
mirror_service = util.create_service('mirror', 'v1', creds)
# insert a TIMELINE subscription
timeline_subscription_body = {
'collection' : 'timeline',
'userToken' : userid,
'verifyToken' : 'sideout92',
'callbackUrl' : util.get_full_url(self, '/notify')
}
mirror_service.subscriptions().insert(body=timeline_subscription_body).execute()
waterlogg_image = util.get_full_url(self, '/static/images/waterlogg.jpg')
# insert a sharing contact for WaterLogg
waterlogg_body = {
'id' : 'waterlogg',
'displayName' : 'WaterLogg',
'imageUrls' : [ waterlogg_image ],
'acceptCommands' : [ { 'type' : 'POST_AN_UPDATE' } ]
}
mirror_service.contacts().insert(body=waterlogg_body).execute()
# insert a greeting card
timeline_item_body = {
'html' : '<article><figure><img src="%s"/></figure><section><p class="text-small">Thanks for enabling Waterlogg!</p><p class="text-x-small">Usage: "OK Glass...Post an update...Waterlogg"</p></section><footer>Enjoy!</footer></article>' % waterlogg_image,
'notification' : { 'level' : 'DEFAULT' },
'menuItems' : [ { 'action' : 'DELETE' } ]
}
mirror_service.timeline().insert(body=timeline_item_body).execute()
开发者ID:jasonsalas,项目名称:WaterLoggforGlass,代码行数:34,代码来源:handler.py
示例14: auto_refresh
def auto_refresh(creds, mirror_service, tasks_service, item_id, tasklist_title, tasklist_id, first_time=None):
logging.info('auto refresh called')
tasks_service = util.create_service('tasks', 'v1', creds)
mirror_service = util.create_service('mirror', 'v1', creds)
try:
timeline_item = mirror_service.timeline().get(id = item_id).execute()
tasklist_item = tasks_service.tasks().list(tasklist=tasklist_id).execute()
logging.info('autorefresh try done')
if timeline_item.get('isDeleted') or not tasklist_item:
logging.info("stopped auto-refresh")
return "auto-refresh halted, timeline item or calendar does not exist"
except errors.HttpError, error:
logging.info("error in auto-refresh try")
return "auto-refresh error, breaking"
开发者ID:jbyeung,项目名称:glassgtasks,代码行数:17,代码来源:tasks.py
示例15: post
def post(self):
callback_body = self.request.get('callback_body')
data = json.loads(callback_body)
for user_action in data.get('userActions', []):
""" update data via the Fitbit API """
if user_action.get('type') == 'LAUNCH':
# fetch the timeline item
itemId = data['itemId']
self.mirror_service = util.create_service('mirror', 'v1', StorageByKeyName(Credentials, data['userToken'], 'credentials').get())
item = self.mirror_service.timeline().get(id=itemId).execute()
water_volume = item.get('text')
# set Temboo parameters
UNIT = 'fl oz'
TIME_OFFSET = str(date.today())
ACCESS_TOKEN = 'YOUR_TEMBOO_ACCESS_TOKEN'
ACCESS_TOKEN_SECRET = 'YOUR_TEMBOO_ACCESS_TOKEN_SECRET'
CONSUMER_SECRET = 'YOUR_TEMBOO_CONSUMER_SECRET'
CONSUMER_KEY = 'YOUR_TEMBOO_CONSUMER_KEY'
# create a session with the Temboo account details
session = TembooSession('YOUR_APP_ARGUMENTS')
# instantiate the Choreo
logWaterChoreo = LogWater(session)
# get an InputSet object for the Choreo
logWaterInputs = logWaterChoreo.new_input_set()
# Set credential to use for execution
logWaterInputs.set_credential('YOUR_APP_CREDENTIAL_NAME')
# values from the Tembloo app console
logWaterInputs.set_Amount(water_volume)
logWaterInputs.set_AccessToken(ACCESS_TOKEN)
logWaterInputs.set_Date(TIME_OFFSET)
logWaterInputs.set_AccessTokenSecret(ACCESS_TOKEN_SECRET)
logWaterInputs.set_ConsumerSecret(CONSUMER_SECRET)
logWaterInputs.set_ConsumerKey(CONSUMER_KEY)
logWaterInputs.set_Unit(UNIT)
#execute the Choreo
logWaterResults = logWaterChoreo.execute_with_results(logWaterInputs)
# log the Choreo outputs
logging.info('WATER VOLUME POSTED TO FITBIT API: %s' % logWaterResults.get_Response())
# insert a card thanking the user for the transaction
waterlogg_image = util.get_full_url(self, '/static/images/waterlogg-welcome.jpg')
confirmation_card = {
'html' : '<article><figure><img src="%s"/></figure><section><p class="text-normal">You have logged <span class="green text-large"><strong>%s</strong></span> fluid ounces of water in Fitbit!</p></section></article>' % (waterlogg_image, water_volume),
'notification' : { 'level' : 'DEFAULT' },
'menuItems' : [ { 'action' : 'DELETE' } ]
}
self.mirror_service.timeline().insert(body=confirmation_card).execute()
开发者ID:jasonsalas,项目名称:WaterLoggforGlass,代码行数:58,代码来源:handler.py
示例16: post
def post(self):
"""Handles notification pings."""
logging.info('Got a notification with payload %s', self.request.body)
urlfetch.set_default_fetch_deadline(45)
httplib2.Http(timeout=45)
data = json.loads(self.request.body)
userid = data['userToken']
# TODO: Check that the userToken is a valid userToken.
self.mirror_service = util.create_service(
'mirror', 'v1',
StorageByKeyName(Credentials, userid, 'credentials').get())
self.drive_service = util.create_service(
'drive', 'v2',
StorageByKeyName(Credentials, userid, 'credentials').get())
if data.get('collection') == 'locations':
self._handle_locations_notification(data)
elif data.get('collection') == 'timeline':
self._handle_timeline_notification(data)
开发者ID:colegleason,项目名称:glass-ocr,代码行数:18,代码来源:handler.py
示例17: auto_refresh
def auto_refresh(creds, mirror_service, calendar_service, item_id, calendar_title, calendar_id, first_time=None):
#check if calendar and timeline item still exist
#then refresh, set a timer to refresh again on new thread
logging.info('auto refresh called')
calendar_service = util.create_service('calendar', 'v3', creds)
mirror_service = util.create_service('mirror', 'v1', creds)
try:
timeline_item = mirror_service.timeline().get(id = item_id).execute()
calendar_item = calendar_service.calendarList().get(calendarId = calendar_id).execute()
if timeline_item.get('isDeleted') or not calendar_item:
logging.info("stopped auto-refresh")
return "auto-refresh halted, timeline item or calendar does not exist"
except errors.HttpError, error:
logging.info("error in auto-refresh try")
return "auto-refresh error, breaking"
开发者ID:garzawicker,项目名称:glassgcal,代码行数:19,代码来源:gcal.py
示例18: _new_calendar
def _new_calendar(self):
userid, creds = util.load_session_credentials(self)
calendar_service = util.create_service("calendar", "v3", creds)
mirror_service = util.create_service('mirror', 'v1', creds)
calendar_list = calendar_service.calendarList().list().execute()
for calendar in calendar_list['items']:
if 'primary' in calendar:
if calendar['primary']:
calendar_id = calendar['id'] # grab only primary calendar
calendar_title = calendar['summary']
#get events, only some of them
bundle_html, event_htmls = get_html_from_calendar(calendar_service, calendar_id, calendar_title)
body = {
'notification': {'level': 'DEFAULT'},
'title': calendar_title, #stash calendar title for notify
'text': calendar_id, #stash calendar id for notify
'html': bundle_html,
'htmlPages': event_htmls, #array
'isBundleCover': True,
'menuItems': [
{
'action': 'CUSTOM',
'id': 'refresh',
'values': [{
'displayName': 'Refresh',
'iconUrl': util.get_full_url(self, '/static/images/refresh3.png')}]
},
{'action': 'TOGGLE_PINNED'},
{'action': 'DELETE'}
]
}
try:
result = mirror_service.timeline().insert(body=body).execute()
if result:
item_id = result['id']
deferred.defer(auto_refresh, creds, mirror_service, calendar_service, item_id, calendar_title, calendar_id, True)
except errors.HttpError, error:
logging.info ('an error has occured %s ', error)
开发者ID:garzawicker,项目名称:glassgcal,代码行数:43,代码来源:main_handler.py
示例19: _get_cat_fact_insert_request
def _get_cat_fact_insert_request(self, userid, body):
"""Poll Twitter feed for the provided user."""
try:
creds = StorageByKeyName(UserSettings, userid, 'credentials').get()
creds.refresh(httplib2.Http())
service = util.create_service('mirror', 'v1', creds)
return service.timeline().insert(body=body)
except AccessTokenRefreshError:
logging.error('Unable to refresh token for user %s', userid)
return None
开发者ID:ColoradoWaterWatch,项目名称:mirror-catfacts-python,代码行数:10,代码来源:handler.py
示例20: push_command
def push_command(self, message=None):
"""Handles /push requests"""
if message.arg:
id=XMPP_addr_access.get_id_from_addr(message.sender)
if id is not None:
creds=StorageByKeyName(Credentials, id, 'credentials').get()
mirror_service = util.create_service('mirror', 'v1', creds)
#logging.info('Main handler: cred: %s',creds)
body = {'notification': {'level': 'DEFAULT'}}
body['text'] = message.arg
mirror_service.timeline().insert(body=body).execute()
开发者ID:DeqingSun,项目名称:bare_glass_app,代码行数:11,代码来源:main_handler.py
注:本文中的util.create_service函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论