request.build_absolute_uri()用法

request.build_absolute_uri() 是 Django 中一个非常实用的方法,用于构建完整的、绝对的 URL(包含协议、域名、端口和路径)


📌 基本语法

复制代码
request.build_absolute_uri(location=None)
  • 如果 不传参数:返回当前请求的完整绝对 URL。
  • 如果 传入 location(字符串) :将 location 拼接到当前站点的根地址上,生成完整 URL。

✅ 举个例子

假设你的网站部署在:

复制代码
https://example.com:8000/myapp/
情况 1:不传参数(获取当前页面完整 URL)
复制代码
# 用户访问 https://example.com:8000/student/123/
full_url = request.build_absolute_uri()
print(full_url)
# 输出: https://example.com:8000/student/123/
情况 2:传入相对路径(常用于生成二维码、分享链接等)
复制代码
relative_path = "/student-volunteer-er/6/"
full_url = request.build_absolute_uri(relative_path)
print(full_url)
# 输出: https://example.com:8000/student-volunteer-er/6/

💡 即使你本地开发用 http://127.0.0.1:8000,它也会自动适配为 http://127.0.0.1:8000/...

部署到线上后自动变成 https://yourdomain.com/...无需硬编码域名


🔧 常见用途

场景 说明
生成二维码 二维码必须是完整 URL,不能是 /path/
发送邮件中的链接 邮件里不能用相对路径,必须是 https://...
第三方回调地址 如微信登录、支付回调,需要提供完整 URL
SEO 或 Open Graph 标签 <meta property="og:url" content="完整URL">

⚠️ 注意事项

  1. 依赖 Host 请求头

    Django 通过 request.get_host() 获取域名,而 get_host() 来自 HTTP 请求头中的 Host 字段。

    → 所以在反向代理(如 Nginx)后面时,要确保正确传递 Host 头,或设置 USE_X_FORWARDED_HOST = True

  2. 不要手动拼接 http:// + domain + path

    这样容易出错(比如忘记端口、协议是 http/https 混乱)。

    ✅ 用 build_absolute_uri() 更安全、更通用。

  3. reverse() 配合使用

    复制代码
    from django.urls import reverse
    
    relative_url = reverse('student_volunteer_erlist', kwargs={'student_id': 6})
    absolute_url = request.build_absolute_uri(relative_url)
    # 结果: https://example.com/student-volunteer-er/6/

✅ 总结

方法 返回值
request.path /student/123/(仅路径)
request.get_full_path() /student/123/?a=1(路径+查询参数)
request.build_absolute_uri() https://example.com/student/123/(完整 URL)✅
相关推荐
玄同7658 小时前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
小瑞瑞acd8 小时前
【小瑞瑞精讲】卷积神经网络(CNN):从入门到精通,计算机如何“看”懂世界?
人工智能·python·深度学习·神经网络·机器学习
火车叼位8 小时前
也许你不需要创建.venv, 此规范使python脚本自备依赖
python
火车叼位8 小时前
脚本伪装:让 Python 与 Node.js 像原生 Shell 命令一样运行
运维·javascript·python
孤狼warrior9 小时前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
Katecat996639 小时前
YOLO11分割算法实现甲状腺超声病灶自动检测与定位_DWR方法应用
python
玩大数据的龙威9 小时前
农经权二轮延包—各种地块示意图
python·arcgis
ZH15455891319 小时前
Flutter for OpenHarmony Python学习助手实战:数据库操作与管理的实现
python·学习·flutter
belldeep9 小时前
python:用 Flask 3 , mistune 2 和 mermaid.min.js 10.9 来实现 Markdown 中 mermaid 图表的渲染
javascript·python·flask
喵手9 小时前
Python爬虫实战:电商价格监控系统 - 从定时任务到历史趋势分析的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·电商价格监控系统·从定时任务到历史趋势分析·采集结果sqlite存储