1

我正在学习 Udacity 课程,讲师正在使用 Python 2。
我正在使用 Python 3。

目标是创建一个使用CGI处理POSTGET请求的 Web 服务器。

在 Python 2 中,表单输入提交使用此方法发布到屏幕上。检查“ do_POST ”方法:

from BaseHTTPServer 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)
            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)
            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.getheader('content-type'))
        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]
        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)
        print output
    except:
        pass


  def main():
      try:
          port = 8080
          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()

在 Python 3(这是我的代码)中,我使用 cgi.FieldStorage() 将数据存储在变量中。请参阅下面的代码。检查“do_POST”方法:

from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi, cgitb 
# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
first_name = form.getvalue('firstname')
last_name  = form.getvalue('lastname')

class WebServerHandler(BaseHTTPRequestHandler):

  def do_GET(self):
    if self.path.endswith("/"):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        output = ""
        output += "<html><body>"
        output += "<h2> How's it going?</h2>"
        output += "<form action = '/' method = 'POST'>\
                    First Name: <input type = 'text' name = 'firstname'><br />\
                    Last Name: <input type = 'text' name = 'lastname' />\
                    <input type = 'submit' value = 'Submit' /></form>"
        output += "</body></html>"
        self.wfile.write(output.encode(encoding='utf_8'))
        print (output)
        return
    if self.path.endswith("/hello"):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        output = ""
        output += "<html><body>&#161hola  <a href = /hello> Back to English! </a>"
        output += "<form action = '/' method = 'POST'>\
                    First Name: <input type = 'text' name = 'firstname'><br />\
                    Last Name: <input type = 'text' name = 'lastname' />\
                    <input type = 'submit' value = 'Submit' /></form>"
        output += "</body></html>"
        self.wfile.write(output.encode(encoding='utf_8'))
        print (output)
        return

    else:
        self.send_error(404, 'File Not Found:')


def do_POST(self):
    try:
        self.send_response(301)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        output = ""
        output += "<html><body>"
        output += " <h2> Okay, how about this: </h2>"
        output += "<h3> Output: %s </h3>" % first_name
        output += "<form action = '/' method = 'POST'>\
                    First Name: <input type = 'text' name = 'firstname'><br />\
                    Last Name: <input type = 'text' name = 'lastname' />\
                    <input type = 'submit' value = 'Submit' /></form>"
        output += "</body></html>"
        self.wfile.write(output.encode(encoding = "utf_8"))
        print(output)

    except:
        pass


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

 if __name__ == '__main__':
   main()

这是我在前端得到的:
提交表格之前

表单提交后:
表单提交后的输出

输出应该是“史蒂夫”。为什么说没有?

我不知道这是否会有所帮助,但是我在虚拟环境中运行整个项目。Python 3.5.4 版上的 Vagrant + Virtual Box。

谢谢你们的帮助。我很感激!
哦,如果你知道使用 FLASK 之外的更好的方法,请分享。


有没有办法使用 Python 2 设置但为 Python 3 格式化?

4

0 回答 0