From 5a9a414d82931d16de65e7a95dc476b33f94bfd0 Mon Sep 17 00:00:00 2001 From: Rishi-gdrx Date: Fri, 17 Jul 2026 13:59:30 +0530 Subject: [PATCH] Add Request.to_curl() as the inverse of Request.from_curl() Closes #7743. Co-authored-by: Cursor --- docs/topics/request-response.rst | 2 ++ scrapy/http/request/__init__.py | 10 ++++++++++ tests/test_http_request.py | 13 +++++++++++++ 3 files changed, 25 insertions(+) diff --git a/docs/topics/request-response.rst b/docs/topics/request-response.rst index f2fcfb0b5..624a5c8dd 100644 --- a/docs/topics/request-response.rst +++ b/docs/topics/request-response.rst @@ -257,6 +257,8 @@ Request objects .. automethod:: from_curl + .. automethod:: to_curl + .. automethod:: to_dict diff --git a/scrapy/http/request/__init__.py b/scrapy/http/request/__init__.py index 73c2e7dd4..ce43dccb8 100644 --- a/scrapy/http/request/__init__.py +++ b/scrapy/http/request/__init__.py @@ -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. diff --git a/tests/test_http_request.py b/tests/test_http_request.py index 1941b826f..fb752dd50 100644 --- a/tests/test_http_request.py +++ b/tests/test_http_request.py @@ -406,6 +406,19 @@ class TestRequest: 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 # `test_utils_curl.py`