如何在localhost上执行python2 POST请求

时间:2017-05-16 12:31:02

标签: python python-2.7 localhost

我是Python中的新手,我无法执行帖子请求

def do_POST(self):
        try:
            self.send_response(301)
            self.send_header('Content-type', 'text/html')
            self.send_header('Access-Control-Allow-Origin', 'http://localhost:8080')
            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 += "  Values: "
            output += " %s " % messagecontent[0]
            output += '''<form method='POST' enctype='multipart/form-data' action='/hello'>What would you like me to say?<input name="message" type="text" ><input type="submit" value="Submit"> </form>'''
            output += "</body></html>"
            self.wfile.write(output)
            print output
        except:
            pass

我收到错误,其中501为错误代码

  

错误代码501。

     

消息:不支持的方法(&#39; POST&#39;)。

     

错误代码说明:501 =服务器不支持此操作。

1 个答案:

答案 0 :(得分:0)

使用Django的经典用例是使用require_http_methods装饰器:

    @require_http_methods(["GET", "POST"])
    def my_view(request):
        # I can assume now that only GET or POST requests make it this far
        # ...

=&GT;见https://docs.djangoproject.com/en/1.11/topics/http/decorators/

与Flask相同的用例:

@app.route('/hello/', methods=['POST'])
def hello():
    name = request.form['yourname']
    email = request.form['youremail']

=&GT;见http://flask.pocoo.org/docs/0.12/quickstart/#http-methods