创建索引页面
我们网站的索引页面将允许用户提交要缩短的 URL。生成缩短后的 URL 后,它也会显示该 URL。此页面的 HTML 代码可在 templates/index.html 中找到。
首先,我们需要扩展 base.html 模板并创建一个表单,供用户提交他们的 URL:
{% extends "base.html" %} {% block content %}
<div class="text-center">
<h1 class="text-3xl font-bold text-gray-900 mb-8">Shorten Your URL</h1>
<form action="/" method="POST" class="w-full max-w-sm mx-auto">
<div
class="flex items-center border-2 border-blue-500 rounded overflow-hidden"
>
<input
type="text"
name="original_url"
placeholder="Enter URL"
class="appearance-none bg-transparent border-none w-full text-gray-700 py-2 px-4 leading-tight focus:outline-none"
/>
<button
type="submit"
class="bg-blue-500 hover:bg-blue-700 text-white py-2 px-4 rounded-r focus:outline-none"
>
Shorten
</button>
</div>
</form>
{% if short_url %}
<div class="mt-4">
<p class="text-lg text-gray-700">
Short URL:
<a href="{{ request.host_url }}{{ short_url }}" class="text-blue-500"
>{{ request.host_url }}{{ short_url }}</a
>
</p>
</div>
{% endif %}
</div>
{% endblock %}
在 index.html 中,我们有一个表单,其中有一个输入字段供用户输入他们的 URL。表单将提交到同一页面,因此我们将 action 属性设置为 /。我们还将 method 属性设置为 POST,以便表单数据将在请求体中发送。
现在,我们需要添加 templates/base.html:
<!doctype html>
<html>
<head>
<title>URL Shortener</title>
<link
href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css"
rel="stylesheet"
/>
</head>
<body>
<nav class="p-6 bg-white flex justify-between items-center">
<a href="/" class="text-2xl font-bold text-gray-900">URL Shortener</a>
<div>
<a href="/" class="text-gray-800 mr-6">Home</a>
<a href="/history" class="text-gray-800">History</a>
</div>
</nav>
<main class="container mx-auto max-w-xl pt-8 min-h-screen">
{% block content %} {% endblock %}
</main>
</body>
</html>
在 base.html 中,我们在页面顶部有一个导航栏,其中包含指向主页和历史记录页面的链接。我们还有一个 main 元素,它将包含每个页面的内容。content 块是每个页面的内容将被插入的地方。
我们还需要在 app.py 中添加必要的代码来处理表单提交并生成缩短后的 URL:
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
original_url = request.form["original_url"]
short_url = generate_short_url()
## Insert the original and short URLs into the database
db.execute(
"INSERT INTO urls (original_url, short_url) VALUES (?,?)",
(original_url, short_url),
)
conn.commit()
return render_template("index.html", short_url=short_url)
return render_template("index.html")
在 index() 中,我们检查请求方法是否为 POST。如果是,我们从表单数据中获取原始 URL 并生成一个短 URL。然后,我们将原始 URL 和短 URL 插入数据库,并使用短 URL 渲染 index.html 模板。