From 5e290b69354a4a777467a904555a4e81906a7764 Mon Sep 17 00:00:00 2001 From: Rishi-gdrx Date: Fri, 17 Jul 2026 12:39:30 +0530 Subject: [PATCH] request to curl --- docs/topics/request-response.rst | 2 ++ scrapy/http/request/__init__.py | 10 ++++++++++ tests/test_http_request.py | 15 ++++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) 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..ba7abb830 100644 --- a/tests/test_http_request.py +++ b/tests/test_http_request.py @@ -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