2012-03-14 14:17:39 +03:00
|
|
|
import os
|
2012-03-04 12:48:30 +03:00
|
|
|
import json
|
|
|
|
import argparse
|
2012-04-17 04:28:08 +03:00
|
|
|
import re
|
2012-03-04 12:48:30 +03:00
|
|
|
from collections import namedtuple
|
|
|
|
from . import pretty
|
|
|
|
from . import __doc__ as doc
|
|
|
|
from . import __version__ as version
|
|
|
|
|
|
|
|
|
|
|
|
SEP_COMMON = ':'
|
|
|
|
SEP_HEADERS = SEP_COMMON
|
|
|
|
SEP_DATA = '='
|
|
|
|
SEP_DATA_RAW_JSON = ':='
|
2012-03-14 14:17:39 +03:00
|
|
|
SEP_FILES = '@'
|
2012-03-04 12:48:30 +03:00
|
|
|
PRETTIFY_STDOUT_TTY_ONLY = object()
|
|
|
|
|
2012-03-14 02:05:44 +03:00
|
|
|
OUT_REQUEST_HEADERS = 'H'
|
|
|
|
OUT_REQUEST_BODY = 'B'
|
|
|
|
OUT_RESPONSE_HEADERS = 'h'
|
|
|
|
OUT_RESPONSE_BODY = 'b'
|
|
|
|
|
|
|
|
OUTPUT_OPTIONS = [OUT_REQUEST_HEADERS,
|
|
|
|
OUT_REQUEST_BODY,
|
|
|
|
OUT_RESPONSE_HEADERS,
|
|
|
|
OUT_RESPONSE_BODY]
|
|
|
|
|
2012-03-04 12:48:30 +03:00
|
|
|
|
|
|
|
class ParseError(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
KeyValue = namedtuple('KeyValue', ['key', 'value', 'sep', 'orig'])
|
|
|
|
|
|
|
|
class KeyValueType(object):
|
|
|
|
"""A type used with `argparse`."""
|
|
|
|
def __init__(self, *separators):
|
|
|
|
self.separators = separators
|
2012-04-19 02:18:00 +03:00
|
|
|
self.escapes = ['\\\\' + sep for sep in separators]
|
2012-03-04 12:48:30 +03:00
|
|
|
|
|
|
|
def __call__(self, string):
|
2012-04-17 04:28:08 +03:00
|
|
|
found = {}
|
2012-04-19 02:18:00 +03:00
|
|
|
found_escapes = []
|
|
|
|
for esc in self.escapes:
|
|
|
|
found_escapes += [m.span() for m in re.finditer(esc, string)]
|
2012-04-17 04:28:08 +03:00
|
|
|
for sep in self.separators:
|
2012-04-19 02:18:00 +03:00
|
|
|
matches = re.finditer(sep, string)
|
|
|
|
for match in matches:
|
|
|
|
start, end = match.span()
|
|
|
|
inside_escape = False
|
|
|
|
for estart, eend in found_escapes:
|
|
|
|
if start >= estart and end <= eend:
|
|
|
|
inside_escape = True
|
|
|
|
break
|
|
|
|
if not inside_escape:
|
|
|
|
found[start] = sep
|
2012-03-04 12:48:30 +03:00
|
|
|
|
|
|
|
if not found:
|
|
|
|
#noinspection PyExceptionInherit
|
|
|
|
raise argparse.ArgumentTypeError(
|
|
|
|
'"%s" is not a valid value' % string)
|
2012-04-17 04:28:08 +03:00
|
|
|
|
|
|
|
# split the string at the earliest non-escaped separator.
|
|
|
|
seploc = min(found.keys())
|
|
|
|
sep = found[seploc]
|
|
|
|
key = string[:seploc]
|
|
|
|
value = string[seploc + len(sep):]
|
|
|
|
|
|
|
|
# remove escape chars
|
|
|
|
for sepstr in self.separators:
|
|
|
|
key = key.replace('\\' + sepstr, sepstr)
|
|
|
|
value = value.replace('\\' + sepstr, sepstr)
|
2012-03-04 12:48:30 +03:00
|
|
|
return KeyValue(key=key, value=value, sep=sep, orig=string)
|
|
|
|
|
|
|
|
|
2012-03-14 14:17:39 +03:00
|
|
|
def parse_items(items, data=None, headers=None, files=None):
|
|
|
|
"""Parse `KeyValueType` `items` into `data`, `headers` and `files`."""
|
2012-03-04 12:48:30 +03:00
|
|
|
if headers is None:
|
|
|
|
headers = {}
|
|
|
|
if data is None:
|
|
|
|
data = {}
|
2012-03-14 14:17:39 +03:00
|
|
|
if files is None:
|
|
|
|
files = {}
|
2012-03-04 12:48:30 +03:00
|
|
|
for item in items:
|
|
|
|
value = item.value
|
2012-03-14 14:17:39 +03:00
|
|
|
key = item.key
|
2012-03-04 12:48:30 +03:00
|
|
|
if item.sep == SEP_HEADERS:
|
|
|
|
target = headers
|
2012-03-14 14:17:39 +03:00
|
|
|
elif item.sep == SEP_FILES:
|
|
|
|
try:
|
|
|
|
value = open(os.path.expanduser(item.value), 'r')
|
|
|
|
except IOError as e:
|
|
|
|
raise ParseError(
|
|
|
|
'Invalid argument %r. %s' % (item.orig, e))
|
|
|
|
if not key:
|
|
|
|
key = os.path.basename(value.name)
|
|
|
|
target = files
|
2012-03-04 12:48:30 +03:00
|
|
|
elif item.sep in [SEP_DATA, SEP_DATA_RAW_JSON]:
|
|
|
|
if item.sep == SEP_DATA_RAW_JSON:
|
|
|
|
try:
|
|
|
|
value = json.loads(item.value)
|
|
|
|
except ValueError:
|
|
|
|
raise ParseError('%s is not valid JSON' % item.orig)
|
|
|
|
target = data
|
|
|
|
else:
|
|
|
|
raise ParseError('%s is not valid item' % item.orig)
|
|
|
|
|
2012-03-14 14:17:39 +03:00
|
|
|
if key in target:
|
2012-03-04 12:48:30 +03:00
|
|
|
ParseError('duplicate item %s (%s)' % (item.key, item.orig))
|
|
|
|
|
2012-03-14 14:17:39 +03:00
|
|
|
target[key] = value
|
2012-03-04 12:48:30 +03:00
|
|
|
|
2012-03-14 14:17:39 +03:00
|
|
|
return headers, data, files
|
2012-03-04 12:48:30 +03:00
|
|
|
|
|
|
|
|
|
|
|
def _(text):
|
|
|
|
"""Normalize white space."""
|
|
|
|
return ' '.join(text.strip().split())
|
|
|
|
|
|
|
|
|
2012-03-14 02:05:44 +03:00
|
|
|
class HTTPieArgumentParser(argparse.ArgumentParser):
|
|
|
|
def parse_args(self, args=None, namespace=None):
|
|
|
|
args = super(HTTPieArgumentParser, self).parse_args(args, namespace)
|
|
|
|
self._validate_output_options(args)
|
2012-04-11 14:47:47 +03:00
|
|
|
self._validate_auth_options(args)
|
2012-03-14 02:05:44 +03:00
|
|
|
return args
|
|
|
|
|
|
|
|
def _validate_output_options(self, args):
|
|
|
|
unknown_output_options = set(args.output_options) - set(OUTPUT_OPTIONS)
|
|
|
|
if unknown_output_options:
|
|
|
|
self.error('Unknown output options: %s' % ','.join(unknown_output_options))
|
|
|
|
|
2012-04-11 14:47:47 +03:00
|
|
|
def _validate_auth_options(self, args):
|
|
|
|
if args.auth_type and not args.auth:
|
|
|
|
self.error('--auth-type can only be used with --auth')
|
|
|
|
|
|
|
|
|
2012-03-14 02:05:44 +03:00
|
|
|
|
|
|
|
parser = HTTPieArgumentParser(description=doc.strip(),)
|
2012-03-04 12:49:37 +03:00
|
|
|
parser.add_argument('--version', action='version', version=version)
|
2012-03-04 12:48:30 +03:00
|
|
|
|
|
|
|
# Content type.
|
|
|
|
#############################################
|
|
|
|
|
|
|
|
group_type = parser.add_mutually_exclusive_group(required=False)
|
|
|
|
group_type.add_argument(
|
|
|
|
'--json', '-j', action='store_true',
|
|
|
|
help=_('''
|
|
|
|
Serialize data items as a JSON object and set
|
|
|
|
Content-Type to application/json, if not specified.
|
|
|
|
''')
|
|
|
|
)
|
|
|
|
group_type.add_argument(
|
|
|
|
'--form', '-f', action='store_true',
|
|
|
|
help=_('''
|
2012-03-14 14:17:39 +03:00
|
|
|
Serialize fields as form values. The Content-Type is set to application/x-www-form-urlencoded.
|
|
|
|
The presence of any file fields results into a multipart/form-data request.
|
|
|
|
Note that Content-Type is not automatically set if explicitely specified.
|
2012-03-04 12:48:30 +03:00
|
|
|
''')
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2012-03-14 02:05:44 +03:00
|
|
|
# output_options options.
|
2012-03-04 12:48:30 +03:00
|
|
|
#############################################
|
|
|
|
|
|
|
|
parser.add_argument(
|
|
|
|
'--traceback', action='store_true', default=False,
|
|
|
|
help=_('''
|
|
|
|
Print exception traceback should one occur.
|
|
|
|
''')
|
|
|
|
)
|
|
|
|
|
|
|
|
prettify = parser.add_mutually_exclusive_group(required=False)
|
|
|
|
prettify.add_argument(
|
2012-03-14 02:05:44 +03:00
|
|
|
'--pretty', dest='prettify', action='store_true',
|
2012-03-04 12:48:30 +03:00
|
|
|
default=PRETTIFY_STDOUT_TTY_ONLY,
|
|
|
|
help=_('''
|
2012-03-14 02:05:44 +03:00
|
|
|
If stdout is a terminal, the response is prettified
|
|
|
|
by default (colorized and indented if it is JSON).
|
|
|
|
This flag ensures prettifying even when stdout is redirected.
|
2012-03-04 12:48:30 +03:00
|
|
|
''')
|
|
|
|
)
|
|
|
|
prettify.add_argument(
|
|
|
|
'--ugly', '-u', dest='prettify', action='store_false',
|
|
|
|
help=_('''
|
|
|
|
Do not prettify the response.
|
|
|
|
''')
|
|
|
|
)
|
|
|
|
|
2012-03-14 02:05:44 +03:00
|
|
|
output_options = parser.add_mutually_exclusive_group(required=False)
|
|
|
|
output_options.add_argument('--print', '-p', dest='output_options',
|
|
|
|
default=OUT_RESPONSE_HEADERS + OUT_RESPONSE_BODY,
|
|
|
|
help=_('''
|
|
|
|
String specifying what should the output contain.
|
|
|
|
"{request_headers}" stands for request headers and
|
|
|
|
"{request_body}" for request body.
|
|
|
|
"{response_headers}" stands for response headers and
|
|
|
|
"{response_body}" for response body.
|
|
|
|
Defaults to "hb" which means that the whole response
|
|
|
|
(headers and body) is printed.
|
|
|
|
'''.format(
|
|
|
|
request_headers=OUT_REQUEST_HEADERS,
|
|
|
|
request_body=OUT_REQUEST_BODY,
|
|
|
|
response_headers=OUT_RESPONSE_HEADERS,
|
|
|
|
response_body=OUT_RESPONSE_BODY,
|
|
|
|
))
|
|
|
|
)
|
2012-03-14 13:14:28 +03:00
|
|
|
output_options.add_argument(
|
|
|
|
'--verbose', '-v', dest='output_options',
|
|
|
|
action='store_const', const=''.join(OUTPUT_OPTIONS),
|
|
|
|
help=_('''
|
|
|
|
Print the whole request as well as response.
|
|
|
|
Shortcut for --print={0}.
|
|
|
|
'''.format(''.join(OUTPUT_OPTIONS)))
|
|
|
|
)
|
2012-03-14 02:05:44 +03:00
|
|
|
output_options.add_argument(
|
|
|
|
'--headers', '-t', dest='output_options',
|
|
|
|
action='store_const', const=OUT_RESPONSE_HEADERS,
|
|
|
|
help=_('''
|
2012-03-04 12:48:30 +03:00
|
|
|
Print only the response headers.
|
2012-03-14 13:14:28 +03:00
|
|
|
Shortcut for --print={0}.
|
2012-03-14 02:05:44 +03:00
|
|
|
'''.format(OUT_RESPONSE_HEADERS))
|
2012-03-04 12:48:30 +03:00
|
|
|
)
|
2012-03-14 02:05:44 +03:00
|
|
|
output_options.add_argument(
|
|
|
|
'--body', '-b', dest='output_options',
|
|
|
|
action='store_const', const=OUT_RESPONSE_BODY,
|
|
|
|
help=_('''
|
2012-03-04 12:48:30 +03:00
|
|
|
Print only the response body.
|
2012-03-14 13:14:28 +03:00
|
|
|
Shortcut for --print={0}.
|
2012-03-14 02:05:44 +03:00
|
|
|
'''.format(OUT_RESPONSE_BODY))
|
2012-03-04 12:48:30 +03:00
|
|
|
)
|
2012-03-14 02:05:44 +03:00
|
|
|
|
2012-03-04 12:48:30 +03:00
|
|
|
parser.add_argument(
|
|
|
|
'--style', '-s', dest='style', default='solarized', metavar='STYLE',
|
|
|
|
choices=pretty.AVAILABLE_STYLES,
|
|
|
|
help=_('''
|
|
|
|
Output coloring style, one of %s. Defaults to solarized.
|
|
|
|
''') % ', '.join(sorted(pretty.AVAILABLE_STYLES))
|
|
|
|
)
|
|
|
|
|
|
|
|
# ``requests.request`` keyword arguments.
|
|
|
|
parser.add_argument(
|
|
|
|
'--auth', '-a', help='username:password',
|
|
|
|
type=KeyValueType(SEP_COMMON)
|
|
|
|
)
|
2012-03-22 17:40:03 +03:00
|
|
|
|
|
|
|
parser.add_argument(
|
2012-04-11 14:47:47 +03:00
|
|
|
'--auth-type', choices=['basic', 'digest'],
|
|
|
|
help=_('The type of authentication ("basic" or "digest"). Defaults to "basic".')
|
2012-03-22 17:40:03 +03:00
|
|
|
)
|
|
|
|
|
2012-03-04 12:48:30 +03:00
|
|
|
parser.add_argument(
|
2012-04-11 13:44:02 +03:00
|
|
|
'--verify', default='yes',
|
2012-03-04 12:48:30 +03:00
|
|
|
help=_('''
|
2012-04-11 13:44:02 +03:00
|
|
|
Set to "no" to skip checking the host\'s SSL certificate.
|
2012-03-04 12:48:30 +03:00
|
|
|
You can also pass the path to a CA_BUNDLE
|
|
|
|
file for private certs. You can also set
|
|
|
|
the REQUESTS_CA_BUNDLE environment variable.
|
2012-04-11 13:44:02 +03:00
|
|
|
Defaults to "yes".
|
2012-03-04 12:48:30 +03:00
|
|
|
''')
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'--proxy', default=[], action='append',
|
|
|
|
type=KeyValueType(SEP_COMMON),
|
|
|
|
help=_('''
|
|
|
|
String mapping protocol to the URL of the proxy
|
|
|
|
(e.g. http:foo.bar:3128).
|
|
|
|
''')
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'--allow-redirects', default=False, action='store_true',
|
|
|
|
help=_('''
|
|
|
|
Set this flag if full redirects are allowed
|
|
|
|
(e.g. re-POST-ing of data at new ``Location``)
|
|
|
|
''')
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'--timeout', type=float,
|
|
|
|
help=_('''
|
|
|
|
Float describes the timeout of the request
|
|
|
|
(Use socket.setdefaulttimeout() as fallback).
|
|
|
|
''')
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# Positional arguments.
|
|
|
|
#############################################
|
|
|
|
|
|
|
|
parser.add_argument(
|
|
|
|
'method', metavar='METHOD',
|
|
|
|
help=_('''
|
|
|
|
HTTP method to be used for the request
|
|
|
|
(GET, POST, PUT, DELETE, PATCH, ...).
|
|
|
|
''')
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'url', metavar='URL',
|
|
|
|
help=_('''
|
|
|
|
Protocol defaults to http:// if the
|
|
|
|
URL does not include it.
|
|
|
|
''')
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'items', nargs='*',
|
2012-03-14 14:17:39 +03:00
|
|
|
type=KeyValueType(SEP_COMMON, SEP_DATA, SEP_DATA_RAW_JSON, SEP_FILES),
|
2012-03-04 12:48:30 +03:00
|
|
|
help=_('''
|
2012-03-14 14:17:39 +03:00
|
|
|
HTTP header (header:value), data field (field=value),
|
|
|
|
raw JSON field (field:=value)
|
|
|
|
or file field (field@/path/to/file).
|
2012-03-04 12:48:30 +03:00
|
|
|
''')
|
|
|
|
)
|