不使用python在http.server上工作
我正在尝试创建一个简单的http服务器,它具有基本的GET和POST功能。该程序应该通过打印一个简单的网页来获得请求,该网页向用户打招呼并询问他希望如何被问候。当用户输入他选择的问候语时,网页现在应该像他选择的那样问候他 虽然GET似乎运行良好,但POST并非如此。我尝试在每次代码执行时打印以进行调试,但它似乎被卡住了:不使用python在http.server上工作,python,server,cgi,Python,Server,Cgi,我正在尝试创建一个简单的http服务器,它具有基本的GET和POST功能。该程序应该通过打印一个简单的网页来获得请求,该网页向用户打招呼并询问他希望如何被问候。当用户输入他选择的问候语时,网页现在应该像他选择的那样问候他 虽然GET似乎运行良好,但POST并非如此。我尝试在每次代码执行时打印以进行调试,但它似乎被卡住了: ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) 我将在下面粘贴完整的代码以及终
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
我将在下面粘贴完整的代码以及终端输出
代码:
从http.server导入BaseHTTPRequestHandler,HTTPServer
导入cgi
类webServerHandler(BaseHTTPRequestHandler):
def do_获得(自我):
尝试:
如果self.path.endswith(“/hello”):
自我发送_响应(200)
self.send_标题('Content-type','text/html')
self.end_头()
output=“”
输出+=“”
输出+=“你好!”
输出+=''你想让我说什么?''
输出+=“”
self.wfile.write(output.encode(encoding='utf_8'))
打印(输出)
返回
如果self.path.endswith(“/hola”):
自我发送_响应(200)
self.send_标题('Content-type','text/html')
self.end_头()
output=“”
输出+=“”
输出+=“¡ Hola!”
输出+=''你想让我说什么?''
输出+=“”
self.wfile.write(output.encode(encoding='utf_8'))
打印(输出)
返回
除IOError外:
self.send_错误(404,'找不到文件:%s'%self.path)
def do_POST(自我):
尝试:
self.send_响应(201)
打印(“已发送响应”)
self.send_标题('Content-type','text/html')
打印(“发送的标题”)
self.end_头()
打印(“结束页眉”)
ctype,pdict=cgi.parse_头(self.headers.getheader('content-type'))
打印(“解析的标题”)
如果ctype==“多部分/表单数据”:
fields=cgi.parse_multipart(self.rfile,pdict)
messagecontent=fields.get('message')
打印(“接收方消息内容”)
output=“”
输出+=“”
输出+=“好的,这个怎么样:”
输出+=%s”%messagecontent[0]
输出+=''你想让我说什么?''
输出+=“”
打印(输出)
self.wfile.write(output.encode(encoding='utf_8'))
打印(“通过CGI写入”)
除:
通过
def main():
尝试:
端口=8080
服务器=HTTPServer(“”,端口),webServerHandler)
打印(“在端口上运行的Web服务器”,端口)
服务器。永远为您服务()
除键盘中断外:
打印(“^C已输入,正在停止web服务器…”
server.socket.close()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
终端输出:
Web Server running on port 8080
127.0.0.1 - - [28/Apr/2016 13:28:59] "GET /hello HTTP/1.1" 200 -
<html><body><h1>Hello!</h1><form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name="message" type="text" ><input type="submit" value="Submit"> </form></body></html>
127.0.0.1 - - [28/Apr/2016 13:29:09] "POST /hello HTTP/1.1" 201 -
Sent response
Sent headers
Ended header
在端口8080上运行的Web服务器
127.0.0.1---[28/Apr/2016 13:28:59]“GET/hello HTTP/1.1”200-
你好你想让我说什么?
127.0.0.1---[28/Apr/2016 13:29:09]“POST/hello HTTP/1.1”201-
发送响应
发送的标题
端头
如您所见,POST函数似乎没有超出parse_header命令的范围。我想不出来,任何帮助都是有用的 现在太晚了。然而,我仍然会发布这个答案,因为我在网上学习教程时遇到了同样的问题。希望,如果有人偶然发现同样的问题,这将有助于某人 在本教程中,讲师使用的是python 2,我使用的是python 3.6 更改日志与讲师所说的内容相比较:
- 分析标头时使用get方法而不是getheader,因为self.headers是类“MessageClass”的实例。并提供了获取方法
- 在分析多部分消息之前,已将边界转换为字节
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
class webserverHandler(BaseHTTPRequestHandler):
"""docstring for webserverHandler"""
def do_GET(self):
try:
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
output = ""
output += '<html><body>Hello!'
output += '<form method="POST" enctype="multipart/form-data" action="/hello"><h2> What would you like me to say?</h2><input name="message" type="text" /><input type="submit" value="Submit" /></form>'
output += '</body></html>'
self.wfile.write(output.encode())
print(output)
return
if self.path.endswith("/hola"):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
output = ""
output += '<html><body>¡Hola <a href="/hello">Back to Hello</a>'
output += '<form method="POST" enctype="multipart/form-data" action="/hello"><h2> What would you like me to say?</h2><input name="message" type="text" /><input type="submit" value="Submit" /></form>'
output += '</body></html>'
self.wfile.write(output.encode())
print(output)
return
except IOError:
self.send_error(404, "File not found %s" % self.path)
def do_POST(self):
try:
self.send_response(301)
self.send_header('Content-Type', 'text/html')
self.end_headers()
ctype, pdict = cgi.parse_header(self.headers.get('Content-Type'))
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ''
output += '<html><body>'
output += '<h2> Okay, how about this: </h2>'
output += '<h1> %s </h1>' % messagecontent[0].decode("utf-8")
output += '<form method="POST" enctype="multipart/form-data" action="/hello"><h2> What would you like me to say?</h2><input name="message" type="text" /><input type="submit" value="Submit" /></form>'
output += '</body></html>'
self.wfile.write(output.encode())
print(output)
except:
self.send_error(404, "{}".format(sys.exc_info()[0]))
print(sys.exc_info())
def main():
try:
port = 8000
server = HTTPServer(('', port), webserverHandler)
print("Web server running on port %s" % port)
server.serve_forever()
except KeyboardInterrupt:
print(" ^C entered stopping web server...")
server.socket.close()
if __name__ == '__main__':
main()
从http.server导入BaseHTTPRequestHandler,HTTPServer
导入cgi
类webserverHandler(BaseHTTPRequestHandler):
“”“webserverHandler的docstring”“”
def do_获得(自我):
尝试:
如果self.path.endswith(“/hello”):
自我发送_响应(200)
self.send_标题('Content-Type','text/html')
self.end_头()
output=“”
输出+=“你好!”
输出+=“您想让我说什么?”
输出+=''
self.wfile.write(output.encode())
打印(输出)
返回
如果self.path.endswith(“/hola”):
自我发送_响应(200)
self.send_标题('Content-Type','text/html')
self.end_头()
output=“”
输出+='¡霍拉'
输出+=“您想让我说什么?”
输出+=''
self.wfile.write(output.encode())
打印(输出)
返回
除IOError外:
self.send_错误(404,“找不到文件%s”%self.path)
def do_POST(自我):
尝试:
self.send_响应(301)
self.send_标题('Content-Type','text/html')
self.end_头()
ctype,pdict=cgi.parse_头(self.headers.get('Content-Type'))
pdict['boundary']=字节(pdict['boundary'],“utf-8”)
如果ctype==“多部分/表单数据”:
fields=cgi.parse_multipart(self.rfile,pdict)
messagecontent=fields.get('message')
输出=“”
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
class webserverHandler(BaseHTTPRequestHandler):
"""docstring for webserverHandler"""
def do_GET(self):
try:
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
output = ""
output += '<html><body>Hello!'
output += '<form method="POST" enctype="multipart/form-data" action="/hello"><h2> What would you like me to say?</h2><input name="message" type="text" /><input type="submit" value="Submit" /></form>'
output += '</body></html>'
self.wfile.write(output.encode())
print(output)
return
if self.path.endswith("/hola"):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
output = ""
output += '<html><body>¡Hola <a href="/hello">Back to Hello</a>'
output += '<form method="POST" enctype="multipart/form-data" action="/hello"><h2> What would you like me to say?</h2><input name="message" type="text" /><input type="submit" value="Submit" /></form>'
output += '</body></html>'
self.wfile.write(output.encode())
print(output)
return
except IOError:
self.send_error(404, "File not found %s" % self.path)
def do_POST(self):
try:
self.send_response(301)
self.send_header('Content-Type', 'text/html')
self.end_headers()
ctype, pdict = cgi.parse_header(self.headers.get('Content-Type'))
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ''
output += '<html><body>'
output += '<h2> Okay, how about this: </h2>'
output += '<h1> %s </h1>' % messagecontent[0].decode("utf-8")
output += '<form method="POST" enctype="multipart/form-data" action="/hello"><h2> What would you like me to say?</h2><input name="message" type="text" /><input type="submit" value="Submit" /></form>'
output += '</body></html>'
self.wfile.write(output.encode())
print(output)
except:
self.send_error(404, "{}".format(sys.exc_info()[0]))
print(sys.exc_info())
def main():
try:
port = 8000
server = HTTPServer(('', port), webserverHandler)
print("Web server running on port %s" % port)
server.serve_forever()
except KeyboardInterrupt:
print(" ^C entered stopping web server...")
server.socket.close()
if __name__ == '__main__':
main()