Created
September 2, 2021 15:19
-
-
Save Romern/cdfa620ffe9ca6e45900054d75c0f7e3 to your computer and use it in GitHub Desktop.
simple web app which serves as a link shortener, which can give another link based on chance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, g, request, redirect | |
from datetime import datetime | |
import sqlite3 | |
import random | |
app = Flask(__name__) | |
DATABASE = "short.db" | |
SECRET = "UltraSecretCode32904235235" | |
def get_db(): | |
db = getattr(g, '_database', None) | |
if db is None: | |
db = g._database = sqlite3.connect(DATABASE) | |
cur = db.cursor() | |
cur.execute(create_table_sql) | |
return db | |
@app.teardown_appcontext | |
def close_connection(exception): | |
db = getattr(g, '_database', None) | |
if db is not None: | |
db.close() | |
create_table_sql = """ | |
CREATE TABLE IF NOT EXISTS links ( | |
id text PRIMARY KEY NOT NULL, | |
link text NOT NULL, | |
second_link text NOT NULL, | |
chance_second REAL NOT NULL, | |
submission_date text NOT NULL | |
); | |
""" | |
@app.route("/g/<id>") | |
def get_link(id): | |
cur = get_db().cursor() | |
cur.execute("SELECT * FROM links WHERE id=?", (id,)) | |
res = cur.fetchone() | |
if not res: | |
return "Not found!", 404 | |
if random.random() > res[3]: | |
return redirect(res[1]) | |
else: | |
return redirect(res[2]) | |
@app.route("/s/<id>", methods=["POST"]) | |
def set_link(id): | |
data = request.form | |
if "link" not in data or "second_link" not in data or "chance" not in data: | |
return "No link, second link or chance supplied!", 403 | |
if "secret" not in data or data["secret"]!=SECRET: | |
return "Invalid secret!", 403 | |
db = get_db() | |
cur = db.cursor() | |
try: | |
cur.execute("INSERT INTO links VALUES (?,?,?,?,?)", ( | |
id, | |
data["link"], | |
data["second_link"], | |
float(data["chance"]), | |
datetime.now().isoformat())) | |
except Exception as e: | |
return str(e), 403 | |
db.commit() | |
return "", 200 | |
if __name__ == "__main__": | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment