HTTP requests error handling, adding cmdline params

This commit is contained in:
shijuleon 2018-12-25 21:31:01 +05:30
parent f0b4365f7c
commit dbfd332ca5

View file

@ -1,12 +1,27 @@
import requests
import json
import os
import sys
def write_to_file(url, fname):
with open(fname, "a") as f:
f.write(url+"\n")
def make_request(url, headers, error_type):
try:
r = requests.get(url, headers=headers)
if r.status_code:
return r, error_type
except requests.exceptions.HTTPError as errh:
print ("HTTP Error: ", errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting: ", errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error: ", errt)
except requests.exceptions.RequestException as err:
print ("Unknown error: ", err)
return None, ""
def main():
# Not sure why, but the banner messes up if i put into one print function
print(" .\"\"\"-.")
@ -19,7 +34,11 @@ def main():
print("\033[37;1m .'`-._ `.\ | J /")
print("\033[37;1m / `--.| \__/\033[0m")
username = input("\033[92;1m[\033[37;1m?\033[92;1m]\033[92;1m Input Username: \033[0m")
if len(sys.argv) > 1:
username = sys.argv[1]
else:
username = input("\033[92;1m[\033[37;1m?\033[92;1m]\033[92;1m Input Username: \033[0m")
print()
fname = username+".txt"
@ -28,7 +47,6 @@ def main():
os.remove(fname)
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Removing previous file:\033[1;37m {}\033[0m".format(fname))
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Checking username\033[0m\033[1;37m {}\033[0m\033[1;92m on: \033[0m".format(username))
raw = open("data.json", "r")
data = json.load(raw)
@ -43,10 +61,9 @@ def main():
for social_network in data:
url = data.get(social_network).get("url").format(username)
error_type = data.get(social_network).get("errorType")
r = requests.get(url, headers=headers)
r, error_type = make_request(url=url, headers=headers, error_type=error_type)
if error_type == "message":
error = data.get(social_network).get("errorMsg")
@ -75,6 +92,9 @@ def main():
else:
print("\033[37;1m[\033[91;1m-\033[37;1m]\033[92;1m {}:\033[93;1m Not Found!".format(social_network))
elif error_type == "":
print("\033[37;1m[\033[91;1m-\033[37;1m]\033[92;1m {}:\033[93;1m Error!".format(social_network))
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Saved: \033[37;1m{}\033[0m".format(username+".txt"))
main()