Skip to content
8 changes: 8 additions & 0 deletions .hark/changes/2026-11-13_stripe-openapi_cb38740c.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
title: Update generated code
pr_url: https://github.com/stripe/stripe-python/pull/1989
semver_level: minor
is_stripe_api_change: true
---

* Release specs are identical.
2 changes: 1 addition & 1 deletion CODEGEN_VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
5b1e713ce463b45ef5e0d44fe81667a61fd28115
087107391e4d36a11e317f83346d27cabfa71bb8
13 changes: 13 additions & 0 deletions stripe/_api_requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@

from stripe._base_address import BaseAddress
from stripe._api_mode import ApiMode
from stripe._stripe_object import API_KEY_SERIALIZATION_CONSTANT

if TYPE_CHECKING:
from stripe._app_info import AppInfo
Expand Down Expand Up @@ -166,6 +167,12 @@ def _new_requestor_with_options(
"""
Returns a new _APIRequestor instance with the same HTTP client but a (potentially) updated set of options. Useful for ensuring the original isn't modified, but any options the original had are still used.
"""
if self.api_key == API_KEY_SERIALIZATION_CONSTANT:
raise error.AuthenticationError(
"This object was unpickled without API credentials. "
"Call reattach_api_key(api_key) on the object before making requests."
)

options = options or {}
new_options = self._options.to_dict()
for key in PERSISTENT_OPTIONS_KEYS:
Expand Down Expand Up @@ -702,6 +709,12 @@ def _args_for_request_with_retries(
"""
Mechanism for issuing an API call. Used by request_raw and request_raw_async.
"""
if self.api_key == API_KEY_SERIALIZATION_CONSTANT:
raise error.AuthenticationError(
"This object was unpickled without API credentials. "
"Call reattach_api_key(api_key) on the object before making requests."
)

request_options = merge_options(self._options, options)

# Special stripe_version handling for v2 requests:
Expand Down
65 changes: 43 additions & 22 deletions stripe/_http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,21 +858,24 @@ def __init__(
proxy: Optional[HTTPClient._Proxy] = None,
async_fallback_client: Optional[HTTPClient] = None,
_lib=None, # used for internal unit testing
*,
timeout: int = 80,
connect_timeout: int = 30,
):
super(PycurlClient, self).__init__(
verify_ssl_certs=verify_ssl_certs,
proxy=proxy,
async_fallback_client=async_fallback_client,
)
self._timeout = timeout
self._connect_timeout = connect_timeout

if _lib is None:
import pycurl # pyright: ignore[reportMissingModuleSource]

_lib = pycurl

self.pycurl = _lib
# Initialize this within the object so that we can reuse connections.
self._curl = _lib.Curl()

self._parsed_proxy = {}
# need to urlparse the proxy, since PyCurl
Expand All @@ -886,6 +889,20 @@ def __init__(
# but we know value to be a string because all the value types on Proxy_ are strings.
self._parsed_proxy[scheme] = urlparse(cast(str, value))

def _get_curl(self):
"""
Returns this thread's Curl handle, creating it on first use.

A libcurl easy handle must never be used by more than one thread at a
time, so each thread gets its own. Reusing a handle within a thread
lets us keep its established connections.
"""
curl = getattr(self._thread_local, "curl", None)
if curl is None:
curl = self.pycurl.Curl()
self._thread_local.curl = curl
return curl

def parse_headers(self, data):
if "\r\n" not in data:
return {}
Expand Down Expand Up @@ -944,48 +961,49 @@ def _request_internal(
# pristine state, but notably reset() doesn't reset connections, so we
# still get to take advantage of those by virtue of re-using the same
# object.
self._curl.reset()
curl = self._get_curl()
curl.reset()

proxy = self._get_proxy(url)
if proxy:
if proxy.hostname:
self._curl.setopt(self.pycurl.PROXY, proxy.hostname)
curl.setopt(self.pycurl.PROXY, proxy.hostname)
if proxy.port:
self._curl.setopt(self.pycurl.PROXYPORT, proxy.port)
curl.setopt(self.pycurl.PROXYPORT, proxy.port)
if proxy.username or proxy.password:
self._curl.setopt(
curl.setopt(
self.pycurl.PROXYUSERPWD,
"%s:%s" % (proxy.username, proxy.password),
)

if method == "get":
self._curl.setopt(self.pycurl.HTTPGET, 1)
curl.setopt(self.pycurl.HTTPGET, 1)
elif method == "post":
self._curl.setopt(self.pycurl.POST, 1)
self._curl.setopt(self.pycurl.POSTFIELDS, post_data)
curl.setopt(self.pycurl.POST, 1)
curl.setopt(self.pycurl.POSTFIELDS, post_data)
else:
self._curl.setopt(self.pycurl.CUSTOMREQUEST, method.upper())
curl.setopt(self.pycurl.CUSTOMREQUEST, method.upper())

# pycurl doesn't like unicode URLs
self._curl.setopt(self.pycurl.URL, url)
curl.setopt(self.pycurl.URL, url)

self._curl.setopt(self.pycurl.WRITEFUNCTION, b.write)
self._curl.setopt(self.pycurl.HEADERFUNCTION, rheaders.write)
self._curl.setopt(self.pycurl.NOSIGNAL, 1)
self._curl.setopt(self.pycurl.CONNECTTIMEOUT, 30)
self._curl.setopt(self.pycurl.TIMEOUT, 80)
curl.setopt(self.pycurl.WRITEFUNCTION, b.write)
curl.setopt(self.pycurl.HEADERFUNCTION, rheaders.write)
curl.setopt(self.pycurl.NOSIGNAL, 1)
curl.setopt(self.pycurl.CONNECTTIMEOUT, self._connect_timeout)
curl.setopt(self.pycurl.TIMEOUT, self._timeout)
_assert_no_header_injection(headers)
self._curl.setopt(
curl.setopt(
self.pycurl.HTTPHEADER,
["%s: %s" % (k, v) for k, v in dict(headers).items()],
)
if self._verify_ssl_certs:
self._curl.setopt(self.pycurl.CAINFO, stripe.ca_bundle_path)
curl.setopt(self.pycurl.CAINFO, stripe.ca_bundle_path)
else:
self._curl.setopt(self.pycurl.SSL_VERIFYHOST, False)
curl.setopt(self.pycurl.SSL_VERIFYHOST, False)

try:
self._curl.perform()
curl.perform()
except self.pycurl.error as e:
self._handle_request_error(e)

Expand All @@ -995,7 +1013,7 @@ def _request_internal(
else:
rcontent = b.getvalue().decode("utf-8")

rcode = self._curl.getinfo(self.pycurl.RESPONSE_CODE)
rcode = curl.getinfo(self.pycurl.RESPONSE_CODE)
headers = self.parse_headers(rheaders.getvalue().decode("utf-8"))

return rcontent, rcode, headers
Expand Down Expand Up @@ -1044,7 +1062,10 @@ def _get_proxy(self, url) -> Optional["ParseResult"]:
return None

def close(self):
pass
curl = getattr(self._thread_local, "curl", None)
if curl is not None:
curl.close()
self._thread_local.curl = None


class UrllibClient(HTTPClient):
Expand Down
49 changes: 48 additions & 1 deletion stripe/_stripe_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@
from stripe._api_requestor import _APIRequestor # pyright: ignore[reportPrivateUsage]


API_KEY_SERIALIZATION_CONSTANT = "API_KEY_SERIALIZATION_CONSTANT"


@overload
def _compute_diff(
current: Dict[str, Any], previous: Optional[Dict[str, Any]]
Expand Down Expand Up @@ -156,6 +159,50 @@ def stripe_account(self):
def stripe_version(self):
return self._requestor.stripe_version

def reattach_api_key(self, api_key: str) -> None:
"""Attach credentials to an unpickled object and its nested objects.

Each object retains its saved API version and connected account.
Objects that already have credentials cannot be reattached.
"""
if self.api_key != API_KEY_SERIALIZATION_CONSTANT:
raise ValueError(
"API credentials can only be reattached to an unpickled "
"object that has not already been reattached."
)
if (
not isinstance(cast(object, api_key), str)
or not api_key.strip()
or api_key == API_KEY_SERIALIZATION_CONSTANT
):
raise ValueError("api_key must be a non-empty, valid API key.")

from stripe._api_requestor import _APIRequestor # pyright: ignore[reportPrivateUsage]

seen: Set[int] = set()

def reattach(value: Any) -> None:
if id(value) in seen:
return
seen.add(id(value))
if isinstance(value, StripeObject):
if value.api_key == API_KEY_SERIALIZATION_CONSTANT:
value._requestor = _APIRequestor._global_with_options( # pyright: ignore[reportPrivateUsage]
api_key=api_key,
stripe_version=value.stripe_version,
stripe_account=value.stripe_account,
)
for nested in value._data.values():
reattach(nested)
elif isinstance(value, dict):
for nested in cast(Dict[Any, Any], value).values():
reattach(nested)
elif isinstance(value, (list, tuple)):
for nested in cast(Union[List[Any], Tuple[Any, ...]], value):
reattach(nested)

reattach(self)

@property
def last_response(self) -> Optional[StripeResponse]:
return self._last_response
Expand Down Expand Up @@ -298,7 +345,7 @@ def __reduce__(self) -> Tuple[Any, ...]:
type(self), # callable
( # args
getattr(self, "id", None),
self.api_key,
API_KEY_SERIALIZATION_CONSTANT,
self.stripe_version,
self.stripe_account,
),
Expand Down
91 changes: 91 additions & 0 deletions tests/api_resources/test_list_object.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import pickle

import pytest

Expand Down Expand Up @@ -297,6 +298,68 @@ def test_iter_two_pages(self, http_client_mock):

assert seen == ["pm_123", "pm_124", "pm_125", "pm_126"]

@pytest.fixture
def restored_list(self, monkeypatch):
lo = stripe.ListObject.construct_from(
self.pageable_model_response(["pm_123"], True),
"producer-key-sentinel",
stripe_account="example-account",
)
monkeypatch.setattr(stripe, "api_key", None)
restored = pickle.loads(pickle.dumps(lo))
restored.reattach_api_key("worker-key-sentinel")
return restored

def test_iter_uses_reattached_api_key_on_every_page(
self, http_client_mock, restored_list
):
http_client_mock.stub_request(
"get",
path="/v1/pageablemodels",
query_string="starting_after=pm_123",
rbody=json.dumps(self.pageable_model_response(["pm_124"], True)),
)
http_client_mock.stub_request(
"get",
path="/v1/pageablemodels",
query_string="starting_after=pm_124",
rbody=json.dumps(self.pageable_model_response(["pm_125"], False)),
)

seen = [item["id"] for item in restored_list.auto_paging_iter()]

assert seen == ["pm_123", "pm_124", "pm_125"]
for starting_after in ("pm_123", "pm_124"):
http_client_mock.assert_requested(
"get",
path="/v1/pageablemodels",
query_string=f"starting_after={starting_after}",
api_key="worker-key-sentinel",
stripe_account="example-account",
)

def test_iter_reverse_uses_reattached_api_key(
self, http_client_mock, restored_list
):
restored_list._retrieve_params = {"ending_before": "pm_124"}
http_client_mock.stub_request(
"get",
path="/v1/pageablemodels",
query_string="ending_before=pm_123",
rbody=json.dumps(self.pageable_model_response(["pm_122"], False)),
)

seen = [item["id"] for item in restored_list.auto_paging_iter()]

assert seen == ["pm_123", "pm_122"]
http_client_mock.assert_requested(
"get",
path="/v1/pageablemodels",
query_string="ending_before=pm_123",
api_key="worker-key-sentinel",
stripe_account="example-account",
)

def test_iter_reverse(self, http_client_mock):
lo = stripe.ListObject.construct_from(
self.pageable_model_response(["pm_125", "pm_126"], True), "mykey"
Expand Down Expand Up @@ -655,6 +718,34 @@ async def test_iter_one_page(self, http_client_mock):

assert seen == ["pm_123", "pm_124"]

@pytest.mark.anyio
async def test_iter_uses_reattached_api_key(
self, http_client_mock, monkeypatch
):
lo = stripe.ListObject.construct_from(
self.pageable_model_response(["pm_123"], True),
"producer-key-sentinel",
)
monkeypatch.setattr(stripe, "api_key", None)
restored = pickle.loads(pickle.dumps(lo))
restored.reattach_api_key("worker-key-sentinel")
http_client_mock.stub_request(
"get",
path="/v1/pageablemodels",
query_string="starting_after=pm_123",
rbody=json.dumps(self.pageable_model_response(["pm_124"], False)),
)

seen = [item["id"] async for item in restored.auto_paging_iter()]

assert seen == ["pm_123", "pm_124"]
http_client_mock.assert_requested(
"get",
path="/v1/pageablemodels",
query_string="starting_after=pm_123",
api_key="worker-key-sentinel",
)

@pytest.mark.anyio
async def test_iter_two_pages(self, http_client_mock):
lo = stripe.ListObject.construct_from(
Expand Down
Loading
Loading