Skip to content

Commit 3c4fe55

Browse files
committed
implemented url shortened with flask
1 parent c0bd76e commit 3c4fe55

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

URL SHORTENER/app.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from flask import Flask, render_template, request, redirect, flash, url_for
2+
import string
3+
import random
4+
5+
app = Flask(__name__)
6+
app.secret_key = 'your_secret_key' # Change this to a secure secret key
7+
8+
# Dictionary to store URL mappings (short URL to long URL)
9+
url_dict = {}
10+
11+
@app.route('/')
12+
def index():
13+
return render_template('index.html')
14+
15+
@app.route('/shorten', methods=['POST'])
16+
def shorten():
17+
long_url = request.form.get('long_url')
18+
19+
# Generate a random 6-character short URL
20+
short_url = generate_short_url()
21+
22+
# Store the mapping in the dictionary
23+
url_dict[short_url] = long_url
24+
25+
return render_template('shortened.html', short_url=short_url)
26+
27+
@app.route('/<short_url>')
28+
def redirect_to_long_url(short_url):
29+
if short_url in url_dict:
30+
long_url = url_dict[short_url]
31+
return redirect(long_url)
32+
else:
33+
flash('Short URL not found.')
34+
return redirect(url_for('index'))
35+
36+
def generate_short_url():
37+
characters = string.ascii_letters + string.digits
38+
return ''.join(random.choice(characters) for _ in range(6))
39+
40+
if __name__ == '__main__':
41+
app.run(debug=True)

URL SHORTENER/templates/index.html

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>URL Shortener</title>
5+
</head>
6+
<body>
7+
<h1>URL Shortener</h1>
8+
<form method="POST" action="/shorten">
9+
<label for="long_url">Enter a URL to shorten:</label>
10+
<input type="url" name="long_url" required>
11+
<input type="submit" value="Shorten">
12+
</form>
13+
</body>
14+
</html>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>Shortened URL</title>
5+
</head>
6+
<body>
7+
<h1>Your shortened URL:</h1>
8+
<p><a href="{{ url_for('redirect_to_long_url', short_url=short_url) }}">{{ url_for('redirect_to_long_url', short_url=short_url) }}</a></p>
9+
</body>
10+
</html>

0 commit comments

Comments
 (0)