BELOW IS MY PYTHON CODE
import random
import string
from flask import Flask, render_template, redirect, request
app = Flask(__name__)
shortened_urls = {}
def generate_short_url(length=6):
chars = string.ascii_letters + string.digits
short_url = "".join(random.choice(chars) for _ in range(length))
return short_url
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
long_url = request.form['long_url']
short_url = generate_short_url()
while short_url in shortened_urls:
short_url = generate_short_url()
shortened_urls[short_url] = long_url
return f"Shortened URL: {request.url_root}{short_url}"
return render_template("index.html")
@app.route("/<short_url")
def redirect_url(short_url):
long_url = shortened_urls.get(short_url)
if long_url:
return redirect(long_url)
else:
return "URL NOT FOUND", 404
if __name__ == '__main__':
app.run(debug=True)
BELOW IS THE HTML FILE( index.html )
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>URL SHORTNER</title>
</head>
<body>
<h1>URL SHORTNER</h1>
<form method="POST" action="{{url_for('index)}}">
<input type="text" name="long_url" placeholder="Enter the long url">
<button type="submit">SHORTEN</button>
</form>
</body>
</html>
I am trying to make a url shortener to local host and it is showing me the error
Error is posted as below:
Traceback (most recent call last):
File "/Users/tanishqvernela/PycharmProjects/URL_SHORTNER/LOCAL HOST/main.py", line 29, in <module>
@app.route("/<short_url")
^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/tanishqvernela/PycharmProjects/URL_SHORTNER/venv/lib/python3.12/site-packages/flask/sansio/scaffold.py", line 362, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/Users/tanishqvernela/PycharmProjects/URL_SHORTNER/venv/lib/python3.12/site-packages/flask/sansio/scaffold.py", line 47, in wrapper_func
return f(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/tanishqvernela/PycharmProjects/URL_SHORTNER/venv/lib/python3.12/site-packages/flask/sansio/app.py", line 653, in add_url_rule
self.url_map.add(rule_obj)
File "/Users/tanishqvernela/PycharmProjects/URL_SHORTNER/venv/lib/python3.12/site-packages/werkzeug/routing/map.py", line 176, in add
rule.bind(self)
File "/Users/tanishqvernela/PycharmProjects/URL_SHORTNER/venv/lib/python3.12/site-packages/werkzeug/routing/rules.py", line 571, in bind
self.compile()
File "/Users/tanishqvernela/PycharmProjects/URL_SHORTNER/venv/lib/python3.12/site-packages/werkzeug/routing/rules.py", line 716, in compile
self._parts.extend(self._parse_rule(rule))
File "/Users/tanishqvernela/PycharmProjects/URL_SHORTNER/venv/lib/python3.12/site-packages/werkzeug/routing/rules.py", line 608, in _parse_rule
raise ValueError(f"malformed url rule: {rule!r}")
ValueError: malformed url rule: '/<short_url'
Process finished with exit code 1
1