使用FastAPI和python解决方案实现三个API终结点满足以下需求1 应用程序应允许用户使用包含长URL的键值对的JSON正文向终端节点提交长URL2 收到请求后服务器生产一个最多五个字符的随机字符串并使用此字符串作为密钥以创建格式的缩短URL 然后应用程序应在响应正文中返回此缩短的URL状态代码为201并返回段URL的json对象。 httpcompanycomkey3 应用程序应实
from fastapi import FastAPI, HTTPException from pydantic import BaseModel import random import string
app = FastAPI()
class URL(BaseModel): long_url: str
url_db = {}
def generate_key(): return ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))
@app.post("/") def create_short_url(url: URL): long_url = url.long_url if long_url in url_db: short_url = url_db[long_url] else: short_url = generate_key() url_db[long_url] = short_url return {"short_url": f"http://company.com/{short_url}"}
@app.get("/{key}") def redirect_short_url(key: str): for long_url, short_url in url_db.items(): if short_url == key: return {"url": long_url} raise HTTPException(status_code=404, detail="Short URL not found")
@app.get("/info/{key}") def get_visit_count(key: str): for long_url, short_url in url_db.items(): if short_url == key: return {"visits": 0} raise HTTPException(status_code=404, detail="Short URL not found"
原文地址: http://www.cveoy.top/t/topic/iJH6 著作权归作者所有。请勿转载和采集!