【问题标题】:Can python webbrowser module work with cgi?python webbrowser模块可以与cgi一起使用吗?
【发布时间】:2014-03-23 18:50:51
【问题描述】:

我正在尝试使用 python cgi 和 webbrowser 模块从 html 表单提交操作中打开一个 url。我可以在 localhost 上启动 url python -m webbrowser -t "http://myhost.com/path/to/some/file.html" 然而与 webbrowser.open(url, new=0, autoraise=True) 在我的 cgi 脚本中,apache 提供一个空白页面,并且页面上没有打印任何错误。我的 Firefox 浏览器的位置框显示“http://myhost.com/my_script.cgi?Submit=Submit”而不是目标网址。

如果不能在这种情况下使用 webbrowser 模块,我对它的实际用途感到困惑。如果我使用 url 作为表单操作,该页面将提供给客户端,但我的脚本需要处理由以前的 html 表单传递的变量,以确定 url,然后将该 url 提供给客户端。让我知道我缺少什么,谢谢。

【问题讨论】:

  • 您是否尝试在您的 CGI 脚本中运行 webbrowser 命令来代理数据以传回给用户?
  • 是的,但我从静态网址开始了解如何继续:if 'Submit' in form: url = "http://www.python.org" try: webbrowser.open(url, new=0, autoraise=True)

标签: python html python-2.7 cgi python-webbrowser


【解决方案1】:

我很确定,是的,您对 webbrowser 库应该做什么感到困惑。 如果您在 cgi 中运行 webbrowser 命令,它将尝试在运行您的 cgi 脚本的服务器上打开一个 webbrowser(就像运行 cgi 的任何用户一样)。这可能行不通。我认为您希望发生的是您的 cgi 脚本应该将适当的 HTTP“命令”返回给浏览器以使其重定向。举个例子:

if "Submit" in form:
   url = "http://www.python.org #or do whatever processing is needed to calculate the new URL
   print "Status: 302" #this tells the browser the result is a redirect
   print "Location: " + url #this tells the browser where to redirect
   print "" #send two new lines to end the HTTP header

请注意,如果您使用的是 django 或其他库(我希望甚至只是 cgi 库计数),可能有更高级别的方法来执行此操作,但这应该可以在任何地方使用。您还可以在 HTML 等中使用 META-refresh 进行操作。

【讨论】:

  • 我认为默认的python cgi行为是使用提交按钮传递的参数加载脚本的路径,所以我在浏览器的位置栏中看到http://path/to/my_script.cgi?URL=PythonStatus: 302 Location: http://www.python.org 在空白页中。我对 localhost 上的 apache 配置知之甚少,无法解决这个问题,但这样做了:<form action="${path_to_file}"><input type="submit" name="Submit" value="Go to ${place_name}"> 此外,样式化的 href 有效:<a class="button" href="${path_to_file}">Go to ${place_name}</a> 所以我现在将使用 href。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
  • 2010-09-27
  • 2021-09-16
相关资源
最近更新 更多