Bottle request.json gets 405 in the mail

I am trying to get a bottle to get json in xmlhttprequest and I get 405 error

Part of my bottle script:

@app.route('/myroute/') def myroute(): print request.json 

Part of my other script for checking xhr out:

 jdata = json.dumps({"foo":"bar"}) urllib2.urlopen("http://location/app/myroute/", jdata) 

Why am I getting 405?

 bottlepy error: 127.0.0.1 - - [2012-09-23 23:09:34] "POST /myroute/ HTTP/1.0" 405 911 0.005458 urllib2 error: urllib2.HTTPError: HTTP Error 405: Method Not Allowed 

I also tried the options:

 @app.route('/myroute/json:json#[1-9]+#') def myroute(json): request.content_type = 'application/json' print request.json, json 

Json return doesn't seem to be a problem

+4
source share
2 answers

I think the problem is that the server does not allow POST requests. You can probably try sending it in a GET request:

 urllib2.urlopen("http://location/app/myroute/?" + jdata) 

UPDATE :

I just realized by looking at your question again that you are actually trying to send JSON data via a GET request. You should generally avoid sending JSON with GET requests, but use POST [ Link ] requests instead.

To send a POST request to Bottle, you also need to set the headers in application/json :

 headers = {} headers['Content-Type'] = 'application/json' jdata = json.dumps({"foo":"bar"}) urllib2.urlopen("http://location/app/myroute/", jdata, headers) 

Then with @Anton's answer, you can access the JSON data in your view as follows:

 @app.post('/myroute/') def myroute(): print request.json 

Also, as a bonus, send a regular GET request and access it:

 # send GET request urllib2.urlopen("http://location/app/myroute/?myvar=" + "test") # access it @app.route('/myroute/') def myroute(): print request.GET['myvar'] # should print "test" 
+4
source

By default, the route decorator makes the processed function process only GET requests. You need to add the method argument to tell the Butlet to process POST requests. To do this, you need to change:

 @app.route('/myroute/') 

in

 @app.route('/myroute/', method='POST') 

or shorter version:

 @app.post('/myroute/') 
+3
source

Source: https://habr.com/ru/post/1435829/


All Articles