python - 如何在python创建的BaseHTTPSERVER上执行python脚本?

标签 python http webserver cgi

我简单地创建了一个 python 服务器:

python -m SimpleHTTPServer

我有一个 .htaccess(我不知道它是否对 python 服务器有用) 与:

AddHandler cgi-script .py
Options +ExecCGI

现在我正在编写一个简单的 python 脚本:

#!/usr/bin/python
import cgitb
cgitb.enable()
print 'Content-type: text/html'
print '''
<html>
     <head>
          <title>My website</title>
     </head>
     <body>
          <p>Here I am</p>
     </body>
</html>
'''

我使 test.py(我的脚本的名称)成为一个执行文件:

chmod +x test.py

我在 firefox 中使用这个地址启动:(http ://) 0.0.0.0:8000/test.py

问题,脚本没有执行...我看到网页中的代码... 服务器错误是:

localhost - - [25/Oct/2012 10:47:12] "GET / HTTP/1.1" 200 -
localhost - - [25/Oct/2012 10:47:13] code 404, message File not found
localhost - - [25/Oct/2012 10:47:13] "GET /favicon.ico HTTP/1.1" 404 -

如何简单地管理python代码的执行?是否可以在 python 服务器中编写来执行 python 脚本,就像这样:

import BaseHTTPServer
import CGIHTTPServer
httpd = BaseHTTPServer.HTTPServer(\
    ('localhost', 8123), \
CGIHTTPServer.CGIHTTPRequestHandler)
###  here some code to say, hey please execute python script on the webserver... ;-)
httpd.serve_forever()

或者别的……

最佳答案

CGIHTTPRequestHandler 你走在正确的轨道上,因为 .htaccess 文件对内置的 http 服务器没有任何意义。有一个 CGIHTTPRequestHandler.cgi_directories 变量指定可执行文件被视为 cgi 脚本的目录 (here is the check itself)。您应该考虑将 test.py 移动到 cgi-binhtbin 目录并使用以下脚本:

cgiserver.py:

#!/usr/bin/env python3

from http.server import CGIHTTPRequestHandler, HTTPServer

handler = CGIHTTPRequestHandler
handler.cgi_directories = ['/cgi-bin', '/htbin']  # this is the default
server = HTTPServer(('localhost', 8123), handler)
server.serve_forever()

cgi-bin/test.py:

#!/usr/bin/env python3
print('Content-type: text/html\n')
print('<title>Hello World</title>')

你应该得到:

|- cgiserver.py
|- cgi-bin/
   ` test.py

使用 python3 cgiserver.py 运行并将请求发送到 localhost:8123/cgi-bin/test.py。干杯。

关于python - 如何在python创建的BaseHTTPSERVER上执行python脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13065306/

相关文章:

python - 在 Python 中实现 Miller-Rabin 复合性时遇到问题

java - 我可以使用哪些技术来帮助更好地理解离散数学中的概念是如何在编程中使用的?

python - 打印列表时如何去掉字符串引号?

javascript - Stack Overflow 如何在不重新加载页面的情况下通知服务器端事件?我在 Firebug 中没有看到任何请求

html - 使用 Dreamweaver 确保所有网站文件正确上传

java - 在 Apache 服务器 2.2 上运行两个虚拟主机。* 总是转到第一个服务器名称的文档根目录

python - wxPython - Linux 和 Windows 之间的 TextCtrl 不同行为

http - 如何让客户端在下载文件时打开保存文件对话框

apache - 如何使用 htaccess 将 https 域重定向到 http 域?

ruby - 如何使用 ruby​​ 将大文件从客户端传输到服务器?