Skip to content

Commit 5cca06e

Browse files
committed
add HttpRequest command #78
1 parent 2d2fca9 commit 5cca06e

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

mara_pipelines/commands/http.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""Commands for interacting with HTTP"""
2+
3+
from mara_page import html, _
4+
from .. import pipelines
5+
from ..shell import http_request_command
6+
7+
8+
class HttpRequest(pipelines.Command):
9+
def __init__(self, url: str, headers: {str: str} = None, method: str = None, body: str = None) -> None:
10+
"""
11+
Executes a HTTP request
12+
13+
Args:
14+
url: The url
15+
headers: The HTTP headers as dict
16+
method: The HTTP method to be used
17+
body: The body string to be used in the HTTP request
18+
"""
19+
super().__init__()
20+
self.url = url
21+
self.headers = headers
22+
self.method = method
23+
self.body = body
24+
25+
def shell_command(self):
26+
return http_request_command(self.url, self.headers, self.method, self.body)
27+
28+
def html_doc_items(self) -> [(str, str)]:
29+
return [
30+
('method', _.tt[self.method or 'GET']),
31+
('url', _.tt[self.url]),
32+
('headers', _.pre[
33+
'\n'.join([f'{header}: {content}' for header, content in self.headers.items()]) if self.headers else ''
34+
]),
35+
('body', _.pre[self.body or '']),
36+
('command', html.highlight_syntax(self.shell_command(), 'bash'))
37+
]

mara_pipelines/shell.py

+26
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Command execution in bash shells"""
22

33
import time
4+
import shlex
45

56
from . import config
67
from .logging import logger
@@ -84,5 +85,30 @@ def quote(s):
8485
+ '"'
8586

8687

88+
def http_request_command(url: str, headers: {str: str} = None, method: str = 'GET', body: str = None, body_from_stdin: bool = False) -> str:
89+
"""
90+
Creates a curl command sending a HTTP request
91+
92+
Args:
93+
url: The url
94+
headers: The HTTP headers as dict
95+
method: The HTTP method to be used
96+
body: The body string to be used in the HTTP request
97+
body_from_stdin: Read the body for the HTTP request from stdin
98+
"""
99+
if body and body_from_stdin:
100+
raise ValueError('You can only use body or body_from_stdin but not both')
101+
102+
def quote(s):
103+
return str(s).replace('\\', '\\\\').replace('"', '\\"')
104+
105+
return ("curl -sf"
106+
+ (f' -X {method}' if method and method != 'GET' else '')
107+
+ (''.join([f' -H "{quote(header)}: {quote(content)}"' for header, content in headers.items()]) if headers else '')
108+
+ (f' --data {shlex.quote(body)}' if body else '')
109+
+ (' --data-binary @-' if body_from_stdin else '')
110+
+ f" {shlex.quote(url)}")
111+
112+
87113
if __name__ == "__main__":
88114
run_shell_command('ping -c 3 google.com; ping null')

0 commit comments

Comments
 (0)