可以使用FastAPI和Python来实现这个解决方案。下面是一个基本的示例代码:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import random
import string

app = FastAPI()

class URL(BaseModel):
    login_url: str

url_mapping = {}

def generate_key():
    return ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))

@app.post('/')
def create_short_url(url: URL):
    key = next((k for k, v in url_mapping.items() if v == url.login_url), None)
    if key is None:
        key = generate_key()
        url_mapping[key] = url.login_url
    return {'short_url': f'http://company.com/{key}'}

@app.get('/{key}')
def redirect_to_long_url(key: str):
    if key not in url_mapping:
        raise HTTPException(status_code=404, detail='Short URL not found')
    return {'redirect_url': url_mapping[key]}

@app.get('/info/{key}')
def get_visit_count(key: str):
    count = 0
    if key in url_mapping:
        count = 1
    return {'visits': count}

在这个示例代码中,我们使用了一个字典 url_mapping 来存储长URL与短URL之间的映射关系。create_short_url 函数用于创建新的短URL,并将映射关系存储在字典中。redirect_to_long_url 函数用于处理用户访问短URL时的重定向,并返回原始URL。get_visit_count 函数用于获取特定短URL的访问次数。

请注意,这个示例代码并没有实现持久化存储,而是将映射关系存储在内存中的字典中。对于实际的应用程序,你可能需要考虑使用数据库或其他持久化存储来保存映射关系。

你可以使用以下命令来运行这个应用程序:

uvicorn main:app --reload

然后,你可以使用任何HTTP客户端工具(如curl或Postman)来测试这些API终端点。例如,你可以使用以下命令来创建新的短URL:

curl -X POST -H 'Content-Type: application/json' -d '{"login_url": "http://a.very.long.long.url/even-loging-path"}' http://localhost:8000/

希望这个示例对你有帮助!

使用FastAPI和Python构建URL缩短服务

原文地址: https://www.cveoy.top/t/topic/qp68 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录