Sentient07
Sentient07

Reputation: 1290

Writing the Content-Length header to the client from the server in Tornado

I have a tornado server, that simply prints the headers that the client sent. server.py :

import tornado.httpserver
import tornado.ioloop
import tornado.httputil as hutil

def handle_request(request):

    message = ""
    try :
            message = request.headers['Content-Length']
    except KeyError :
            message = request.headers
    request.connection.write_headers(
            tornado.httputil.ResponseStartLine('HTTP/1.1', 200, 'OK'),
            tornado.httputil.HTTPHeaders
            ({"Content-Length": str(len(message))}))
    request.connection.finish()
    print(request.headers)

http_server = tornado.httpserver.HTTPServer(handle_request)
http_server.listen(8888, address='127.0.0.1')
tornado.ioloop.IOLoop.instance().start()

When I send request to this server using curl, I get the following traceback.

ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tornado/http1connection.py", line 234, in _read_message
    delegate.finish()
  File "/usr/local/lib/python2.7/dist-packages/tornado/httpserver.py", line 280, in finish
    self.server.request_callback(self.request)
  File "Tests/tornado_server.py", line 17, in handle_request
    request.connection.finish()
  File "/usr/local/lib/python2.7/dist-packages/tornado/http1connection.py", line 430, in finish
    self._expected_content_remaining)
HTTPOutputError: Tried to write 5 bytes less than Content-Length

The headers that I sent from Curl :

{'Host': '127.0.0.1:8888', 'Accept': '*/*', 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36'}

Is it necessary that I should write back the same amount of data as Content-Length ? If so why and how should that be done ? Thanks in advance.

Upvotes: 1

Views: 5114

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122342

You need to write back the same number of bytes as you say you will. You returned a Content-Length header for the response. That means your response body needs to contain that many bytes.

By the looks of it you don't write anything back for a response body; if you are stating that you are sending len(str(message)) bytes, you probably wanted to send str(message) too:

request.connection.write(str(message))

This is separate from the Content-Length in the request, which denotes how many bytes the request body contains.

Upvotes: 3

Related Questions