【问题标题】:Python redirect to URL not workingPython重定向到URL不起作用
【发布时间】:2016-05-24 01:40:55
【问题描述】:

我知道还有其他关于此的帖子,但我已经尝试了所有我能想到的方法,但仍然无法在 Linux 服务器上将简单的重定向作为 CGI 脚本工作。我尝试了 3 种不同的方法,但都没有奏效。我知道有些人会建议在导入后删除前两个打印语句,但这给了我 500 服务器错误。我要做的就是在调用这个 python CGI 脚本时让浏览器重定向到另一个 URL。

#!/usr/bin/env python
import cgi, cgitb 
print "Content-Type: text/html"
print

def go_to_url(url):
    print "HTTP/1.1 302 Found"
    print "Location: ",url,"\r\n"
    print "Connection: close \r\n"
    print " "

def go_to_url2(url):
    print ('<script type="text/javascript">window.location = ' + url + ';</script>')

def go_to_url3(url):
    print '<html><head><script type="text/javascript">'
    print '<!-- function jump(){window.location = "' + url + '" } //-->'
    print '</script></head><body onLoad="jump()"></body></html>'

url = 'http://www.yahoo.com'
# go_to_url(url)    
# go_to_url2(url)   
go_to_url3(url)

【问题讨论】:

  • 我尝试了另一种使用 webbrowser 模块的解决方案,但也失败了。我知道脚本会运行,因为当我插入 Hello World 打印语句时,它会打印到屏幕上。这似乎是服务器问题,而不是代码。

标签: javascript python url redirect cgi


【解决方案1】:

我知道这是旧的,但我希望这会有所帮助。它对我有用!

print ("Status: 302 Moved")
print ("Location: http://www.somedomain.com/")
print() # HTTP says you have to have a blank line between headers and content

【讨论】:

    【解决方案2】:

    首先,重要的是要记住 HTTP 版本应该是客户端浏览器动态的,您不应该强制它。

    用于 HTTP 重定向的 JavaScript 解决方案会产生更多的性能开销。

    因为第一个请求是针对带有 JS 重定向代码的 HTML 页面,所以第二个请求是针对重定向本身(总共两个请求对一个)

    我相信您在打印 print "Content-Type: text/html" 后无法重定向。

    您的脚本应如下所示:

    #!/usr/bin/env python
    import cgi 
    
    def print_http_header():
        print "Content-type: text/html; charset=UTF-8"
        print
    
    def go_to_url(url):
        # HTTP version ( 1.0 / 1.1 / 2.0 ) should be determine by browser
        print "Status: 302 Moved"
        print "Location: %s" % url
        print
    
    def go_to_url2(url):
        print_http_header()
        print ('<script type="text/javascript">window.location = ' + url + ';</script>')
    
    def go_to_url3(url):
        print_http_header()
        print '<html><head><script type="text/javascript">'
        print '<!-- function jump(){window.location = "' + url + '" } //-->'
        print '</script></head><body onLoad="jump()"></body></html>'
    
    url = 'http://www.yahoo.com'
    # go_to_url(url)    
    # go_to_url2(url)   
    go_to_url3(url)
    

    希望对您有所帮助....

    【讨论】:

      【解决方案3】:

      我解决了。这行得通。其他需要注意的重要问题, 1.在Windows系统上开发时,一定要把行尾改成Linux格式 2. 将python文件chmod为755。

      def go_to_url(url):
          print ('<html><header><script type="text/javascript">window.location ="' + url + '";</script></header><body><p>Redirect2</p></body></html>')
      

      【讨论】:

        猜你喜欢
        • 2014-08-30
        • 1970-01-01
        • 2014-01-19
        • 2012-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多