request to curl

This commit is contained in:
Rishi-gdrx 2026-07-17 12:39:30 +05:30
parent 870803b7fb
commit 5e290b6935
3 changed files with 26 additions and 1 deletions

View File

@ -257,6 +257,8 @@ Request objects
.. automethod:: from_curl
.. automethod:: to_curl
.. automethod:: to_dict

View File

@ -381,6 +381,16 @@ class Request(object_ref):
request_kwargs.update(kwargs)
return cls(**request_kwargs)
def to_curl(self) -> str:
"""Return a string with a cURL command equivalent to this request.
Inverse of :meth:`from_curl`. See also
:func:`scrapy.utils.request.request_to_curl`.
"""
from scrapy.utils.request import request_to_curl
return request_to_curl(self)
def to_dict(self, *, spider: scrapy.Spider | None = None) -> dict[str, Any]:
"""Return a dictionary containing the Request's data.

View File

@ -404,7 +404,20 @@ class TestRequest:
def test_no_callback(self):
with pytest.raises(RuntimeError):
NO_CALLBACK()
def test_to_curl(self):
request = self.request_class(
"https://www.httpbin.org/post",
method="POST",
headers={"Content-Type": "application/json"},
body='{"foo": "bar"}',
)
assert request.to_curl() == (
"curl -X POST https://www.httpbin.org/post"
' --data-raw \'{"foo": "bar"}\''
" -H 'Content-Type: application/json'"
)
def test_from_curl(self):
# Note: more curated tests regarding curl conversion are in