first commit

This commit is contained in:
2026-09-12 09:01:12 +02:00
commit 1f22503eae
2 changed files with 67 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
from flask import Flask, request, redirect, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
import string
import random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///urls.db'
db = SQLAlchemy(app)
class URLMapping(db.Model):
id = db.Column(db.Integer, primary_key=True)
original_url = db.Column(db.String(500), nullable=False)
short_url = db.Column(db.String(10), unique=True, nullable=False)
def __repr__(self):
return f'<URLMapping {self.short_url}>'
def generate_short_url():
return ''.join(random.choices(string.ascii_letters + string.digits, k=6))
@app.route('/')
def index():
return render_template('index.html')
@app.route('/shorten', methods=['POST'])
def shorten_url():
original_url = request.form['url'].strip()
if not original_url.startswith(('http://', 'https://')):
original_url = 'http://' + original_url
short_url = generate_short_url()
new_url = URLMapping(original_url=original_url, short_url=short_url)
db.session.add(new_url)
db.session.commit()
full_short_url = request.host_url + short_url
return f'Short URL: <a href="{full_short_url}">{full_short_url}</a>'
@app.route('/<short_url>')
def redirect_to_url(short_url):
url_mapping = URLMapping.query.filter_by(short_url=short_url).first()
if url_mapping:
return redirect(url_mapping.original_url)
return 'URL not found!'
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=False, host='0.0.0.0', port=80)