Skip to content

Instantly share code, notes, and snippets.

@yozx
Created July 12, 2020 18:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yozx/08a7799830da7ccfc1279e8d494354eb to your computer and use it in GitHub Desktop.
Save yozx/08a7799830da7ccfc1279e8d494354eb to your computer and use it in GitHub Desktop.
bitly_shorten_async
# Non-blocking script for shorten link via https://bit.ly Api
import asyncio
import logging
from typing import Dict, Optional
from aiohttp import ClientSession
logger = logging.getLogger('bitly_app')
logger.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
formatter = logging.Formatter(
(
'{"unix_time":%(created)s, "time":"%(asctime)s", "module":"%(name)s",'
' "line_no":%(lineno)s, "level":"%(levelname)s", "msg":"%(message)s"},'
)
)
ch.setFormatter(formatter)
logger.addHandler(ch)
# Get your token: https://support.bitly.com/hc/en-us/articles/230647907-How-do-I-generate-an-OAuth-access-token-for-the-Bitly-API-
TOKEN = ""
URL = 'https://api-ssl.bitly.com/v4/'
oauth = {'Authorization': f'Bearer {TOKEN}'}
async def fetch(session: ClientSession,
headers: Dict[str, str],
url: str,
payload: Dict,
endpoint: str,
method='GET',
) -> Optional[Dict]:
"""Generic get/post request"""
async with session.request(method=method,
url=f'{url}{endpoint}',
headers=headers,
json=payload) as response:
if response.status in (200, 201):
json_response = await response.json()
logger.debug(json_response)
return json_response
else:
logger.error(f"Failed to make request {response.status}")
return None
async def shorten(link: str) -> Optional[str]:
"""https://dev.bitly.com/v4_documentation.html#operation/createBitlink"""
session = ClientSession()
result = None
payload = {
"domain": "bit.ly",
"long_url": link
}
try:
result = await fetch(session, oauth, URL, payload, 'shorten', method='POST')
except Exception as exc:
logger.error(exc)
finally:
await session.close()
return result.get('link', None) if result else None
if __name__ == '__main__':
example_link = 'https://dev.bitly.com'
loop = asyncio.get_event_loop()
loop.run_until_complete(shorten(example_link))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment