3

データ構造で応答またはタイムアウトを検索する非同期リクエストを処理する単純なhttpサーバーを作成しようとしています。

  1. リクエストが届きます
  2. 時間<タイムアウトの間、responseCollectorの応答を確認します(requestIdをキーとして使用)
  3. 応答する場合は、それを返します
  4. タイムアウトした場合は、タイムアウトメッセージを返します

私はツイストに不慣れで、非同期応答を行うための最良の方法は何であるか疑問に思っています。ねじれたDeferredドキュメントcallLaterをいくつか調べましたが、正確に何をすべきかがわかりませんでした。現在、deferToThreadを使用してブロッキングメソッドを実行し、タイムアウトが経過するのを待ちます。据え置きメソッドで文字列呼び出し不可エラーが発生します:

Unhandled error in Deferred:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 497, in __bootstrap
    self.__bootstrap_inner()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 477, in run
    self.__target(*self.__args, **self.__kwargs)
--- <exception caught here> ---
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/python/threadpool.py", line 210, in _worker
    result = context.call(ctx, function, *args, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/python/context.py", line 59, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/python/context.py", line 37, in callWithContext
    return func(*args,**kw)
exceptions.TypeError: 'str' object is not callable

これが私のコードです:

from twisted.web import server, resource
from twisted.internet import reactor, threads
import json
import time

connectedClients = {}
responseCollector = {}

# add fake data to the collector
class FakeData(resource.Resource):
    isLeaf = True

    def render_GET(self, request):
        request.setHeader("content-type", "application/json")
        if 'rid' in request.args and 'data' in request.args:
            rid = request.args['rid'][0]
            data = request.args['data'][0]
            responseCollector[str(rid)] = data
            return json.dumps(responseCollector)
        return "{}"

class RequestHandler(resource.Resource):
    isLeaf = True

    def render_GET(self, request):
        #request.setHeader("content-type", "application/json")

        if not ('rid' in request.args and and 'json' in request.args):
            return '{"success":"false","response":"invalid request"}'

        rid = request.args['rid'][0]
        json = request.args['id'][0]

        # TODO: Wait for data to show up in the responseCollector with same rid
        # as our request without blocking other requests OR timeout
        d = threads.deferToThread(self.blockingMethod(rid))
        d.addCallback(self.ret)
        d.addErrback(self.err)

    def blockingMethod(self,rid):
        timeout  = 5.0
        timeElapsed = 0.0
        while timeElapsed<timeout:
            if rid in responseCollector:
                return responseCollector[rid]
            else:
                timeElapsed+=0.01
                time.sleep(0.01)
        return "timeout"

    def ret(self, hdata):
        return hdata

    def err(self, failure):
        return failure

reactor.listenTCP(8080, server.Site(RequestHandler()))
reactor.listenTCP(9080, server.Site(FakeData()))
reactor.run()

リクエストを行います(現在有用なものは何も返しません):

http://localhost:8080/?rid=1234&json={%22foo%22:%22bar%22}

リクエストで使用する偽のデータを追加します。

http://localhost:9080/?rid=1234&data=foo

作業バージョンで更新

from twisted.web import server, resource
from twisted.internet import reactor, threads
import json
import time

connectedClients = {}
responseCollector = {}

# add fake data to the collector
class FakeData(resource.Resource):
    isLeaf = True

    def render_GET(self, request):
        request.setHeader("content-type", "application/json")
        if 'rid' in request.args and 'data' in request.args:
            rid = request.args['rid'][0]
            data = request.args['data'][0]
            responseCollector[str(rid)] = data
            return json.dumps(responseCollector)
        return "{}"

class RequestHandler(resource.Resource):
    isLeaf = True

    def render_GET(self, request):

        if not ('rid' in request.args and 'data' in request.args):
            return '{"success":"false","response":"invalid request"}'

        rid = request.args['rid'][0]
        json = request.args['data'][0]

        # TODO: Wait for data to show up in the responseCollector with same rid
        # as our request without blocking other requests OR timeout
        d = threads.deferToThread(self.blockingMethod,rid)
        d.addCallback(self.ret, request)
        d.addErrback(self.err)

        return server.NOT_DONE_YET

    def blockingMethod(self,rid):
        timeout  = 5.0
        timeElapsed = 0.0
        while timeElapsed<timeout:
            if rid in responseCollector:
                return responseCollector[rid]
            else:
                timeElapsed+=0.01
                time.sleep(0.01)
        return "timeout"

    def ret(self, result, request):
        request.write(result)
        request.finish()

    def err(self, failure):
        return failure

reactor.listenTCP(8080, server.Site(RequestHandler()))
reactor.listenTCP(9080, server.Site(FakeData()))
reactor.run()
4

2 に答える 2

4

render_GET()では、twisted.web.server.NOT_DONE_YETを返す必要があります。リクエストオブジェクトをretメソッドに渡す必要があります:d.addCallback(self.ret、request)

次に、ret(request)で、request.write(hdata)を使用して非同期データを書き込み、request.finish()を使用して接続を閉じる必要があります。

def ret(self, result, request):
    request.write(result)
    request.finish()

からのいくつかの情報: http: //twistedmatrix.com/documents/current/web/howto/using-twistedweb.html

リソースのレンダリングは、TwistedWebがWeb要求を処理するためのリーフResourceオブジェクトを見つけたときに発生します。リソースのrenderメソッドは、ブラウザに返送される出力を生成するためにさまざまなことを行う場合があります。

  • 文字列を返す
  • Deferredをリクエストし、server.NOT_DONE_YETを返し、後でDeferredのコールバックでrequest.write( "stuff")とrequest.finish()を呼び出します。
于 2012-05-14T01:55:26.860 に答える
3

例のコード行のこれら2つのバージョンの違いについて考えてみてください。

d = threads.deferToThread(self.blockingMethod(rid))

vs

d = threads.deferToThread(self.blockingMethod, rid)

APIドキュメントdeferToThread読み、関数オブジェクトに関するPythonドキュメントを読んでください(python.orgドキュメントはこれを十分にカバーしていませんが、多くのサードパーティドキュメントはカバーしています)。

于 2012-05-14T12:40:20.903 に答える