You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI中解析URL里的账户专属多级子域名?

FastAPI解析账户专属子域名方案

方法一:直接从请求对象提取主机名拆分

FastAPI的Request对象能直接获取到请求的纯主机名(不含路径部分),你可以拆分出需要的专属子域名:

from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/v1.5/")
async def read_root(request: Request):
    # 获取不含路径的完整主机名
    host = request.url.hostname
    # 拆分域名片段,假设固定根域名为domain.com
    domain_parts = host.split('.')
    # 校验格式并提取子域名
    if len(domain_parts) >= 4 and domain_parts[-2:] == ["domain", "com"]:
        acc_subdomain = domain_parts[0]
        parent_subdomain = domain_parts[1]
        return {"account": acc_subdomain, "parent": parent_subdomain}
    else:
        return {"error": "域名格式不符合要求"}
  • 核心逻辑:通过request.url.hostname拿到用户访问的纯域名(如foo123.bar456.domain.com),按.拆分后取前两个片段作为账户专属子域名。
  • 如果根域名有变动,可提前定义常量(比如ROOT_DOMAIN_SUFFIX = ["domain", "com"]),用它来校验拆分后的结尾部分,提升灵活性。

方法二:封装依赖项复用解析逻辑

如果多个接口都需要用到子域名信息,把解析逻辑做成依赖项能减少重复代码:

from fastapi import FastAPI, Request, Depends, HTTPException

app = FastAPI()
ROOT_DOMAIN = "domain.com"

async def extract_account_subdomains(request: Request):
    host = request.url.hostname
    # 校验域名是否以指定根域名结尾
    if not host.endswith(f".{ROOT_DOMAIN}"):
        raise HTTPException(status_code=400, detail="无效的访问域名")
    # 剥离根域名后拆分专属子域名
    subdomain_section = host[:-len(f".{ROOT_DOMAIN}")]
    acc_subdomain, parent_subdomain = subdomain_section.split('.')
    return {"account": acc_subdomain, "parent": parent_subdomain}

@app.get("/v1.5/")
async def read_root(account_info = Depends(extract_account_subdomains)):
    return account_info
  • 优势:统一处理域名校验和解析逻辑,所有需要子域名的接口只需注入依赖即可,维护更方便。

关键注意事项

  • 确保代理传递正确主机头:如果FastAPI服务前有Nginx等反向代理,必须配置代理传递原始Host头,比如Nginx中添加proxy_set_header Host $host;,否则request.url.hostname会拿到代理服务器的地址,而非用户实际访问的域名。
  • 增加容错处理:要考虑域名格式异常的情况(比如子域名数量不足),及时返回错误提示,避免程序抛出未处理异常。

内容的提问来源于stack exchange,提问作者Todd Curry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 06:22:26