本文整理汇总了Python中models.sitevar.Sitevar类的典型用法代码示例。如果您正苦于以下问题:Python Sitevar类的具体用法?Python Sitevar怎么用?Python Sitevar使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Sitevar类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _render
def _render(self):
status_sitevar_future = Sitevar.get_by_id_async('apistatus')
fmsapi_sitevar_future = Sitevar.get_by_id_async('apistatus.fmsapi_down')
down_events_sitevar_future = Sitevar.get_by_id_async('apistatus.down_events')
# Error out of no sitevar found
status_sitevar = status_sitevar_future.get_result()
if not status_sitevar:
self._errors = {"404": "API Status Not Found"}
self.abort(404)
status_dict = status_sitevar.contents
down_events_sitevar = down_events_sitevar_future.get_result()
down_events_list = down_events_sitevar.contents if down_events_sitevar else None
fmsapi_sitevar = fmsapi_sitevar_future.get_result()
status_dict['is_datafeed_down'] = True if fmsapi_sitevar and fmsapi_sitevar.contents == True else False
status_dict['down_events'] = down_events_list if down_events_list is not None else []
last_modified_times = [status_sitevar.updated]
if down_events_sitevar:
last_modified_times.append(down_events_sitevar.updated)
if fmsapi_sitevar:
last_modified_times.append(fmsapi_sitevar.updated)
self._last_modified = max(last_modified_times)
return json.dumps(status_dict, ensure_ascii=True, indent=2, sort_keys=True)
示例2: post
def post(self):
self._require_admin()
trusted_sitevar = Sitevar.get_or_insert('trustedapi')
sitevar = Sitevar.get_or_insert('apistatus')
old_value = sitevar.contents
status = {}
status['android'] = {}
status['ios'] = {}
status['max_season'] = int(self.request.get('max_year'))
status['current_season'] = int(self.request.get('current_year'))
status['android']['latest_app_version'] = int(self.request.get('android_latest_version'))
status['android']['min_app_version'] = int(self.request.get('android_min_version'))
status['ios']['latest_app_version'] = int(self.request.get('ios_latest_version'))
status['ios']['min_app_version'] = int(self.request.get('ios_min_version'))
sitevar.contents = status
sitevar.put()
trusted_status = {
1: True if self.request.get('enable_match_video') else False,
2: True if self.request.get('enable_event_teams') else False,
3: True if self.request.get('enable_event_matches') else False,
4: True if self.request.get('enable_event_rankings') else False,
5: True if self.request.get('enable_event_alliances') else False,
6: True if self.request.get('enable_event_awards') else False,
}
trusted_sitevar.contents = trusted_status
trusted_sitevar.put()
ApiStatusController.clear_cache_if_needed(old_value, status)
self.redirect('/admin/apistatus')
示例3: test_parse_2017_events_with_cmp_hacks
def test_parse_2017_events_with_cmp_hacks(self):
hack_sitevar = Sitevar(id='cmp_registration_hacks')
hack_sitevar.contents = {
"event_name_override": [
{"event": "2017cmpmo", "name": "FIRST Championship Event", "short_name": "Championship"},
{"event": "2017cmptx", "name": "FIRST Championship Event", "short_name": "Championship"}],
"set_start_to_last_day": ["2017cmptx", "2017cmpmo"],
"divisions_to_skip": ["2017arc", "2017cars", "2017cur", "2017dal", "2017dar"],
}
hack_sitevar.put()
with open('test_data/fms_api/2017_event_list.json', 'r') as f:
events, districts = FMSAPIEventListParser(2017).parse(json.loads(f.read()))
self.assertEqual(len(events), 159)
self.assertEqual(len(districts), 10)
non_einstein_types = EventType.CMP_EVENT_TYPES
non_einstein_types.remove(EventType.CMP_FINALS)
for key in hack_sitevar.contents['divisions_to_skip']:
self.assertFalse(filter(lambda e: e.key_name == key, events))
einstein_stl = next(e for e in events if e.key_name == '2017cmpmo')
self.assertIsNotNone(einstein_stl)
self.assertEqual(einstein_stl.name, "FIRST Championship Event (St. Louis)")
self.assertEqual(einstein_stl.short_name, "Championship (St. Louis)")
self.assertEquals(einstein_stl.start_date, datetime.datetime(year=2017, month=4, day=29, hour=0, minute=0, second=0))
self.assertEquals(einstein_stl.end_date, datetime.datetime(year=2017, month=4, day=29, hour=23, minute=59, second=59))
einstein_hou = next(e for e in events if e.key_name == '2017cmptx')
self.assertIsNotNone(einstein_hou)
self.assertEqual(einstein_hou.name, "FIRST Championship Event (Houston)")
self.assertEqual(einstein_hou.short_name, "Championship (Houston)")
self.assertEquals(einstein_hou.start_date, datetime.datetime(year=2017, month=4, day=22, hour=0, minute=0, second=0))
self.assertEquals(einstein_hou.end_date, datetime.datetime(year=2017, month=4, day=22, hour=23, minute=59, second=59))
示例4: post
def post(self):
self._require_admin()
google_secrets = Sitevar.get_or_insert('google.secrets')
firebase_secrets = Sitevar.get_or_insert('firebase.secrets')
fmsapi_secrets = Sitevar.get_or_insert('fmsapi.secrets')
mobile_clientIds = Sitevar.get_or_insert('mobile.clientIds')
gcm_serverKey = Sitevar.get_or_insert('gcm.serverKey')
google_key = self.request.get("google_secret")
firebase_key = self.request.get("firebase_secret")
fmsapi_user = self.request.get("fmsapi_user")
fmsapi_secret = self.request.get("fmsapi_secret")
web_client_id = self.request.get("web_client_id")
android_client_id = self.request.get("android_client_id")
ios_client_id = self.request.get("ios_client_id")
gcm_key = self.request.get("gcm_key")
google_secrets.contents = {'api_key': google_key}
firebase_secrets.contents = {'FIREBASE_SECRET': firebase_key}
fmsapi_secrets.contents = {'username': fmsapi_user, 'authkey': fmsapi_secret}
mobile_clientIds.contents = {'web': web_client_id, 'android': android_client_id,
'ios': ios_client_id}
gcm_serverKey.contents = {'gcm_key': gcm_key}
google_secrets.put()
firebase_secrets.put()
fmsapi_secrets.put()
mobile_clientIds.put()
gcm_serverKey.put()
self.redirect('/admin/authkeys')
示例5: post
def post(self, sitevar_key):
#note, we don't use sitevar_key
sitevar = Sitevar(
id = self.request.get("key"),
description = self.request.get("description"),
values_json = self.request.get("values_json"),
)
sitevar.put()
self.redirect("/admin/sitevar/edit/" + sitevar.key.id() + "?success=true")
示例6: __init__
def __init__(self, version, sim_time=None, save_response=False):
self._sim_time = sim_time
self._save_response = save_response and sim_time is None
fms_api_secrets = Sitevar.get_by_id('fmsapi.secrets')
if fms_api_secrets is None:
if self._sim_time is None:
raise Exception("Missing sitevar: fmsapi.secrets. Can't access FMS API.")
else:
fms_api_username = fms_api_secrets.contents['username']
fms_api_authkey = fms_api_secrets.contents['authkey']
self._fms_api_authtoken = base64.b64encode('{}:{}'.format(fms_api_username, fms_api_authkey))
self._is_down_sitevar = Sitevar.get_by_id('apistatus.fmsapi_down')
if not self._is_down_sitevar:
self._is_down_sitevar = Sitevar(id="apistatus.fmsapi_down", description="Is FMSAPI down?")
self.FMS_API_DOMAIN = 'https://frc-api.firstinspires.org/'
if version == 'v1.0':
FMS_API_URL_BASE = self.FMS_API_DOMAIN + 'api/v1.0'
self.FMS_API_AWARDS_URL_PATTERN = FMS_API_URL_BASE + '/awards/%s/%s' # (year, event_short)
self.FMS_API_HYBRID_SCHEDULE_QUAL_URL_PATTERN = FMS_API_URL_BASE + '/schedule/%s/%s/qual/hybrid' # (year, event_short)
self.FMS_API_HYBRID_SCHEDULE_PLAYOFF_URL_PATTERN = FMS_API_URL_BASE + '/schedule/%s/%s/playoff/hybrid' # (year, event_short)
self.FMS_API_EVENT_RANKINGS_URL_PATTERN = FMS_API_URL_BASE + '/rankings/%s/%s' # (year, event_short)
self.FMS_API_EVENT_ALLIANCES_URL_PATTERN = FMS_API_URL_BASE + '/alliances/%s/%s' # (year, event_short)
self.FMS_API_TEAM_DETAILS_URL_PATTERN = FMS_API_URL_BASE + '/teams/%s/?teamNumber=%s' # (year, teamNumber)
self.FMS_API_TEAM_AVATAR_URL_PATTERN = FMS_API_URL_BASE + '/%s/avatars/?teamNumber=%s' # (year, teamNumber)
self.FMS_API_EVENT_AVATAR_URL_PATTERN = FMS_API_URL_BASE + '/%s/avatars/?eventCode=%s&page=%s' # (year, eventCode, page)
self.FMS_API_EVENT_LIST_URL_PATTERN = FMS_API_URL_BASE + '/events/season=%s'
self.FMS_API_EVENTTEAM_LIST_URL_PATTERN = FMS_API_URL_BASE + '/teams/?season=%s&eventCode=%s&page=%s' # (year, eventCode, page)
elif version == 'v2.0':
FMS_API_URL_BASE = self.FMS_API_DOMAIN + 'v2.0'
self.FMS_API_AWARDS_URL_PATTERN = FMS_API_URL_BASE + '/%s/awards/%s' # (year, event_short)
self.FMS_API_HYBRID_SCHEDULE_QUAL_URL_PATTERN = FMS_API_URL_BASE + '/%s/schedule/%s/qual/hybrid' # (year, event_short)
self.FMS_API_HYBRID_SCHEDULE_PLAYOFF_URL_PATTERN = FMS_API_URL_BASE + '/%s/schedule/%s/playoff/hybrid' # (year, event_short)
self.FMS_API_MATCH_DETAILS_QUAL_URL_PATTERN = FMS_API_URL_BASE + '/%s/scores/%s/qual' # (year, event_short)
self.FMS_API_MATCH_DETAILS_PLAYOFF_URL_PATTERN = FMS_API_URL_BASE + '/%s/scores/%s/playoff' # (year, event_short)
self.FMS_API_EVENT_RANKINGS_URL_PATTERN = FMS_API_URL_BASE + '/%s/rankings/%s' # (year, event_short)
self.FMS_API_EVENT_ALLIANCES_URL_PATTERN = FMS_API_URL_BASE + '/%s/alliances/%s' # (year, event_short)
self.FMS_API_TEAM_DETAILS_URL_PATTERN = FMS_API_URL_BASE + '/%s/teams/?teamNumber=%s' # (year, teamNumber)
self.FMS_API_TEAM_AVATAR_URL_PATTERN = FMS_API_URL_BASE + '/%s/avatars/?teamNumber=%s' # (year, teamNumber)
self.FMS_API_EVENT_AVATAR_URL_PATTERN = FMS_API_URL_BASE + '/%s/avatars/?eventCode=%s&page=%s' # (year, eventCode, page)
self.FMS_API_EVENT_LIST_URL_PATTERN = FMS_API_URL_BASE + '/%s/events' # year
self.FMS_API_EVENT_DETAILS_URL_PATTERN = FMS_API_URL_BASE + '/%s/events?eventCode=%s' # (year, event_short)
self.FMS_API_EVENTTEAM_LIST_URL_PATTERN = FMS_API_URL_BASE + '/%s/teams/?eventCode=%s&page=%s' # (year, eventCode, page)
self.FMS_API_DISTRICT_LIST_URL_PATTERN = FMS_API_URL_BASE + '/%s/districts' # (year)
self.FMS_API_DISTRICT_RANKINGS_PATTERN = FMS_API_URL_BASE + '/%s/rankings/district?districtCode=%s&page=%s' # (year, district abbreviation, page)
else:
raise Exception("Unknown FMS API version: {}".format(version))
示例7: oauth_req
def oauth_req(self, url, http_method="GET", post_body=None,
http_headers=None):
twitter_secrets = Sitevar.get_by_id("twitter.secrets")
if not twitter_secrets:
raise Exception("Missing sitevar: twitter.secrets. Cant scrape twitter.")
TWITTER_CONSUMER_KEY = twitter_secrets.contents['TWITTER_CONSUMER_KEY']
TWITTER_CONSUMER_SECRET = twitter_secrets.contents['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS_TOKEN = twitter_secrets.contents['TWITTER_ACCESS_TOKEN']
TWITTER_ACCESS_TOKEN_SECRET = twitter_secrets.contents['TWITTER_ACCESS_TOKEN_SECRET']
consumer = oauth2.Consumer(key=TWITTER_CONSUMER_KEY, secret=TWITTER_CONSUMER_SECRET)
token = oauth2.Token(key=TWITTER_ACCESS_TOKEN, secret=TWITTER_ACCESS_TOKEN_SECRET)
client = oauth2.Client(consumer, token)
resp, content = client.request(
url,
method=http_method,
body=post_body,
headers=http_headers,
force_auth_header=True
)
return content
示例8: track_call
def track_call(api_action, api_details):
analytics_id = Sitevar.get_by_id("google_analytics.id")
if analytics_id is None:
logging.warning("Missing sitevar: google_analytics.id. Can't track API usage.")
else:
GOOGLE_ANALYTICS_ID = analytics_id.contents['GOOGLE_ANALYTICS_ID']
params = urllib.urlencode({
'v': 1,
'tid': GOOGLE_ANALYTICS_ID,
'cid': '1',
't': 'event',
'ec': 'api',
'ea': api_action,
'el': api_details,
'ev': 1,
'ni': 1
})
# Sets up the call
analytics_url = 'http://www.google-analytics.com/collect'
urlfetch.fetch(
url=analytics_url,
payload=params,
method=urlfetch.POST,
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
示例9: _render
def _render(self):
status_sitevar = Sitevar.get_by_id('apistatus')
fmsapi_sitevar = Sitevar.get_by_id('apistatus.fmsapi_down')
down_events_sitevar = Sitevar.get_by_id('apistatus.down_events')
# Error out of no sitevar found
if not status_sitevar:
self._errors = json.dumps({"404": "API Status Not Found"})
self.abort(404)
status_dict = status_sitevar.contents
down_events_list = down_events_sitevar.contents if down_events_sitevar else None
status_dict['is_datafeed_down'] = True if fmsapi_sitevar and fmsapi_sitevar.contents == True else False
status_dict['down_events'] = down_events_list if down_events_list is not None else []
return json.dumps(status_dict, ensure_ascii=True)
示例10: get
def get(self, event_key):
self._require_admin()
event = Event.get_by_id(event_key)
if not event:
self.abort(404)
event.prepAwardsMatchesTeams()
reg_sitevar = Sitevar.get_by_id("cmp_registration_hacks")
api_keys = ApiAuthAccess.query(ApiAuthAccess.event_list == ndb.Key(Event, event_key)).fetch()
event_medias = Media.query(Media.references == event.key).fetch(500)
self.template_values.update({
"event": event,
"medias": event_medias,
"cache_key": event_controller.EventDetail('2016nyny').cache_key.format(event.key_name),
"flushed": self.request.get("flushed"),
"playoff_types": PlayoffType.type_names,
"write_auths": api_keys,
"event_sync_disable": reg_sitevar and event_key in reg_sitevar.contents.get('divisions_to_skip', []),
"set_start_day_to_last": reg_sitevar and event_key in reg_sitevar.contents.get('set_start_to_last_day', []),
"skip_eventteams": reg_sitevar and event_key in reg_sitevar.contents.get('skip_eventteams', []),
"event_name_override": next(iter(filter(lambda e: e.get("event") == event_key, reg_sitevar.contents.get("event_name_override", []))), {}).get("name", "")
})
path = os.path.join(os.path.dirname(__file__), '../../templates/admin/event_details.html')
self.response.out.write(template.render(path, self.template_values))
示例11: track_call
def track_call(api_action, api_label, x_tba_app_id):
"""
For more information about GAnalytics Protocol Parameters, visit
https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
"""
analytics_id = Sitevar.get_by_id("google_analytics.id")
if analytics_id is None:
logging.warning("Missing sitevar: google_analytics.id. Can't track API usage.")
else:
GOOGLE_ANALYTICS_ID = analytics_id.contents["GOOGLE_ANALYTICS_ID"]
params = urllib.urlencode(
{
"v": 1,
"tid": GOOGLE_ANALYTICS_ID,
"cid": uuid.uuid3(uuid.NAMESPACE_X500, str(x_tba_app_id)),
"t": "event",
"ec": "api-v02",
"ea": api_action,
"el": api_label,
"cd1": x_tba_app_id, # custom dimension 1
"ni": 1,
"sc": "end", # forces tracking session to end
}
)
analytics_url = "http://www.google-analytics.com/collect?%s" % params
urlfetch.fetch(url=analytics_url, method=urlfetch.GET, deadline=10)
示例12: _render
def _render(self, event_key, webcast_number):
self.response.headers["Cache-Control"] = "public, max-age=%d" % (5 * 60)
self.response.headers["Pragma"] = "Public"
self.response.headers.add_header("content-type", "application/json", charset="utf-8")
output = {}
if not webcast_number.isdigit():
return json.dumps(output)
webcast_number = int(webcast_number) - 1
event = Event.get_by_id(event_key)
if event and event.webcast:
webcast = event.webcast[webcast_number]
if "type" in webcast and "channel" in webcast:
output["player"] = self._renderPlayer(webcast)
else:
special_webcasts_future = Sitevar.get_by_id_async("gameday.special_webcasts")
special_webcasts = special_webcasts_future.get_result()
if special_webcasts:
special_webcasts = special_webcasts.contents
else:
special_webcasts = {}
if event_key in special_webcasts:
webcast = special_webcasts[event_key]
if "type" in webcast and "channel" in webcast:
output["player"] = self._renderPlayer(webcast)
return json.dumps(output)
示例13: update_champ_numbers
def update_champ_numbers(cls, match):
champ_numbers_sitevar = Sitevar.get_or_insert(
'champ_numbers',
values_json=json.dumps({
'kpa_accumulated': 0,
'rotors_engaged': 0,
'ready_for_takeoff': 0,
}))
old_contents = champ_numbers_sitevar.contents
for color in ['red', 'blue']:
old_contents['kpa_accumulated'] += match.score_breakdown[color]['autoFuelPoints'] + match.score_breakdown[color]['teleopFuelPoints']
if match.score_breakdown[color]['rotor4Engaged']:
old_contents['rotors_engaged'] += 4
elif match.score_breakdown[color]['rotor3Engaged']:
old_contents['rotors_engaged'] += 3
elif match.score_breakdown[color]['rotor2Engaged']:
old_contents['rotors_engaged'] += 2
elif match.score_breakdown[color]['rotor1Engaged']:
old_contents['rotors_engaged'] += 1
old_contents['ready_for_takeoff'] += match.score_breakdown[color]['teleopTakeoffPoints'] / 50
champ_numbers_sitevar.contents = old_contents
champ_numbers_sitevar.put()
deferred.defer(
cls._patch_data,
'champ_numbers',
json.dumps(old_contents),
_queue="firebase")
示例14: post
def post(self):
self._require_registration()
event_key = self.request.get("event_key")
status, suggestion = SuggestionCreator.createEventMediaSuggestion(
author_account_key=self.user_bundle.account.key,
media_url=self.request.get("media_url"),
event_key=event_key)
if status == 'success':
# Send an update to the FUN slack
slack_sitevar = Sitevar.get_or_insert('slack.hookurls')
if slack_sitevar:
slack_url = slack_sitevar.contents.get('fun', '')
if slack_url:
message_body = u"{0} ({1}) has suggested a video for <https://www.thebluealliance.com/event/{2}|{2}>: https://youtu.be/{3}.\nSee all suggestions at https://www.thebluealliance.com/suggest/event/media/review".format(
self.user_bundle.account.display_name,
self.user_bundle.account.email,
event_key,
suggestion.contents['foreign_key']).encode('utf-8')
OutgoingNotificationHelper.send_slack_alert(slack_url, message_body, [])
self.redirect('/suggest/event/media?event_key=%s&status=%s' % (event_key, status))
示例15: track_call
def track_call(api_action, api_label, auth_owner):
"""
For more information about GAnalytics Protocol Parameters, visit
https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
"""
analytics_id = Sitevar.get_by_id("google_analytics.id")
if analytics_id is None:
logging.warning("Missing sitevar: google_analytics.id. Can't track API usage.")
else:
GOOGLE_ANALYTICS_ID = analytics_id.contents['GOOGLE_ANALYTICS_ID']
payload = urllib.urlencode({
'v': 1,
'tid': GOOGLE_ANALYTICS_ID,
'cid': uuid.uuid3(uuid.NAMESPACE_X500, str(auth_owner)),
't': 'event',
'ec': 'api-v03',
'ea': api_action,
'el': api_label,
'cd1': auth_owner, # custom dimension 1
'ni': 1,
'sc': 'end', # forces tracking session to end
})
urlfetch.fetch(
url='https://www.google-analytics.com/collect',
validate_certificate=True,
method=urlfetch.POST,
deadline=30,
payload=payload,
)