从Python CGI脚本发送301/302重定向

2024-04-20 14:11:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找关于如何从Python中读取HTTP客户端响应的重定向的答案,但我不知道如何将301或302重定向发送回客户端。看起来这应该行得通,但我总是在身体前得到200的回复:

print("Content-Type: text/html; charset=UTF-8\n")
print("HTTP/1.1 301 Moved Permanently")
print("Location:", "https://www.google.com/")

等效的PHP代码应该是:

// Redirect the browser to Google
header("Location: https://www.google.com/", true, 301);

Tags: 答案texthttpscomhttp客户端wwwtype
1条回答
网友
1楼 · 发布于 2024-04-20 14:11:26

它是最简单的形式,没有外部库,您可以直接输出HTTP:

print('''Status: 301 Redirect
Location: {url}
Content-Type: text/html

Moved permanently to <a href="{url}">{url}</a>
'''.format(url='https://www.google.com/'))

如果您正在使用库或框架,可能有更好的方法

相关问题 更多 >