2016-04-28 55 views
1

我想创建一个简单的HTTP服务器与基本的GET和POST功能。该程序应该通过打印出一个简单的网页向用户发出GET请求,并询问他将如何迎接。当用户输入他选择的问候语时,网页现在应该像他所选择的那样迎接他。do_POST不能在http.server与python

虽然GET似乎工作正常,但POST不是。我通过在每个代码执行打印尝试调试和它似乎越来越困在这里:

ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) 

我将粘贴下面的代码完整的代码,我端子输出。

代码:

from http.server import BaseHTTPRequestHandler, HTTPServer 
    import cgi 


    class webServerHandler(BaseHTTPRequestHandler): 

     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>" 
        output += "<h1>Hello!</h1>" 
        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(encoding = 'utf_8')) 
        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>" 
        output += "<h1>&#161 Hola !</h1>" 
        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(encoding = 'utf_8')) 
        print (output) 
        return 

      except IOError: 
       self.send_error(404, 'File Not Found: %s' % self.path) 

     def do_POST(self): 
      try: 
       self.send_response(201) 
       print("Sent response") 
       self.send_header('Content-type', 'text/html') 
       print("Sent headers") 
       self.end_headers() 
       print("Ended header") 
       ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) 
       print("Parsed headers") 
       if ctype == 'multipart/form-data': 
        fields = cgi.parse_multipart(self.rfile, pdict) 
        messagecontent = fields.get('message') 
       print("Receiver message content") 
       output = "" 
       output += "<html><body>" 
       output += " <h2> Okay, how about this: </h2>" 
       output += "<h1> %s </h1>" % messagecontent[0] 
       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>" 
       print(output) 
       self.wfile.write(output.encode(encoding = 'utf_8')) 
       print ("Wrote through CGI") 
      except: 
       pass 


    def main(): 
     try: 
      port = 8080 
      server = HTTPServer(('', port), webServerHandler) 
      print ("Web Server running on port", port) 
      server.serve_forever() 
     except KeyboardInterrupt: 
      print (" ^C entered, stopping web server....") 
      server.socket.close() 

    if __name__ == '__main__': 
     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 

正如你所看到的,POST功能似乎并没有去beyong的parse_header命令。我无法弄清楚这一点,任何帮助将是有用的!

+0

你的问题表明您正在使用Python 3,为了避免混淆,你应该包括你正在使用,并期待它的Python版本上下工夫: ) –

回答

1

现在已经太晚了。不过,我仍然会发布这个答案,因为我在遵循在线教程时遇到了同样的问题。希望,如果有人偶然遇到同样的问题,这将有助于某人。

在教程中,教师使用的是Python 2,我使用的是Python 3.6。

更新日志相比有什么教官说:

  • 使用GET方法,而不是getheader在解析头,引起self.headers是类的一个实例“MessageClass的”。它提供了get方法。
  • 在解析多部分消息之前将边界转换为字节。

这里,是的工作代码的副本

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>&#161Hola <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() 
0

我能正常运行你的代码,并获得POST工作,进行以下更改后:

您有:

from http.server 

修改成:

from BaseHTTPServer 

它应该工作。

+0

取决于你的python版本,对于Python2来说,它是BaseHTTPServer,但对于Python3来说,它是http.server。 –