Skip to content

Instantly share code, notes, and snippets.

@TheRealRyGuy
Last active March 12, 2024 21:49
Show Gist options
  • Save TheRealRyGuy/1bf2aac13fdbcf39a98842a66ed2ee9a to your computer and use it in GitHub Desktop.
Save TheRealRyGuy/1bf2aac13fdbcf39a98842a66ed2ee9a to your computer and use it in GitHub Desktop.
Challenge my teacher gave me - make a quick HTTP server to serve as a link shortener using redis and Python. Spedran it in well under an hour not knowing how to use Redis at all
{% block content %}
<form action='/url/post' method="post">
<p>URL: <input type="url" name="url"></p>
<p><button type="submit">Shorten your URL!</button></p>
</form>
{% endblock %}
from flask import Flask, request, redirect, render_template
import redis
import random
import time
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
characters = "abcdefghijklmnopqrstuvwxyz1234567890"
app = Flask(__name__)
@app.route("/")
def home():
return render_template("main.html")
@app.route("/<string:dom>/")
def slashdomain(dom):
return domain(dom)
@app.route("/<string:domain>")
def domain(domain):
if(domain in r.hgetall("links").keys()):
r.lpush(domain, int(time.time()))
return redirect(r.hgetall("links")[domain])
else:
return redirect("/")
@app.route("/<string:domain>/stats")
def stats(domain):
if(domain in r.hgetall("links").keys()):
res = "Domain: " + domain
res += "\nLong Link: " + r.hgetall("links")[domain]
entries = r.lrange(domain, 0, -1)
res += f"\nVisits: {len(entries)}"
return res
else:
return redirect("/")
@app.route("/<string:domain>/stats/")
def slashstats(dom):
return stats(dom)
@app.route("/url/post", methods=["POST"])
def url():
try:
links = r.hgetall("links")
if(request.form["url"] in links.values()):
res = {i for i in links if links[i] == request.form["url"]}
return redirect(f"/{list(res)[0]}/stats")
else:
random = randomString()
r.hset("links", random, request.form["url"])
return redirect(f"/{random}/stats")
except Exception as e:
print("EXCEPTION", repr(e))
return redirect("/")
@app.errorhandler(404)
def notfound(e):
return f"YOU BROKE IT {e}"
def randomString():
return ''.join(random.choices(population=characters, k=5))
if __name__ == '__main__':
app.run(debug = True, host="127.0.0.1", port=8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment