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

2024-04-19 02:30:12 发布

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

我只是创建了一个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()

或者别的什么。。。


Tags: 代码pytestimport服务器脚本localhosttitle
2条回答

由于.htaccess文件对内置http服务器没有任何意义,因此您使用CGIHTTPRequestHandler的方法是正确的。有一个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发送请求。干杯。

你试过用Flask吗?这是一个轻量级的服务器库,使这一切变得非常简单。

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return '<title>Hello World</title>'


if __name__ == '__main__':
    app.run(debug=True)

在本例中,返回值<title>Hello World</title>是用HTML呈现的。您还可以将HTML模板文件用于更复杂的页面。

这里有一个很好的,简短的,youtube tutorial解释得更好。

相关问题 更多 >