简体   繁体   English

Python CGI替代PHP的标头功能?

[英]Python CGI replacement for PHP's header function?

So i found this thread: 所以我找到了这个线程:

Python replacement for PHP's header Python替换PHP标头

but i still couldn't find my answer, i don't understand the first answer because i don't use Django and i want to use pure python (I'm using CGI) 但我仍然找不到答案,我不明白第一个答案,因为我不使用Django,而我想使用纯python(我正在使用CGI)

the second answer also doesn't give details, i tried using start_response() but i couldn't get it to redirect to my url, maybe i was giving it the wrong arguments 第二个答案也没有给出详细信息,我尝试使用start_response()但是我无法将其重定向到我的网址,也许我给了它错误的参数

also i found another topic: 我也发现了另一个话题:

How to redirect a page to another page in python 3 cgi 如何在python 3 cgi中将页面重定向到另一个页面

but again the answer is still not as good as php header because it loads the entire page then redirects it which user can notice, the header function wasn't like this and was much faster and cleaner 但同样,答案仍然不如php标头,因为它会加载整个页面,然后重定向它,用户可以注意到,标头功能不是这样,并且更快,更干净

i also tried webbrowser.open() and webbrowser.get().open() 我也尝试过webbrowser.open()webbrowser.get().open()

but the problem is they open a new tab instead of loading it right there, even when i use the new=0 option! 但问题是,即使我使用new = 0选项,他们也会打开一个新标签页而不是直接在其中加载! (not to mention some weird problem that causes it to open IE as well as chrome which we have to give full path to fix) (更不用说导致它无法打开IE和chrome的一些奇怪问题了,我们必须提供完整的修复路径)

so if the best option is start_response() , can someone explain what exactly should i write? 因此,如果最好的选择是start_response() ,那么有人可以解释我该写什么吗?

what would be the equivalent of this php header: 这相当于这个php标头:

header("location: ./index.php?msg=Invalid Username or Password");

The output of a CGI script should consist of two sections, separated by a blank line. CGI脚本的输出应由两部分组成,并用空白行分隔。 The first section contains a number of headers, telling the client what kind of data is following. 第一部分包含许多标头,告诉客户端要遵循的数据类型。 Python code to generate a minimal header section looks like this: 生成最小标头部分的Python代码如下所示:

https://docs.python.org/2/library/cgi.html https://docs.python.org/2/library/cgi.html

print "Location: ./index.php?msg=Invalid+Username+or+Password"
print                               # blank line, end of headers

To trigger a redirect, it is not enough to set the location header, you must also return the right status code, like this: 要触发重定向,仅设置位置标头是不够的,还必须返回正确的状态码,如下所示:

print("Status: 302")
print("Location: ./index.php?msg=Invalid Username or Password")
print()

In PHP, you don't have to explicitly set the status because the header function does that for you if you specify a Location: header. 在PHP中,您不必显式设置状态,因为如果您指定Location:标头,则标头函数会为您完成状态设置。

The last print is necessary because the headers should be separated with blank line from the response body (which is empty in your case). 最后打印是必需的,因为标题应与响应正文(在您的情况下为空)用空白行分隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM