votes up 3

Cannot redirect after headers have been written

Package:
tornado
github stars 20166
Exception Class:
Exception

Raise code

""" 

        If the ``status`` argument is specified, that value is used as the
        HTTP status code; otherwise either 301 (permanent) or 302
        (temporary) is chosen based on the ``permanent`` argument.
        The default is 302 (temporary).
        """
        if self._headers_written:
            raise Exception("Cannot redirect after headers have been written")
        if status is None:
            status = 301 if permanent else 302
        else:
            assert isinstance(status, int) and 300 <= status <= 399
        self.set_status(status)
        self.set_header("Location", utf8(url))
        self.finish()
😲 Agile task management is now easier than calling a taxi. #Tracklify

Ways to fix

votes up 0 votes down

Error code:

import tornado.ioloop
import tornado.web

class BasicIndexHandler(tornado.web.RequestHandler):
	def get(self): 
		self.write('Hello World! ')

class Redirecthappens(tornado.web.RequestHandler):
	def get(self):
		self.flush()   <----#Error here
		self.redirect('https://www.google.com/')

if __name__ == '__main__':
	app = tornado.web.Application([
		(r'/',BasicIndexHandler),
		(r'/red',Redirecthappens)
		])

	app.listen(8001)
	print('im listening on port')
	tornado.ioloop.IOLoop.current().start()

When you are using the flush method to flushes the current output buffer to the network it uses headers and prevents using the redirect method. So, if you want to redirect just don't use the flush method before it.

Fix code:

import tornado.ioloop
import tornado.web

class BasicIndexHandler(tornado.web.RequestHandler):
	def get(self): 
		self.write('Hello World! ')

class Redirecthappens(tornado.web.RequestHandler):
	def get(self):
		self.redirect('https://www.google.com/')

if __name__ == '__main__':
	app = tornado.web.Application([
		(r'/',BasicIndexHandler),
		(r'/red',Redirecthappens)
		])
	app.listen(8001)
	print('im listening on port')
	tornado.ioloop.IOLoop.current().start()

Jun 22, 2021 nurlan.taghi answer
nurlan.taghi 10.8k

Add a possible fix

Please authorize to post fix