AttributeError:'WebSocketHandler'对象没有属性'write_messsage'

时间:2017-12-18 19:23:15

标签: python-2.7 tornado

我正在尝试构建一个服务器,该服务器接受用户对长(ish)运行作业的请求,在作业进行时更新用户,并返回一些数据供客户端使用。我试图使用龙卷风的WebSocketHandler来做到这一点。有没有理由我不能从另一个对象调用WebSocketHandler的write_message方法?

import tornado.ioloop
import tornado.websocket
import json, sys, os
from uuid import uuid4


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('Welcome to the site. Requests cannot be made to the main page.')



class WSInvalidRequest(Exception):
    """Called when user sends invalid request to the server."""
    pass



class WSRequestQueue:
    def __init__(self):
        self._items = []

    def put(self, item):
        self._items.append(item)
        return self._items.length()

    def get(self):
        return self._items.pop(0)

    def get_position(self, item):
        return self._items.index(item)


QUEUE = WSRequestQueue()


class WSRequest:

    def __init__(self, message, websocket):
        self.websocket = websocket
        self.ran = False
        self.valid = False
        self.write(u'Request received.')
        try:
            self.request = WSRequest.parse_message(message)
            self.valid = True
            self.write(u'Request validated.')
            position = QUEUE.put(self)
            self.write(u'Added request to queue behind %i other requests.' % position)

        except WSInvalidRequest as e: self.write(e.message)


    @staticmethod
    def validate_request_dict(request):
        if not isinstance(messageDict, dict):
            raise WSInvalidRequest(u'Invalid request. Should be JSON dict string.')

        if 'arg' not in request:
            raise WSInvalidRequest(u'Invalid request. No arg found')


    @staticmethod
    def parse_message(message):
        messageDict = json.loads(message)
        validate_request_dict(messageDict)
        argument = messsageDict['arg']
        return {'argumet': argument}


    def write(self, message):
        self.websocket.write_messsage(unicode(message))


    def run(self):
        self.ran = True


    def destroy(self):
        if self.valid:
            if not self.ran: QUEUE.pop(QUEUE.get_position(self))
            self.websocket.requests.remove(self)

        self.write(u'Removed request from queue.')



class RequestWebSocket(tornado.websocket.WebSocketHandler):

    def open(self):
        self.id = uuid4()
        self.requests = set()
        print("WebSocket opened")


    def on_message(self, message):
        self.write_message(u'You sent: %s' % message)
        self.write_message(u'Attempting to add your request to the queue.')
        newRequest = WSRequest(message, self)
        if newRequest.valid: self.requests.add(newRequest)
        else: newRequest.destroy


    def on_close(self):
        print("WebSocket closed. Removing all requests from the queue.")
        for request in self.requests: request.destroy()


    def check_origin(self, origin):
        return True




if __name__ == "__main__":

    # Create the web server
    application = tornado.web.Application([
        (r'/', MainHandler),
        (r'/websocket', RequestWebSocket)
    ], debug=True)

    application.listen(80)
    tornado.ioloop.IOLoop.instance().start()

1 个答案:

答案 0 :(得分:2)

write_messsage中存在拼写错误。还有一个额外的 s

它在:

class WSRequest:

    def write(self, message):
        self.websocket.write_messsage(unicode(message))
                               # ^ extra 's'