repl.it
Python

A simple link shortener made with Python and Flask. Development will remain here, but hosting has been moved to Heroku.

fork
loading
Files
  • main.py
  • static
  • templates
  • links.db
  • Packager files
  • poetry.lock
  • pyproject.toml
  • requirements.txt
main.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# pyth
# by python-b5
#
# A simple link shortener made with Python and Flask.

from flask import Flask, render_template, request, redirect, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from validator_collection import checkers
import itertools
import string
import random
import os

project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format("links.db")

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)
migrate = Migrate(app, db)

class Link(db.Model):
    link = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
    target = db.Column(db.String(80), nullable=False)
    password = db.Column(db.String(80))

    def __repr__(self):
        return "<Link: {}>".format(self.link)

illegal_links = ["__repl", "__logs", "peek", "decoder", "toggle-peek", "make", "delete", "change-link", "change-target", "decode"]

def make_url():
    length = 3
    tried = []
    chars = string.ascii_lowercase + string.ascii_uppercase + string.digits

    done = False
    while not done:
        chosen = False
        while not chosen:
            link = ''.join(random.choices(chars, k=length))
            chosen = link not in tried
        
        tried.append(link)
        if Link.query.filter(Link.link == tried[-1]).first():
            length += 1
            tried = []
        elif tried == itertools.combinations(chars, length):
            done = True
    
    return tried[-1]

for link in Link.query.all():
    print("pyth link:", link.link)
    print("target link:", link.target)
    print("password:", link.password)
    print()

@app.shell_context_processor
def make_shell_context():
    return {'db': db, 'Link': Link}

@app.route('/<page>')
def go_to_page(page):
    if request.cookies.get("peek") == "1":
        return redirect("peek/" + page)
    else:
        try:
            target = Link.query.get(page).target
            return redirect(target, 301)
        except:
            return render_template("error.html") 

@app.route('/<page>/<extra>')
def go_to_page_extra(page, extra):
    if request.cookies.get("peek") == "1":
        return redirect("/peek/" + page + "/" + extra)
    else:
        try:
            target = Link.query.get(page).target
            if extra:
                if target[-1] != "/":
                    target += "/"
                target += extra
            return redirect(target, 301)
        except:
            return render_template("error.html") 

@app.route('/peek/<page>')
def peek_page(page):
    try:
        target = Link.query.get(page).target
        return render_template("peek.html", link=page, target=target)
    except:
        return render_template("error.html")

@app.route('/peek/<page>/<extra>')
def peek_page_extra(page, extra):
    try:
        target = Link.query.get(page).target
        if extra:
            if target[-1] != "/":
                target += "/"
            target += extra
        return render_template("peek.html", link=page, target=target)
    except:
        return render_template("error.html") 

@app.route('/')
def index():
	return render_template('index.html', peek="On" if request.cookies.get("peek") == "1" else "Off")

@app.route('/decoder')
def decode():
    return render_template('decode.html')

@app.route('/toggle-peek')
def toggle_peek():
    resp = make_response(redirect("/"))
    if request.cookies.get("peek") in (None, "0"):
        resp.set_cookie("peek", "1")
    elif request.cookies.get("peek") == "1":
        resp.set_cookie("peek", "0")
    return resp

@app.route('/make', defaults={'target': None, 'link': None, 'password': None})
def make_link(target, link, password):  
    if link == None:
        link = request.args.get('link') 
    if target == None:
        target = request.args.get('target')
    if password == None:
        password = request.args.get('password')
    if (not target.startswith("http://")) and (not target.startswith("https://")):
        target = "http://" + target
    if not ((link.isalnum() or not link) and password and checkers.is_url(target)):
        return render_template("input_error.html")
    if Link.query.filter(Link.link == link).first() or link in illegal_links:
        return render_template("taken.html")
    else:
        if not link:
            link = make_url()
        l = Link(link=link, target=target, password=password)
        db.session.add(l)
        db.session.commit()
        return render_template("created.html", link=link, password=password)

@app.route('/delete', defaults={'link': None, 'password': None})
def delete_link(link, password):   
    if link == None:
        link = request.args.get('link')
    if password == None:
        password = request.args.get('password')
    if not (link and password):
        return render_template("input_error.html")
    try:
        password_real = Link.query.get(link).password
        if password == str(password_real):
            Link.query.filter_by(link=link).delete()
            db.session.commit()
            return render_template("removed.html")
        else:
            return render_template("wrong.html")
    except:
        return render_template("error.html")

@app.route('/change-link', defaults={'link': None, 'password': None, 'new_link': None})
def change_link(link, password, new_link):   
    if link == None:
        link = request.args.get('link')
    if password == None:
        password = request.args.get('password')
    if new_link == None:
        new_link = request.args.get('new_link')
    if not new_link:
        new_link = make_url()
    if not ((link.isalnum() or not link) and password):
        return render_template("input_error.html")
    try:
        password_real = Link.query.get(link).password
        if password == str(password_real) and not Link.query.get(new_link):
            Link.query.get(link).link = new_link
            return render_template("changed.html")
        elif password != str(password_real):
            return render_template("wrong.html")
        elif Link.query.filter(Link.link == new_link).first() or link in illegal_links:
            return render_template("taken.html")
    except:
        return render_template("error.html")

@app.route('/change-target', defaults={'link': None, 'password': None, 'new_target': None})
def change_target(link, password, new_target):   
    if link == None:
        link = request.args.get('link')
    if password == None:
        password = request.args.get('password')
    if new_target == None:
        new_target = request.args.get('new_target')
    if (not new_target.startswith("http://")) and (not new_target.startswith("https://")):
        new_target = "http://" + new_target
    if not (link and password and checkers.is_url(new_target)):
        return render_template("input_error.html")
    try:
        password_real = Link.query.get(link).password
        if password == str(password_real):
            Link.query.get(link).link = new_link
            return render_template("changed.html")
        else:
            return render_template("wrong.html")
    except:
        return render_template("error.html")

@app.route('/decode', defaults={'link': None})
def decode_link(link):
    try:
        if link == None:
            link = request.args.get('link')
        if not link:
            return render_template("input_error.html")
        target = Link.query.get(link).target
        return render_template("decoded.html", target=target)
    except:
        return render_template("error.html")

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080)
Fetching token
?