相較於return後再次呼叫該函式都是新的開始,yield類似一個紀錄點,local state
會被保存
保存後暫停,等到下一次執行時恢復上一次所保存的狀態
在iter_content定義了一個generator function,關於yield的使用分成兩個部分
等到所有內容被消化完成並且沒有發生錯誤,設定self._content_consumed
為True
def generate():
# Special case for urllib3.
if hasattr(self.raw, 'stream'):
try:
for chunk in self.raw.stream(chunk_size, decode_content=True):
yield chunk
except ProtocolError as e:
self._error = ChunkedEncodingError(e)
except DecodeError as e:
self._error = ContentDecodingError(e)
except ReadTimeoutError as e:
self._error = ConnectionError(e)
finally:
# if we had an error - throw the saved error
if self._error:
raise self._error
else:
# Standard file-like object.
while True:
chunk = self.raw.read(chunk_size)
if not chunk:
break
yield chunk
self._content_consumed = True