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)✅
相关推荐
哈里谢顿19 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay2 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤2 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean2 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽2 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188962 天前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api