-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
60 lines (48 loc) · 1.94 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import argparse
import requests
from requests.exceptions import HTTPError
from urllib.parse import urlparse
from dotenv import load_dotenv
def create_arg_parser():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('link', nargs='?')
return arg_parser
def shorten_link(token, link):
body = {"long_url": link}
response = requests.post(url="https://api-ssl.bitly.com/v4/bitlinks",
headers={"Authorization": f"Bearer {token}"},
json=body)
response.raise_for_status()
short_link = response.json()["link"]
return short_link
def counted_clicks(token, link):
parsed_link = urlparse(link)
bit_link = "{0}{1}".format(parsed_link.netloc, parsed_link.path)
url = "https://api-ssl.bitly.com/v4/bitlinks/{}/clicks/summary".format(bit_link)
response = requests.get(url=url, headers={"Authorization": f"Bearer {token}"})
response.raise_for_status()
clicks_count = response.json()["total_clicks"]
return clicks_count
def is_bitlink(link, token):
parsed_link = urlparse(link)
bit_link = "{0}{1}".format(parsed_link.netloc, parsed_link.path)
response = requests.get(url="https://api-ssl.bitly.com/v4/bitlinks/{}".format(bit_link),
headers={"Authorization": f"Bearer {token}"})
return response.ok
def main():
load_dotenv()
token = os.getenv("BITLY_TOKEN")
arg_parser = create_arg_parser()
input_link = arg_parser.parse_args().link
try:
if is_bitlink(input_link, token):
clicks_count = counted_clicks(token, input_link)
print(f"По вашей ссылке перешли: {clicks_count} раз(а)")
else:
short_link = shorten_link(token, input_link)
print(f"Короткая ссылка: {short_link}")
except HTTPError as http_err:
print(f'HTTP ошибка: {http_err}')
if __name__ == '__main__':
main()