2017-01-04 4 views
1

내가 여기에 참조로 Twisted's 구현을 사용하고 비동기 코드를 만드는 inlineCallbacks 동기 코드가 작동처럼 보이는 방법을 이해하려고왜 트위스트의 inlineCallbacks는 '이연'개체를 반환하지

정상 기능을 :.. 입력 → 출력

inlineCallbacks 장식 발전기 기능 : 이연 → 입력

그것은 Deferredcallback에 등록 할 수있는 객체

를 다시 제공합니다.
from twisted.internet import defer 

intermediate_deferred = None 

@defer.inlineCallbacks 
def example(): 
    global intermediate_deferred 
    print("Started") 
    intermediate_deferred = defer.Deferred() 
    result = yield intermediate_deferred 
    print("Resuming for the first time with %s" % result) 
    intermediate_deferred = defer.Deferred() 
    result = yield intermediate_deferred 
    print("Resuming for the second time with %s" % result) 

generator_deferred = example() 
intermediate_deferred.callback("One") 
intermediate_deferred.callback("Two") 
  1. (가)를 소비 즉 지연된 객체를 반환하는 진정한 필요가 무엇입니까?
  2. 누가 최종 값으로 호출합니까?
  3. 반환되지 않으면 어떻게됩니까?

repl에서 나는 왜이 반환 값이 필요한지 알지 못합니다. 나의 근본적인 문제는 내가이 기능의 소비자에 관해서 아직도 생각하고 있지 않다는 사실로부터 생겨난 것 같다.

그래서 일부 웹 프레임 워크를 가지고 코드가 될 방법을 가정 해 봅시다 :

# Assume it returns 'example' function object. 
function_to_call = get_routing_function(request) 
d = function_to_call() 
# But who takes care of calling it back? The Event Loop has to do that? 
# So the Event Loop has one important job of monitoring and calling back 
# such Deferred's to complete the full cycle? 
d.addCallback(handle_http_response) 
@defer.inlineCallbacks 
def get_user_details(user_idn): 
    result = yield get_user_details_from_cache(user_idn) 
    if not result: 
     result = yield get_user_details_from_db(user_idn) 
    result = post_process_user_details(user_idn) 
    return result 
+0

누구나 소프트웨어 엔지니어링에 더 적합하다고 생각하는 사람이 있으면 언제든지 알려 주시기 바랍니다. 거기에 주제가있는 한 그것을 마이그레이션 할 것입니다. – Nishant

답변

0

그것을 소비 즉 Deferred 개체를 반환하는 진짜 필요가 무엇입니까?

이러한 인라인 콜백 함수를 트리거하는 코드는 후행 처리 작업을 여기에 등록 할 수 있습니다. 한 예가 d.addCallback(handle_http_response) 일 수 있습니다.

누가 최종 값으로 호출합니까?

인라인 콜백 데코레이터 기계가 수행하는 작업은 internally입니다. 발전기가 StopIteration, 즉 발전기가 외부 세계에 대해 마지막으로 return을 만들었을 때이 값은 Deferred입니다. 대조적으로, yield ed 값은 generator 내부에서만 사용됩니다.

반환되지 않으면 어떻게됩니까?

이러한 생성기 기능은 부작용에만 사용할 수 있습니다. 즉, 이러한 기능의 출력 값으로는 아무 것도 할 수 없습니다.