first commit
This commit is contained in:
@@ -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)
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>URL Shortener</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>URL Shortener</h1>
|
||||||
|
<form action="/shorten" method="POST">
|
||||||
|
<input type="text" name="url" placeholder="Enter URL" required>
|
||||||
|
<button type="submit">Shorten</button>
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user