I need a library that can only format a correct HTTP response (without creating a web server because I already have this one).
I have to pass a body of an http response and a content type to this library.
The following function does not work properly if I try to send AJAX - jQuery does not find any response. However if I type a corresponding URL in the URL string of browser then a page is displayed.
def response( data ):
return "HTTP/1.0 200 OK\r\nContent-Type:application/json\r\nConnection:close\r\n\r\n{0}\r\n".format( data )
Details. The data variable is string of json. I also use the SocketServer class, call self.request.sendall( result_response ) in child's handle() function.
# the 'request handler' class
class StateRequestHandler( SocketServer.BaseRequestHandler ):
def handle( self ):
...
self.request.sendall( response( some_json ) )
# the configured server class
class StateServer( SocketServer.ThreadingMixIn, SocketServer.TCPServer ):
pass
Solved. The reason was in cross-domain requests.
Try the following:
Although the HTTP 1.0 and 1.1 spec say that a white space is optional between the header name and header value, the specs do say "a single SP[ace] is preferred".
Ensure that you do not have any Cross Domain issues so ensure your HTML page is served from exactly the domain,scheme and port as your JSON response (Unless you've correctly configured CORS.
Use Chrome Dev Tools / Firebug / Fiddler to see what request they're making and check the Javascript console.
Use Wireshark to see exactly what's on the wire.
Related
I'm new to Locust, and I am attempting to log statistics for a POST request, and I'm using the following code along with a generic call to locust.
import json
from locust import HttpUser, task, between
import cfg
class BasicUser(HttpUser):
wait_time = between(1, 3)
v1_data = json.load(open("v1_sample_data.json", "r"))
#task
def get_v1_prediction(self):
route = "/" + cfg.lookup("model.v1.route")
response = self.client.post(
route,
json=self.v1_data,
catch_response=True,
name="API Call"
)
print(response.text)
When I start an experiment, the host is called successfully, and response.text has the expected value and is printed to the console repeatedly. However, the statistics aren't logged.
When I use a GET request in place of the POST without passing data, statistics are logged (though it's only failures because the web app only allows POST requests). Any idea what's going on here?
The catch_response=True is the culprit.
From the documentation:
catch_response – (optional) Boolean argument that, if set, can be used to make a request return a context manager to work as argument to a with statement. This will allow the request to be marked as a fail based on the content of the response, even if the response code is ok (2xx). The opposite also works, one can use catch_response to catch a request and then mark it as successful even if the response code was not (i.e 500 or 404).
there I am new to the flask.
The scenario:
I am trying to redirect to a certain route after submitting the form.
So I am using flask redirect for this along with code parameter.
#topics_bp.route('/create_topic/',methods =['GET','POST'] )
def create_topic():
if request.method == 'GET':
#send the form for create topic!
formData = TopicForm()
return render_template('create-topic.html',form = formData)
if request.method == 'POST':
# check the post method and redirect
return redirect(url_for('topic.topics'),code=201)
Basically , I want to return HTTP code 201 for a record created and then redirect to the intended route.
But if I do like this, it simply returns a redirection page. Every time I need to click manually.
Is there any workaround to return 201 code and redirect automatically?
Thanks in advance!
I want to return HTTP code 201 for a record created and then redirect to the intended route.
That's not something you can do with HTTP. A redirect is itself a specific HTTP 30x status code:
In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3, and a Location header holding the URL to redirect to.
Either you return a 201 status code or you return one of the HTTP redirection status codes. You can't do both.
The flask.redirect() function generates a valid 30x response (with the required Location header), and the documentation for the function states what redirect status codes are supported:
Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
The function doesn't enforce this, however; the status code is not validated.
You need to distinguish between a browser and other clients here. A 201 Created response is something you typically return from a REST API to a client that expects simple JSON or XML interactions at a programmable level. Redirects, on the other hand, are more typically used in a frontend, in the presentation layer.
If you are coding a HTML-based front-end, just return a redirect. Humans don't read response codes, they read rendered HTML pages. They don't care and don't need to know the exact HTTP codes used to make the browser do the right thing. Given that your route also includes a form, you are almost certainly building a site for humans and not for programmatic clients.
If you are building a REST API, then return a 201 response, and document that the API client will have to make a new request based on the Location header you included, or on something in the body of the response. A HTML browser will not follow the Location header on 201 responses however.
I then would not use the redirect() function for this, even if it does allow you to use 201 as the status code, because it always produces a (simple) HTML body containing the text you see in your browser about an automatic redirect.
I am sending post request in the body of some json data, to process on server and I want the results back to client(c++ app on phone) in the form of json data and hence parse on mobile.
I have the following code inside handler:
class ServerHandler(tornado.web.RequestHandler):
def post(self):
data = tornado.escape.json_decode(self.request.body)
id = data.get('id',None)
#process data from db (take a while) and pack in result which is dictinary
result = process_data(id)# returns dictionary from db= takes time
print 'END OF HANDLER'
print json.dumps(result)
#before this code below I have tried also
#return result
#return self.write(result)
#return self.write(json.dumps(result))
#return json.dumps(result)
self.set_header('Content-Type', 'application/json')
json_ = tornado.escape.json_encode(result)
self.write(json_)
self.finish()
#return json.dumps(result)
I always get printed 'END OF HANDLER' and valid dictinary/json below on console but when I read at client mobile I always get
<html><title>405: Method Not Allowed</title><body>405: Method Not Allowed</body></html>
Does anyone have any idea what is the bug ?
(I am using CIwGameHttpRequest for sending request and it works when file is static =>name.json but now same content is giving error in post request. )
The error (HTTP 405 Method Not Allowed) means that you have made a request to a valid URL, but you are using an HTTP verb (e.g. GET, POST, PUT, DELETE) that cannot be used with that URL.
Your web service code appears to handle the POST verb, as evidenced by the post method name, and also by the fact that incoming requests appear to have a request body. You haven't shown us your C++ client code, so all I can do is to speculate that it is making a GET request. Does your C++ code call Request->setPOST();? (I haven't worked with CIwGameHttpRequest before, but Googling for it I found this page from which I took that line of code.)
I've not worked with Tornado before, but I imagine that there is some mechanism somewhere that allows you to connect a URL to a RequestHandler. Given that you have a 405 Method Not Allowed error rather than 404 Not Found, it seems that however this is done you've done it correctly. You issue a GET request to Tornado for the URL, it determines that it should call your handler, and only when it tries to use your handler it realises that it can't handle GET requests, concludes that your handler (and hence its URL) doesn't support GETs and returns a 405 error.
I am trying to send data from a javascript app running in GTK webkit to Python via a HTTP request with the data sent in POST.
I can capture the request using resource-request-starting and checking the uri of the request.
I know the request works because I can send data through the request headers and view it with
def on_resource_request_starting(view, frame, resource, request, response):
uri = urllib.unquote(request.props.uri)
if uri.startswith('http://appname.local/'):
print request.get_message().request_headers.get_one('foobar')
But when I use print request.get_message().request_body.data I don't get anything.
How do I view the POST data?
I haven't used this API, but I believe you need to call the binding's equivalent of soup_message_body_flatten() before reading the data field. See the documentation for SoupMessageBody in the C API.
So, at a guess:
print request.get_message().request_body.flatten().data
Hooking to SoupSession "request-queued" signal and getting
buffer(s) using soup_message_body_get_chunk(soupmsgbody, num);
seems to work (in webkitgtk1 today, Jun 2015).
webkit_get_default_session() returns the SoupSession in question.
my problem is about Web redirect ,, i'm using urllib>getcode() to know what status codes return
so here is my code
import urllib
a = urllib.urlopen("http://www.site.com/incorrect-tDirectory")
a.getcode()
a.getcode() return 200 but actually it's redirect to main page and i've check references that says redirect should return as i remember 300 or 301 but it's not 200 hopefully you got me
so my question how to catch the redirection
urllib2.urlopen() doc page says:
This function returns a file-like object with two additional methods:
geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
info() — return the meta-information of the page, such as headers, in the form of an mimetools.Message instance (see Quick Reference to HTTP Headers)
urllib.urlopen() actually implements geturl(), too, but it's not put as explicitly in the documentation.