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 |
Bu Sun Kim | 205ae59 | 2020-11-18 05:40:02 -0700 | [diff] [blame] | 12 | import google.auth |
| 13 | import googleapiclient |
| 14 | import google_auth_httplib2 |
| 15 | import httplib2 |
| 16 | from googleapiclient import discovery |
| 17 | |
Grant Timmerman | 5c11b0a | 2019-06-26 07:39:48 -0700 | [diff] [blame] | 18 | # Create a new Http() object for every request |
| 19 | def build_request(http, *args, **kwargs): |
Harrison Zhao | 5ae088d | 2020-11-23 03:46:03 -0800 | [diff] [blame] | 20 | new_http = google_auth_httplib2.AuthorizedHttp(credentials, http=httplib2.Http()) |
Bu Sun Kim | 205ae59 | 2020-11-18 05:40:02 -0700 | [diff] [blame] | 21 | return googleapiclient.http.HttpRequest(new_http, *args, **kwargs) |
| 22 | service = discovery.build('api_name', 'api_version', requestBuilder=build_request) |
Grant Timmerman | 5c11b0a | 2019-06-26 07:39:48 -0700 | [diff] [blame] | 23 | |
| 24 | # Pass in a new Http() manually for every request |
Bu Sun Kim | 205ae59 | 2020-11-18 05:40:02 -0700 | [diff] [blame] | 25 | service = discovery.build('api_name', 'api_version') |
| 26 | http = google_auth_httplib2.AuthorizedHttp(credentials, http=httplib2.Http()) |
Grant Timmerman | 5c11b0a | 2019-06-26 07:39:48 -0700 | [diff] [blame] | 27 | service.stamps().list().execute(http=http) |
Bu Sun Kim | 205ae59 | 2020-11-18 05:40:02 -0700 | [diff] [blame] | 28 | ``` |