Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/azure/core/pipeline/transport/_base_async.py: 72%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

39 statements  

1# -------------------------------------------------------------------------- 

2# 

3# Copyright (c) Microsoft Corporation. All rights reserved. 

4# 

5# The MIT License (MIT) 

6# 

7# Permission is hereby granted, free of charge, to any person obtaining a copy 

8# of this software and associated documentation files (the ""Software""), to 

9# deal in the Software without restriction, including without limitation the 

10# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 

11# sell copies of the Software, and to permit persons to whom the Software is 

12# furnished to do so, subject to the following conditions: 

13# 

14# The above copyright notice and this permission notice shall be included in 

15# all copies or substantial portions of the Software. 

16# 

17# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 

18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 

20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 

21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 

22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 

23# IN THE SOFTWARE. 

24# 

25# -------------------------------------------------------------------------- 

26from __future__ import annotations 

27import asyncio 

28import abc 

29from collections.abc import AsyncIterator 

30from typing import ( 

31 AsyncIterator as AsyncIteratorType, 

32 TypeVar, 

33 Generic, 

34 Any, 

35 AsyncContextManager, 

36 Optional, 

37 Type, 

38 TYPE_CHECKING, 

39) 

40from types import TracebackType 

41 

42from ._base import _HttpResponseBase, _HttpClientTransportResponse, HttpRequest 

43from ...utils._pipeline_transport_rest_shared_async import _PartGenerator 

44 

45 

46AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType") 

47HTTPResponseType = TypeVar("HTTPResponseType") 

48HTTPRequestType = TypeVar("HTTPRequestType") 

49 

50if TYPE_CHECKING: 

51 # We need a transport to define a pipeline, this "if" avoid a circular import 

52 from .._base_async import AsyncPipeline 

53 

54 

55class _ResponseStopIteration(Exception): 

56 pass 

57 

58 

59def _iterate_response_content(iterator): 

60 """To avoid the following error from Python: 

61 > TypeError: StopIteration interacts badly with generators and cannot be raised into a Future 

62 

63 :param iterator: An iterator 

64 :type iterator: iterator 

65 :return: The next item in the iterator 

66 :rtype: any 

67 """ 

68 try: 

69 return next(iterator) 

70 except StopIteration: 

71 raise _ResponseStopIteration() # pylint: disable=raise-missing-from 

72 

73 

74class AsyncHttpResponse(_HttpResponseBase, AsyncContextManager["AsyncHttpResponse"]): # pylint: disable=abstract-method 

75 """An AsyncHttpResponse ABC. 

76 

77 Allows for the asynchronous streaming of data from the response. 

78 """ 

79 

80 def stream_download( 

81 self, pipeline: AsyncPipeline[HttpRequest, "AsyncHttpResponse"], *, decompress: bool = True, **kwargs: Any 

82 ) -> AsyncIteratorType[bytes]: 

83 """Generator for streaming response body data. 

84 

85 Should be implemented by sub-classes if streaming download 

86 is supported. Will return an asynchronous generator. 

87 

88 :param pipeline: The pipeline object 

89 :type pipeline: azure.core.pipeline.Pipeline 

90 :keyword bool decompress: If True which is default, will attempt to decode the body based 

91 on the *content-encoding* header. 

92 :return: An async iterator of bytes 

93 :rtype: AsyncIterator[bytes] 

94 """ 

95 raise NotImplementedError("stream_download is not implemented.") 

96 

97 def parts(self) -> AsyncIterator["AsyncHttpResponse"]: 

98 """Assuming the content-type is multipart/mixed, will return the parts as an async iterator. 

99 

100 :return: An async iterator of the parts 

101 :rtype: AsyncIterator 

102 :raises ValueError: If the content is not multipart/mixed 

103 """ 

104 if not self.content_type or not self.content_type.startswith("multipart/mixed"): 

105 raise ValueError("You can't get parts if the response is not multipart/mixed") 

106 

107 return _PartGenerator(self, default_http_response_type=AsyncHttpClientTransportResponse) 

108 

109 async def __aexit__( 

110 self, 

111 exc_type: Optional[Type[BaseException]] = None, 

112 exc_value: Optional[BaseException] = None, 

113 traceback: Optional[TracebackType] = None, 

114 ) -> None: 

115 return None 

116 

117 

118class AsyncHttpClientTransportResponse( # pylint: disable=abstract-method 

119 _HttpClientTransportResponse, AsyncHttpResponse 

120): 

121 """Create a HTTPResponse from an http.client response. 

122 

123 Body will NOT be read by the constructor. Call "body()" to load the body in memory if necessary. 

124 

125 :param HttpRequest request: The request. 

126 :param httpclient_response: The object returned from an HTTP(S)Connection from http.client 

127 """ 

128 

129 

130class AsyncHttpTransport( 

131 AsyncContextManager["AsyncHttpTransport"], 

132 abc.ABC, 

133 Generic[HTTPRequestType, AsyncHTTPResponseType], 

134): 

135 """An http sender ABC.""" 

136 

137 @abc.abstractmethod 

138 async def send(self, request: HTTPRequestType, **kwargs: Any) -> AsyncHTTPResponseType: 

139 """Send the request using this HTTP sender. 

140 

141 :param request: The request object. Exact type can be inferred from the pipeline. 

142 :type request: any 

143 :return: The response object. Exact type can be inferred from the pipeline. 

144 :rtype: any 

145 """ 

146 

147 @abc.abstractmethod 

148 async def open(self) -> None: 

149 """Assign new session if one does not already exist.""" 

150 

151 @abc.abstractmethod 

152 async def close(self) -> None: 

153 """Close the session if it is not externally owned.""" 

154 

155 async def sleep(self, duration: float) -> None: 

156 """Sleep for the specified duration. 

157 

158 You should always ask the transport to sleep, and not call directly 

159 the stdlib. This is mostly important in async, as the transport 

160 may not use asyncio but other implementation like trio and they their own 

161 way to sleep, but to keep design 

162 consistent, it's cleaner to always ask the transport to sleep and let the transport 

163 implementor decide how to do it. 

164 By default, this method will use "asyncio", and don't need to be overridden 

165 if your transport does too. 

166 

167 :param float duration: The number of seconds to sleep. 

168 """ 

169 await asyncio.sleep(duration)