From 1f22503eae8eacd28a482844a420d14595bbc01a Mon Sep 17 00:00:00 2001 From: Zezik Date: Sat, 12 Sep 2026 09:01:12 +0200 Subject: [PATCH] first commit --- main.py | 52 ++++++++++++++++++++++++++++++++++++++++++++ templates/index.html | 15 +++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 main.py create mode 100644 templates/index.html diff --git a/main.py b/main.py new file mode 100644 index 0000000..ddad3b5 --- /dev/null +++ b/main.py @@ -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'' + +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: {full_short_url}' + +@app.route('/') +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) \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..0e5420c --- /dev/null +++ b/templates/index.html @@ -0,0 +1,15 @@ + + + + + + URL Shortener + + +

URL Shortener

+
+ + +
+ + \ No newline at end of file