Skip to content

Instantly share code, notes, and snippets.

@jaydeepkarale
Created June 23, 2022 12:40
Show Gist options
  • Save jaydeepkarale/150e4a58d50ef043f89d155563c0b428 to your computer and use it in GitHub Desktop.
Save jaydeepkarale/150e4a58d50ef043f89d155563c0b428 to your computer and use it in GitHub Desktop.
Ngrok & Shortening
import random
import json
import string
# get the ngrok tunnel url
def get_ngrok_url():
"""Function to get ngrok url"""
url = "http://localhost:4040/api/tunnels"
res = requests.get(url)
res_unicode = res.content.decode("utf-8")
res_json = json.loads(res_unicode)
return res_json["tunnels"][0]["public_url"]
# shorten the url by generating a 6 character code & appending to base url
def shorten_url(longurl: str):
"""Function to shorten url
:param url: The long url to be shortened
"""
ngrok_url = get_ngrok_url()
size = 6
chars = string.ascii_uppercase + string.digits
code = "".join(random.choice(chars) for _ in range(size))
short_url = ngrok_url + "/" + code
try:
cursor.execute(f"INSERT INTO URLSHORTNER VALUES (?, ?, ?)",(longurl, short_url, code,))
except Exception as ex:
print(ex)
return short_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment