-
-
Notifications
You must be signed in to change notification settings - Fork 271
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add customizable response objects (#398)
- Loading branch information
Showing
3 changed files
with
59 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
from curl_cffi import requests | ||
from curl_cffi.curl import Curl, CurlInfo | ||
from typing import cast | ||
|
||
class CustomResponse(requests.Response): | ||
def __init__(self, curl: Curl | None = None, request: requests.Request | None = None): | ||
super().__init__(curl, request) | ||
self.local_port = cast(int, curl.getinfo(CurlInfo.LOCAL_PORT)) | ||
self.connect_time = cast(float, curl.getinfo(CurlInfo.CONNECT_TIME)) | ||
|
||
@property | ||
def status(self): | ||
return self.status_code | ||
|
||
def custom_method(self): | ||
return "this is a custom method" | ||
|
||
session = requests.Session(response_class=CustomResponse) | ||
response: CustomResponse = session.get("http://example.com") | ||
print(f"{response.status=}") | ||
print(response.custom_method()) | ||
print(f"{response.local_port=}") | ||
print(f"{response.connect_time=}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import pytest | ||
from curl_cffi import requests | ||
|
||
def test_default_response(): | ||
response = requests.get("http://example.com") | ||
assert type(response) == requests.Response | ||
print(response.status_code) | ||
|
||
class CustomResponse(requests.Response): | ||
@property | ||
def status(self): | ||
return self.status_code | ||
|
||
def test_custom_response(): | ||
session = requests.Session(response_class=CustomResponse) | ||
response = session.get("http://example.com") | ||
assert isinstance(response, CustomResponse) | ||
assert hasattr(response, "status") | ||
print(response.status) | ||
|
||
class WrongTypeResponse: pass | ||
|
||
def test_wrong_type_custom_response(): | ||
with pytest.raises(TypeError): | ||
requests.Session(response_class=WrongTypeResponse) |