本文整理汇总了Python中inc.Commons.Commons.load_url_json方法的典型用法代码示例。如果您正苦于以下问题:Python Commons.load_url_json方法的具体用法?Python Commons.load_url_json怎么用?Python Commons.load_url_json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inc.Commons.Commons
的用法示例。
在下文中一共展示了Commons.load_url_json方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_load_url_json
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def test_load_url_json(self):
url1 = "https://httpbin.org/get"
data1 = Commons.load_url_json(url1)
assert "args" in data1, "Element missing from json dict response."
assert "headers" in data1, "Element missing from json dict response."
assert "origin" in data1, "Element missing from json dict response."
assert "url" in data1, "Element missing from json dict response."
assert data1["url"] == url1, "JSON data incorrect."
url2 = "https://httpbin.org/headers"
headers2 = [["User-Agent", "Example data"]]
data2 = Commons.load_url_json(url2, headers2)
assert "headers" in data2, "Element missing from json response dict."
assert "User-Agent" in data2["headers"], "Header missing from request."
assert data2["headers"]["User-Agent"] == "Example data", "Header data missing from request."
示例2: run
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def run(self, line, user_obj, destination_obj=None):
input_clean = line.strip().lower()
url = "http://api.randomuser.me/0.6/?nat=gb&format=json"
# Get api response
json_dict = Commons.load_url_json(url)
user_dict = json_dict['results'][0]['user']
# Construct response
name = (user_dict['name']['title'] + " " + user_dict['name']['first'] + " " + user_dict['name']['last']).title()
email = user_dict['email']
address = user_dict['location']['street'].title() + ", "
address += user_dict['location']['city'].title() + ", "
address += user_dict['location']['postcode']
username = user_dict['username']
password = user_dict['password']
date_of_birth = Commons.format_unix_time(int(user_dict['dob']))
phone_home = user_dict['phone']
phone_mob = user_dict['cell']
national_insurance = user_dict['NINO']
pronoun = "he" if user_dict['gender'] == "male" else "she"
pronoun_possessive = "his" if user_dict['gender'] == "male" else "her"
if input_clean not in ["more", "full", "verbose", "all"]:
output = "I have generated this person: Say hello to " + name + ". "
output += pronoun.title() + " was born at " + date_of_birth + "."
return output
output = "I have generated this person: Say hello to " + name + ". "
output += pronoun.title() + " was born at " + date_of_birth + " and lives at " + address + ". "
output += pronoun.title() + " uses the email " + email + ", the username \"" + username + \
"\" and usually uses the password \"" + password + "\". "
output += pronoun_possessive.title() + " home number is " + phone_home + " but "
output += pronoun_possessive + " mobile number is " + phone_mob + ". "
output += pronoun_possessive + " national insurance number is " + national_insurance + "."
return output
示例3: run
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def run(self, event):
api_key = event.server.hallo.get_api_key("thecatapi")
if api_key is None:
return event.create_response("No API key loaded for cat api.")
url = "http://thecatapi.com/api/images/get?format=json&api_key={}&type=gif".format(api_key)
cat_obj = Commons.load_url_json(url)[0]
cat_url = cat_obj["url"]
return event.create_response(cat_url)
示例4: get_random_link_result
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def get_random_link_result(self, search):
"""Gets a random link from the e621 api."""
line_clean = search.replace(' ', '%20')
url = 'https://e621.net/post/index.json?tags=order:random%20score:%3E0%20' + line_clean + '%20&limit=1'
return_list = Commons.load_url_json(url)
if len(return_list) == 0:
return None
else:
result = return_list[0]
return result
示例5: passive_trigger
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def passive_trigger(self, evt):
"""
:type evt: Event.Event
:rtype: None
"""
duo = Commons.load_url_json("https://www.duolingo.com/users/{}".format(self.username))
result = dict()
for lang in duo["language_data"]:
for friend in duo["language_data"][lang]["points_ranking_data"]:
result[friend["username"]] = friend["points_data"]["total"]
result_str = json.dumps(result)
d = (evt.get_send_time() - timedelta(1)).date()
self.save_data(result, d)
# Send date to destination
self.message_channel(result_str)
示例6: read_field
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def read_field(self, dailys_field, data_date):
"""
Save given data in a specified column for the current date row.
:type dailys_field: DailysField
:type data_date: date
:rtype: dict | None
"""
if dailys_field.type_name is None:
raise DailysException("Cannot read from unassigned dailys field")
data = Commons.load_url_json(
"{}/stats/{}/{}/".format(self.dailys_url, dailys_field.type_name, data_date.isoformat())
)
if len(data) == 0:
return None
return data[0]['data']
示例7: check
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def check(self):
url = "https://www.reddit.com/r/{}/new.json".format(self.subreddit)
results = Commons.load_url_json(url)
return_list = []
new_last_ten = []
for result in results["data"]["children"]:
result_id = result["data"]["name"]
# If post hasn't been seen in the latest ten, add it to returned list.
if result_id not in self.latest_ids:
new_last_ten.append(result_id)
return_list.append(result)
else:
break
self.latest_ids = (self.latest_ids + new_last_ten[::-1])[-10:]
# Update check time
self.last_check = datetime.now()
return return_list
示例8: run
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def run(self, event):
# Get dailys repo
hallo = event.server.hallo
function_dispatcher = hallo.function_dispatcher
sub_check_function = function_dispatcher.get_function_by_name("dailys")
sub_check_obj = function_dispatcher.get_function_object(sub_check_function) # type: Dailys
dailys_repo = sub_check_obj.get_dailys_repo(hallo)
# Check if there's already a spreadsheet here
if dailys_repo.get_by_location(event) is not None:
return event.create_response("There is already a dailys API configured in this location.")
# Create new spreadsheet object
clean_input = event.command_args.strip()
spreadsheet = DailysSpreadsheet(event.user, event.channel, clean_input)
# Check the stats/ endpoint returns a list.
resp = Commons.load_url_json(clean_input)
if not isinstance(resp, list):
return event.create_response("Could not locate Dailys API at this URL.")
# Save the spreadsheet
dailys_repo.add_spreadsheet(spreadsheet)
dailys_repo.save_json()
# Send response
return event.create_response("Dailys API found, currently with data for {}.".format(resp))
示例9: get_youtube_playlist
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def get_youtube_playlist(self, playlist_id, page_token=None):
"""Returns a list of video information for a youtube playlist."""
list_videos = []
# Get API key
api_key = self.hallo_obj.get_api_key("youtube")
if api_key is None:
return []
# Find API url
api_fields = "nextPageToken,items(snippet/title,snippet/resourceId/videoId)"
api_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=" + \
playlist_id + "&fields=" + urllib.parse.quote(api_fields) + "&key=" + api_key
if page_token is not None:
api_url += "&pageToken=" + page_token
# Load API response (in json).
api_dict = Commons.load_url_json(api_url)
for api_item in api_dict['items']:
new_video = {'title': api_item['snippet']['title'], 'video_id': api_item['snippet']['resourceId']['videoId']}
list_videos.append(new_video)
# Check if there's another page to add
if "nextPageToken" in api_dict:
list_videos.extend(self.get_youtube_playlist(playlist_id, api_dict['nextPageToken']))
# Return list
return list_videos
示例10: check_subscription
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def check_subscription(self):
"""
Checks the search for any updates
:return: List of new results
"""
search = self.search+" order:-id" # Sort by id
if len(self.latest_ten_ids) > 0:
oldest_id = min(self.latest_ten_ids)
search += " id:>"+str(oldest_id) # Don't list anything older than the oldest of the last 10
url = "http://e621.net/post/index.json?tags=" + urllib.parse.quote(search) + "&limit=50"
results = Commons.load_url_json(url)
return_list = []
new_last_ten = set(self.latest_ten_ids)
for result in results:
result_id = result["id"]
# Create new list of latest ten results
new_last_ten.add(result_id)
# If post hasn't been seen in the latest ten, add it to returned list.
if result_id not in self.latest_ten_ids:
return_list.append(result)
self.latest_ten_ids = sorted(list(new_last_ten))[::-1][:10]
# Update check time
self.last_check = datetime.now()
return return_list
示例11: _check_duo_username
# 需要导入模块: from inc.Commons import Commons [as 别名]
# 或者: from inc.Commons.Commons import load_url_json [as 别名]
def _check_duo_username(username):
try:
Commons.load_url_json("https://www.duolingo.com/users/{}".format(username))
return True
except HTTPError:
return False