-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
71 lines (58 loc) · 2.07 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
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import random
import string
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
@app.before_first_request
def create_tables():
db.create_all()
class Urls(db.Model):
id_ = db.Column("id_", db.Integer, primary_key=True)
long = db.Column("long", db.String())
short = db.Column("short", db.String(10))
def __init__(self, long, short):
self.long = long
self.short = short
def shorten_url():
letters = string.ascii_lowercase + string.ascii_uppercase
while True:
rand_letters = random.choices(letters, k=3)
rand_letters = "".join(rand_letters)
short_url = Urls.query.filter_by(short=rand_letters).first()
if not short_url:
return rand_letters
@app.route('/', methods=['POST', 'GET'])
def home():
if request.method == "POST":
url_received = request.form["nm"]
found_url = Urls.query.filter_by(long=url_received).first()
if found_url:
return redirect(url_for("display_short_url", url=found_url.short))
else:
short_url = shorten_url()
print(short_url)
new_url = Urls(url_received, short_url)
db.session.add(new_url)
db.session.commit()
return redirect(url_for("display_short_url", url=short_url))
else:
return render_template('url_page.html')
@app.route('/<short_url>')
def redirection(short_url):
long_url = Urls.query.filter_by(short=short_url).first()
if long_url:
return redirect(long_url.long)
else:
return f'<h1>Url doesnt exist</h1>'
@app.route('/display/<url>')
def display_short_url(url):
return render_template('shorturl.html', short_url_display=url)
@app.route('/all_urls')
def display_all():
return render_template('all_urls.html', vals=Urls.query.all())
if __name__ == '__main__':
app.run(port=5000, debug=True)