4

I have basic twister app and i keep getting errors like that:

Request did not return bytes

Request:

Resource:

<main.MainPageDispatcher object at 0x7f049fa62be0>

Value:

'hello'

Everywhere, even in official docs' examples I see that string is returned and yet it not works for me. If I comment out first return and send bytes instead of string it is working. Can anyone help me understand how it works? If it has to be in bytes then why official guides are returning strings?

My code:

from twisted.web.server import Site
from twisted.web.static import File
from twisted.web.resource import Resource
from twisted.internet import reactor

class MainPageDispatcher(Resource):
    isLeaf = True
    def __init__(self):
        super().__init__()

    def render_GET(self, request):
        request.setHeader(b"content-type", b"text/html")
        return "hello"
        return bytes("hello", "utf-8")

root = MainPageDispatcher()
factory = Site(root)
reactor.listenTCP(8888, factory)
reactor.run()
Arrekin
  • 95
  • 5
  • Seems like porting python version 2 to 3 issue. Twisted require bytes, I won't put that as answer as I do not have necessary information but if someone encounter silimar issue just always return bytes(and assume that official docs may be in python 2). – Arrekin Dec 09 '17 at 16:46

1 Answers1

9

In python3 I'm using:

def render_GET(self, request):
    request.setHeader("Content-Type", "text/html; charset=utf-8")
    return "<html>Hello, world!</html>".encode('utf-8')

str.encode('utf-8') returns a bytes representation of the Unicode string