【问题标题】:How to execute python2 POST request on localhost如何在本地主机上执行 python2 POST 请求
【发布时间】:2017-05-16 12:31:01
【问题描述】:

我是 Python 新手,无法执行 post 请求

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。

消息:不支持的方法('POST')。

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

【问题讨论】:

  • 我不清楚。您想向远程服务器发送 POST 请求还是响应已经收到的 POST 请求。换句话说:您是 POST 请求的客户端还是服务器?
  • @LaurentLAPORTE 我是服务器
  • Django 哪个框架?烧瓶?

标签: python python-2.7 localhost


【解决方案1】:

使用 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
        # ...

=> 见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']

=> 见http://flask.pocoo.org/docs/0.12/quickstart/#http-methods

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    相关资源
    最近更新 更多