link_shortener/app/routes.py

43 lines
1.1 KiB
Python
Raw Permalink Normal View History

from flask import render_template,redirect,request, jsonify
from app import app
import os, json
import random, string
app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)
app.view_functions['static']
SHORT_HOST = 'short.maenle.tech'
@app.route("/to/<path:short>", host=SHORT_HOST)
def short(short):
f = open('app/static/res/short.json', 'r')
data = json.load(f)
for s in data:
if s['short'] == short:
return redirect(s['path'], code=302)
return jsonify(success=False)
@app.route("/<path:path>", host=SHORT_HOST)
def long(path):
full_path = request.full_path[1:]
f = open('app/static/res/short.json', 'r')
data = json.load(f)
for s in data:
if s['path'] == full_path:
return jsonify(path="short.maenle.tech/to/"+s['short'])
letters = string.ascii_lowercase
short = ''.join(random.choice(letters) for i in range(12))
data.append({'path': full_path, 'short': short})
f = open('app/static/res/short.json', 'w')
json.dump(data, f)
f.close()
template = render_template("short.html", path="short.maenle.tech/to/"+short)
return template