Grant Timmerman | 5c11b0a | 2019-06-26 07:39:48 -0700 | [diff] [blame] | 1 | # Thread Safety |
| 2 | |
| 3 | This page contains important information about the thread safety of this library. |
| 4 | |
| 5 | ## The httplib2.Http() objects are not thread-safe |
| 6 | |
| 7 | The google-api-python-client library is built on top of the [httplib2](https://github.com/httplib2/httplib2) library, which is not thread-safe. Therefore, if you are running as a multi-threaded application, each thread that you are making requests from must have its own instance of `httplib2.Http()`. |
| 8 | |
| 9 | The easiest way to provide threads with their own `httplib2.Http()` instances is to either override the construction of it within the service object or to pass an instance via the http argument to method calls. |
| 10 | |
Bu Sun Kim | 8496ebe | 2019-08-12 18:04:35 -0700 | [diff] [blame^] | 11 | ```python |
Grant Timmerman | 5c11b0a | 2019-06-26 07:39:48 -0700 | [diff] [blame] | 12 | # Create a new Http() object for every request |
| 13 | def build_request(http, *args, **kwargs): |
| 14 | new_http = httplib2.Http() |
| 15 | return apiclient.http.HttpRequest(new_http, *args, **kwargs) |
| 16 | service = build('api_name', 'api_version', requestBuilder=build_request) |
| 17 | |
| 18 | # Pass in a new Http() manually for every request |
| 19 | service = build('api_name', 'api_version') |
| 20 | http = httplib2.Http() |
| 21 | service.stamps().list().execute(http=http) |
Bu Sun Kim | 8496ebe | 2019-08-12 18:04:35 -0700 | [diff] [blame^] | 22 | ``` |