Some code cleanups

This commit is contained in:
sqozz 2016-02-11 21:32:42 +01:00
parent 99b747d4ba
commit 97b906730b

View file

@ -9,28 +9,29 @@ app = Flask(__name__)
@app.route('/<shortLink>', methods=['GET', 'POST']) @app.route('/<shortLink>', methods=['GET', 'POST'])
def short(shortLink=""): def short(shortLink=""):
if request.method == "GET": if request.method == "GET":
conn = sqlite3.connect("data/links.sqlite") if shortLink:
c = conn.cursor() conn = sqlite3.connect("data/links.sqlite")
result = c.execute('SELECT * FROM links WHERE shortLink=?', (shortLink, )).fetchone() c = conn.cursor()
if result: result = c.execute('SELECT * FROM links WHERE shortLink=?', (shortLink, )).fetchone()
url = result[1] conn.close()
parsedUrl = urlparse(url) if result:
if parsedUrl.scheme == "": url = result[1]
url = "http://" + url parsedUrl = urlparse(url)
return redirect(url, code=301) # Redirect to long URL saved in the database if parsedUrl.scheme == "":
url = "http://" + url
return redirect(url, code=301) # Redirect to long URL saved in the database
else:
return render_template("index.html", name=shortLink, message="Enter long URL for "+ request.url_root + shortLink+":", message_type="info") # Custom link page
else: else:
message = "" return render_template("index.html", name=shortLink) # Landing page
if len(shortLink) > 0:
message = "Enter long URL for "+ request.url_root + shortLink+":"
return render_template("index.html", name=shortLink, message=message, message_type="info") # Does the user wish to create a personel short link?
elif request.method == "POST": # Someone submitted a new link to short elif request.method == "POST": # Someone submitted a new link to short
wishId = request.form["wishId"] wishId = request.form["wishId"]
longUrl = request.form["url"] longUrl = request.form["url"]
if not wishId: if wishId:
databaseId = insertIdUnique("", longUrl)
else:
databaseId = insertIdUnique(wishId, longUrl) databaseId = insertIdUnique(wishId, longUrl)
return request.url_root + databaseId # TODO: Give the user a nice site where he can see his short URL else:
databaseId = insertIdUnique("", longUrl)
return request.url_root + databaseId # Short link in plain text
def insertIdUnique(idToCheck, longUrl): def insertIdUnique(idToCheck, longUrl):
hashUrl = hashlib.sha256(longUrl.encode()).digest() hashUrl = hashlib.sha256(longUrl.encode()).digest()