这是我的网络服务器类:
import http.server
import socketserver
class WebHandler(http.server.BaseHTTPRequestHandler):
def parse_POST(self):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
postvars = cgi.parse_multipart(self.rfile, pdict)
elif ctype == 'application/x-www-form-urlencoded':
length = int(self.headers['content-length'])
postvars = urllib.parse.parse_qs(self.rfile.read(length),
keep_blank_values=1)
else:
postvars = {}
return postvars
def do_POST(self):
postvars = self.parse_POST()
print(postvars)
# reply with JSON
self.send_response(200)
self.send_header("Content-type", "application/json")
self.send_header("Access-Control-Allow-Origin","*");
self.send_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
self.send_header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
self.end_headers()
json_response = json.dumps({'test': 42})
self.wfile.write(bytes(json_response, "utf-8"))
当我运行服务器时,我在导入http.server后得到“名称'http'未定义”然后我得到了“没有名为http.server的模块”
答案 0 :(得分:18)
在v3之前的python中,您需要将http服务器作为
运行python -m SimpleHTTPServer 8069
#(8069=portnumber on which your python server is configured)
答案 1 :(得分:16)
http.server
仅存在于Python 3中。在Python 2中,您应该使用BaseHTTPServer
模块:
from BaseHTTPServer import BaseHTTPRequestHandler
应该可以正常工作。
答案 2 :(得分:0)
就像@Sami一样:您需要更早版本的python(2.7) -如果您在Linux上运行,则需要“ apt install python-minimal” -启动服务器“ python2 -m SimpleHTTPServer 8082” [或任何其他端口]时。默认情况下,python将在0.0.0.0上启动它,实际上是127.0.0.1:8082 [或您的特定端口]
骇客入侵
如果您有2个版本的python,则每次运行命令时都需要指定“ python2”或“ python3”