-
Notifications
You must be signed in to change notification settings - Fork 27
/
app.py
72 lines (56 loc) · 1.78 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import logging
from flask import Flask, json, request, redirect, render_template, make_response
from url_shortener.shorten import UrlShortener
from urllib.parse import urlparse
app = Flask(__name__)
shrt = UrlShortener()
logger = logging.getLogger()
logger.info("starting up")
# template pushing routes
@app.route("/")
def index():
return render_template("index.html")
@app.route("/404")
def missing():
return render_template("missing.html")
@app.route("/400")
def invalid():
return render_template("invalid")
# short url lookup
@app.route("/<code>")
def lookup(code):
url = shrt.lookup(code)
if not url:
return redirect("/404")
else:
return redirect(url)
# short url generation
#
# If JSON is fed, we shorten and reply in JSON as well
# If a Form is posted we reply in HTML
# Otherwise we redirect to a failure page
@app.route("/", methods=["POST"])
def shorten_url():
if request.json and "url" in request.json:
u = urlparse(request.json["url"])
if u.netloc == "":
url = "http://" + request.json["url"]
else:
url = request.json["url"]
res = shrt.shorten(url)
logger.debug("shortened %s to %s" % (url, res))
response = make_response(json.dumps(res))
response.headers["Content-Type"] = "application/json"
return response
elif request.form and "url" in request.form:
u = urlparse(request.form["url"])
if u.netloc == "":
url = "http://" + request.form["url"]
else:
url = request.form["url"]
res = shrt.shorten(url)
logger.debug("shortened %s to %s" % (url, res))
return render_template("result.html", result=res)
else:
logger.info("invalid shorten request")
return redirect("/400")