搜索
首页后端开发Python教程使用Python Flask构建高效简洁的URL缩短服务

一、设置 Flask 应用程序

首先,为您的项目创建一个新目录并在该目录中打开一个终端。然后,运行以下命令为您的项目创建一个新的虚拟环境:

# For windows:
virtualenv venv
# For linux:
python3 -m venv venv

通过运行以下命令激活虚拟环境:

 # For windows
venv/Scripts/activate
# For linux
source venv/bin/activate

接下来,通过运行以下命令安装 Flask:

pip install Flask

在您的项目目录中创建一个名为的新文件app.py并添加以下代码以设置基本的 Flask 应用程序:

from flask import Flask, request, redirect
app = Flask(__name__)
@app.route('/')
def index():
    return 'Welcome to the URL Shortener'
if __name__ == '__main__':
    app.run(debug=True)

运行以下命令启动 Flask 开发服务器:

python app.py

在您的网络浏览器中访问http://localhost:5000以查看“欢迎使用 URL 缩短器”消息。

二、将 URL 存储在字典中

接下来,我们会将原始 URL 及其相应的缩短 URL 存储在 Python 字典中。将以下代码添加到您的app.py文件中:

url_map = {}
@app.route('/shorten', methods=['POST'])
def shorten_url():
    original_url = request.form['url']
    short_url = generate_short_url(original_url)
    url_map[short_url] = original_url
    return short_url
def generate_short_url(original_url):
    # Generate a unique short URL for the original URL
    # (We'll implement this in the next step)
    pass

三、生成唯一的短 URL

要生成唯一的短 URL,我们将使用哈希函数。哈希函数接受输入(在本例中为原始 URL)并返回固定长度的输出(短 URL)。我们将使用 SHA-1 哈希函数,它是 Pythonhashlib库的一部分。将以下代码添加到您的app.py文件中:

import hashlib
def generate_short_url(original_url):
    hash = hashlib.sha1(original_url.encode())
    short_url = hash.hexdigest()[:8]
    return short_url

四、重定向到原始 URL

最后,我们将添加一个路由,以便在用户访问缩短的 URL 时将用户重定向到原始 URL。将以下代码添加到您的app.py文件中:

@app.route(&#39;/<short_url>&#39;)
def redirect_url(short_url):
    original_url = url_map.get(short_url)
    if original_url:
        return redirect(original_url

以上是使用Python Flask构建高效简洁的URL缩短服务的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

对于循环和python中的循环时:每个循环的优点是什么?对于循环和python中的循环时:每个循环的优点是什么?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境