@app.route('/<short')
def redirect_to(short):
with sqlite3.connect(DB) as conn:
cur = conn.cursor()
cur.execute(SELECT long FROM urls WHERE short=?, (short,))
row = cur.fetchone()
if row:
return redirect(row[0], code=302)
return Not found, 404
@app.route('/shorten')
def shorten():
long_url = request.args.get('url')
short_code = generate_short(long_url)
with sqlite3.connect(DB) as conn:
conn.execute(INSERT OR IGNORE INTO urls (short, long) VALUES (?, ?), (short_code, long_url))
return fShort URL: https://abc.co/{short_code}
if __name__ == '__main__':
init_db()
app.run()
6、注意事项
SEO 友好性:短链接可能影响搜索引擎抓取,建议添加 `<meta rel=canonical` 标签。
HTTPS 支持:确保短域名启用 HTTPS,避免浏览器标记为不安全。
法律合规:防止用户利用短链接传播恶意内容(需审核或过滤)。