Skip to content

Commit

Permalink
Merge pull request #3 from rishabhsingh971/add-req-to-curl
Browse files Browse the repository at this point in the history
Add req to curl
  • Loading branch information
rishabhsingh971 authored Sep 25, 2023
2 parents eab156e + 427e240 commit 97d09db
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "pyutils"
version = "0.0.1a2"
version = "0.0.1a3"
description = "collection of python utility functions"
authors = ["Rishabh Singh <rishabhsingh971@gmail.com>"]
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion pyutils/httpu/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from pyutils.httpu.main import req
from pyutils.httpu.main import req, req_to_curl, to_curl
32 changes: 31 additions & 1 deletion pyutils/httpu/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import requests
import json
import os

import requests

from pyutils.logu.main import logger


def _ensure_user_agent(headers: dict):
if "User-Agent" in headers or "user-agent" in headers:
return
Expand Down Expand Up @@ -56,3 +60,29 @@ def req(
)
)
return res, e

def req_to_curl(req: requests.Request) -> str:
return to_curl(
url=req.url,
method=req.method,
headers=req.headers,
cookies=getattr(req, "cookies", None),
payload=getattr(req, "body", None),
)


def to_curl(url:str, method: str, headers: dict, cookies: dict, payload: any) -> str:
command = "curl -X {method} -H {headers} -d '{data}' '{uri}'"
data = ""
if cookies:
headers["Cookies"] = ";".join([f"{k}:{v}" for k, v in cookies.items()])
if payload:
if isinstance(payload, str):
data = payload
elif isinstance(payload, bytes):
data = payload.decode()
else:
data = json.dumps(payload)
header_list = ['"{0}: {1}"'.format(k, v) for k, v in headers.items()]
header = " -H ".join(header_list)
return command.format(method=method, headers=header, data=data, uri=url)

0 comments on commit 97d09db

Please sign in to comment.