我正在使用python3
,我正在创建包含两个get方法和一个post方法的简单Web服务器。
get方法工作正常,但post
方法没有显示任何消息。
以下是代码:
from http.server import BaseHTTPRequestHandler, HTTPServer
导入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(bytes(output,'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>¡ 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(bytes(output,'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(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(bytes(output,'UTF-8'))
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()
答案 0 :(得分:0)
以下是如何指定和捕获请求类型的简单示例。
您可以选择功能的访问路径,以及路径可用的方法。进入函数后,您可以捕获request.method
类型,并从那里处理您的案例。
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
elif request.method == 'GET':
get_user_info()
else:
print("Unsupported request")