我嘗試使用twisted.python.context
,但上下文在第一個deferToThread
後消失。在扭曲中使用上下文
from twisted.internet import reactor, defer, threads
from twisted.python import context
def _print_context(msg):
cont = context.get('cont')
print "{msg}: {context}".format(msg=msg, context=cont)
def sub_call():
_print_context("In sub_call")
@defer.inlineCallbacks
def with_context():
_print_context("before thread")
yield threads.deferToThread(sub_call)
_print_context("after thread")
reactor.stop()
def test():
cont = {'cont': "TestContext"}
context.call(cont, with_context)
reactor.callLater(0, test)
reactor.run()
我有背景deferToThread
之前和sub_call
,但deferToThread
後沒有上下文。
deferToThread
之後有什麼方法可以有上下文嗎?
非常感謝。當然,我使用類,這只是一個問題的最小例子。但只有我看到的解決方案是通過方法params傳遞上下文。我不喜歡這個解決方案,但找不到任何其他解決方案。 – aborilov
我很好奇爲什麼你不喜歡將輸入傳遞給你的方法作爲參數的解決方案。 – Glyph
@Glyph,因爲它是一個可選參數,每個方法中都會有這個參數,所以這些方法大部分都不需要這個參數,他們甚至不需要知道它存在,只需要將它傳遞給下一個方法。在此參數中,我傳遞有關在系統上執行操作的用戶的信息。而'context',我認爲是解決這個問題的最佳解決方案。 – aborilov