Почему моя переменная form.getvalue возвращает 'none' при использовании python 3 CGI для публикации отправки формы 'result' на страницу? - PullRequest
0 голосов
/ 17 апреля 2020

Я работаю над курсом Udacity, и инструктор использует Python 2.
Я использую Python 3.

Цель - создать веб-сервер, который обрабатывает POST и GET запросов с использованием CGI .

В 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()

Это то, что я получил на интерфейсе:
Before submitted form

После формы отправка:
Output after form submission

На выходе должно быть написано «Стив». Почему ничего не сказано?

Не знаю, поможет ли это, но я запускаю весь проект в виртуальной среде. Vagrant + Virtual Box на Python версии 3.5.4.

Спасибо за помощь, ребята. Я ценю это!
Да, и если вы знаете лучший способ сделать это, кроме использования FLASK, пожалуйста, поделитесь.


Есть ли способ сделать это, используя установку Python 2, но отформатированную для Python 3?

...