Session commands.

This commit is contained in:
Jakub Roztocil 2012-12-11 12:54:34 +01:00
parent f2d59ba6bd
commit 9ec328ff6f
8 changed files with 163 additions and 71 deletions

View File

@ -919,15 +919,20 @@ following keys:
For instance, you can use this option to change For instance, you can use this option to change
the default style and output options: the default style and output options:
``"default_options": ["--style=fruity", "--body"]`` ``"default_options": ["--style=fruity", "--body"]``
Another useful default option is
``"--session=default"`` to make HTTPie always
use `sessions`_.
Default options from config file can be unset Default options from config file can be unset
via ``--no-OPTION`` arguments passed on the for a particular invocation via
command line (e.g., ``--no-style`` would unset ``--no-OPTION`` arguments passed on the
``fruity`` as the default style for the command line (e.g., ``--no-style``
particular invocation). or ``--no-session``).
========================= ================================================= ========================= =================================================
The default location is ``~/.httpie/config.json`` The default location of the configuration file is ``~/.httpie/config.json``
(``%APPDATA%\httpie\config.json`` on Windows). (or ``%APPDATA%\httpie\config.json`` on Windows).
The config directory location can be changed by setting the The config directory location can be changed by setting the
``HTTPIE_CONFIG_DIR`` environment variable. ``HTTPIE_CONFIG_DIR`` environment variable.
@ -942,10 +947,17 @@ HTTP requests. The ``httpie`` command, on the other hand, is a utility for
managing your configuration. The currently supported actions are: managing your configuration. The currently supported actions are:
* ``httpie session list [hostname]`` ``httpie session list [hostname]``:
* ``httpie session edit hostname session-name`` List all existing sessions, or a host's sessions only.
* ``httpie session show hostname session-name``
* ``httpie session delete hostname [session-name]`` ``httpie session edit hostname session-name``:
Create and/or edit a session file in $EDITOR.
``httpie session show hostname session-name``:
Print a session data to the console.
``httpie session delete hostname [session-name]``
Delete all host's sessions or a specific one by name.
========= =========

View File

@ -12,9 +12,9 @@ from requests.compat import is_windows
from . import __doc__ from . import __doc__
from . import __version__ from . import __version__
from .sessions import DEFAULT_SESSIONS_DIR from .sessions import DEFAULT_SESSIONS_DIR
from .manage import session_name_validator
from .output import AVAILABLE_STYLES, DEFAULT_STYLE from .output import AVAILABLE_STYLES, DEFAULT_STYLE
from .input import (Parser, AuthCredentialsArgType, from .input import (Parser, AuthCredentialsArgType, KeyValueArgType,
KeyValueArgType, SessionNameArgType,
SEP_PROXY, SEP_CREDENTIALS, SEP_GROUP_ITEMS, SEP_PROXY, SEP_CREDENTIALS, SEP_GROUP_ITEMS,
OUT_REQ_HEAD, OUT_REQ_BODY, OUT_RESP_HEAD, OUT_REQ_HEAD, OUT_REQ_BODY, OUT_RESP_HEAD,
OUT_RESP_BODY, OUTPUT_OPTIONS, OUT_RESP_BODY, OUTPUT_OPTIONS,
@ -225,7 +225,7 @@ sessions = parser.add_argument_group(title='Sessions')\
.add_mutually_exclusive_group(required=False) .add_mutually_exclusive_group(required=False)
sessions.add_argument( sessions.add_argument(
'--session', metavar='SESSION_NAME', type=SessionNameArgType(), '--session', metavar='SESSION_NAME', type=session_name_validator,
help=_(''' help=_('''
Create, or reuse and update a session. Create, or reuse and update a session.
Within a session, custom headers, auth credential, as well as any Within a session, custom headers, auth credential, as well as any

View File

@ -26,15 +26,15 @@ from .output import build_output_stream, write, write_with_colors_win_p3k
from . import ExitStatus from . import ExitStatus
def get_exist_status_code(code, follow=False): def get_exit_status(http_status, follow=False):
"""Translate HTTP status code to exit status code.""" """Translate HTTP status code to exit status code."""
if 300 <= code <= 399 and not follow: if 300 <= http_status <= 399 and not follow:
# Redirect # Redirect
return ExitStatus.ERROR_HTTP_3XX return ExitStatus.ERROR_HTTP_3XX
elif 400 <= code <= 499: elif 400 <= http_status <= 499:
# Client Error # Client Error
return ExitStatus.ERROR_HTTP_4XX return ExitStatus.ERROR_HTTP_4XX
elif 500 <= code <= 599: elif 500 <= http_status <= 599:
# Server Error # Server Error
return ExitStatus.ERROR_HTTP_5XX return ExitStatus.ERROR_HTTP_5XX
else: else:
@ -67,12 +67,12 @@ def main(args=sys.argv[1:], env=Environment()):
debug = '--debug' in args debug = '--debug' in args
traceback = debug or '--traceback' in args traceback = debug or '--traceback' in args
exit_status_code = ExitStatus.OK exit_status = ExitStatus.OK
if debug: if debug:
print_debug_info(env) print_debug_info(env)
if args == ['--debug']: if args == ['--debug']:
return exit_status_code return exit_status
try: try:
args = parser.parse_args(args=args, env=env) args = parser.parse_args(args=args, env=env)
@ -80,18 +80,18 @@ def main(args=sys.argv[1:], env=Environment()):
response = get_response(args, config_dir=env.config.directory) response = get_response(args, config_dir=env.config.directory)
if args.check_status: if args.check_status:
exit_status_code = get_exist_status_code(response.status_code, exit_status = get_exit_status(response.status_code, args.follow)
args.follow)
if not env.stdout_isatty and exit_status_code != ExitStatus.OK: if not env.stdout_isatty and exit_status != ExitStatus.OK:
error('HTTP %s %s', error('HTTP %s %s',
response.raw.status, response.raw.status,
response.raw.reason, response.raw.reason,
level='warning') level='warning')
write_kwargs = { write_kwargs = {
'stream': build_output_stream( 'stream': build_output_stream(args, env,
args, env, response.request, response), response.request,
response),
'outfile': env.stdout, 'outfile': env.stdout,
'flush': env.stdout_isatty or args.stream 'flush': env.stdout_isatty or args.stream
} }
@ -112,10 +112,10 @@ def main(args=sys.argv[1:], env=Environment()):
if traceback: if traceback:
raise raise
env.stderr.write('\n') env.stderr.write('\n')
exit_status_code = ExitStatus.ERROR exit_status = ExitStatus.ERROR
except requests.Timeout: except requests.Timeout:
exit_status_code = ExitStatus.ERROR_TIMEOUT exit_status = ExitStatus.ERROR_TIMEOUT
error('Request timed out (%ss).', args.timeout) error('Request timed out (%ss).', args.timeout)
except Exception as e: except Exception as e:
@ -124,6 +124,6 @@ def main(args=sys.argv[1:], env=Environment()):
if traceback: if traceback:
raise raise
error('%s: %s', type(e).__name__, str(e)) error('%s: %s', type(e).__name__, str(e))
exit_status_code = ExitStatus.ERROR exit_status = ExitStatus.ERROR
return exit_status_code return exit_status

View File

@ -8,7 +8,7 @@ import json
import mimetypes import mimetypes
import getpass import getpass
from io import BytesIO from io import BytesIO
from argparse import ArgumentParser, ArgumentTypeError from argparse import ArgumentParser, ArgumentTypeError, ArgumentError
try: try:
from collections import OrderedDict from collections import OrderedDict
@ -171,7 +171,6 @@ class Parser(ArgumentParser):
msg = 'unrecognized arguments: %s' msg = 'unrecognized arguments: %s'
self.error(msg % ' '.join(invalid)) self.error(msg % ' '.join(invalid))
def _print_message(self, message, file=None): def _print_message(self, message, file=None):
# Sneak in our stderr/stdout. # Sneak in our stderr/stdout.
file = { file = {
@ -308,6 +307,38 @@ class KeyValue(object):
return self.__dict__ == other.__dict__ return self.__dict__ == other.__dict__
def session_name_arg_type(name):
from .sessions import Session
if not Session.is_valid_name(name):
raise ArgumentTypeError(
'special characters and spaces are not'
' allowed in session names: "%s"'
% name)
return name
def host_name_arg_type(name):
from .sessions import Host
if not Host.is_valid_name(name):
raise ArgumentTypeError(
'special characters and spaces are not'
' allowed in host names: "%s"'
% name)
return name
class RegexValidator(object):
def __init__(self, pattern, error_message):
self.pattern = re.compile(pattern)
self.error_message = error_message
def __call__(self, value):
if not self.pattern.search(value):
raise ArgumentError(None, self.error_message)
return value
class KeyValueArgType(object): class KeyValueArgType(object):
"""A key-value pair argument type used with `argparse`. """A key-value pair argument type used with `argparse`.

View File

@ -4,11 +4,14 @@ Provides the `httpie' management command.
Note that the main `http' command points to `httpie.__main__.main()`. Note that the main `http' command points to `httpie.__main__.main()`.
""" """
import inspect
import argparse import argparse
from argparse import OPTIONAL import functools
from . import __version__ from . import __version__
from .sessions import (command_session_list, from .input import RegexValidator
from .sessions import (Session, Host,
command_session_list,
command_session_edit, command_session_edit,
command_session_show, command_session_show,
command_session_delete) command_session_delete)
@ -25,34 +28,78 @@ subparsers = parser.add_subparsers()
# Session commands # Session commands
################################################################# #################################################################
hostname_validator = RegexValidator(
Host.VALID_NAME_PATTERN,
'Hostname contains invalid characters.'
)
session_name_validator = RegexValidator(
Session.VALID_NAME_PATTERN,
'Session name contains invalid characters.'
)
def make_command(func):
@functools.wraps(func)
def wrapper(parsed_args):
"""Convert parsed args to function kwargs."""
kwargs = dict((name, getattr(parsed_args, name, None))
for name in inspect.getargspec(func).args)
return func(**kwargs)
return wrapper
def add_hostname_arg(parser, *args, **kwargs):
parser.add_argument(
'hostname', metavar='HOSTNAME',
type=hostname_validator,
*args, **kwargs
)
def add_session_name_arg(parser, *args, **kwargs):
parser.add_argument(
'session_name', metavar='SESSION_NAME',
type=session_name_validator,
*args, **kwargs
)
session = subparsers.add_parser('session', session = subparsers.add_parser('session',
help='manipulate and inspect sessions').add_subparsers() help='manipulate and inspect sessions').add_subparsers()
# List # List
list_ = session.add_parser('list', help='list sessions') session_list_parser = session.add_parser('list', help='list sessions')
list_.set_defaults(command=command_session_list) session_list_parser.set_defaults(command=make_command(command_session_list))
list_.add_argument('host', nargs=OPTIONAL) add_hostname_arg(session_list_parser, nargs=argparse.OPTIONAL)
# Show # Show
show = session.add_parser('show', help='show a session') session_show_parser = session.add_parser('show', help='show a session')
show.set_defaults(command=command_session_show) session_show_parser.set_defaults(command=make_command(command_session_show))
show.add_argument('host') add_hostname_arg(session_show_parser)
show.add_argument('name') add_session_name_arg(session_show_parser)
# Edit # Edit
edit = session.add_parser( session_edit_parser = session.add_parser(
'edit', help='edit a session in $EDITOR') 'edit', help='edit a session in $EDITOR')
edit.set_defaults(command=command_session_edit) session_edit_parser.set_defaults(command=make_command(command_session_edit))
edit.add_argument('host') add_hostname_arg(session_edit_parser)
edit.add_argument('name') add_session_name_arg(session_edit_parser)
# Delete # Delete
delete = session.add_parser('delete', help='delete a session') session_delete_parser = session.add_parser('delete', help='delete a session')
delete.set_defaults(command=command_session_delete) session_delete_parser.set_defaults(
delete.add_argument('host') command=make_command(command_session_delete))
delete.add_argument('name', nargs=OPTIONAL, add_hostname_arg(session_delete_parser)
add_session_name_arg(session_delete_parser, nargs=argparse.OPTIONAL,
help='The name of the session to be deleted.' help='The name of the session to be deleted.'
' If not specified, all host sessions are deleted.') ' If not specified, all of the host\'s')
#################################################################
# Main
#################################################################
def main(): def main():

View File

@ -142,7 +142,6 @@ class HTTPRequest(HTTPMessage):
@property @property
def headers(self): def headers(self):
"""Return Request-Line"""
url = urlparse(self._orig.url) url = urlparse(self._orig.url)
# Querystring # Querystring
@ -172,7 +171,6 @@ class HTTPRequest(HTTPMessage):
headers = ['%s: %s' % (name, value) headers = ['%s: %s' % (name, value)
for name, value in headers.items()] for name, value in headers.items()]
#noinspection PyTypeChecker
headers.insert(0, request_line) headers.insert(0, request_line)
return '\r\n'.join(headers).strip() return '\r\n'.join(headers).strip()

View File

@ -154,6 +154,7 @@ class BaseStream(object):
:param with_body: if `True`, body will be included :param with_body: if `True`, body will be included
""" """
assert with_headers or with_body
self.msg = msg self.msg = msg
self.with_headers = with_headers self.with_headers = with_headers
self.with_body = with_body self.with_body = with_body

View File

@ -65,19 +65,22 @@ def get_response(name, request_kwargs, config_dir, read_only=False):
class Host(object): class Host(object):
"""A host is a per-host directory on the disk containing sessions files.""" """A host is a per-host directory on the disk containing sessions files."""
VALID_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.:-]+$')
def __init__(self, name, root_dir=DEFAULT_SESSIONS_DIR): def __init__(self, name, root_dir=DEFAULT_SESSIONS_DIR):
assert self.VALID_NAME_PATTERN.match(name)
self.name = name self.name = name
self.root_dir = root_dir self.root_dir = root_dir
def __iter__(self): def __iter__(self):
"""Return a iterator yielding `Session` instances.""" """Return an iterator yielding `Session` instances."""
for fn in sorted(glob.glob1(self.path, '*.json')): for fn in sorted(glob.glob1(self.path, '*.json')):
session_name = os.path.splitext(fn)[0] session_name = os.path.splitext(fn)[0]
yield Session(host=self, name=session_name) yield Session(host=self, name=session_name)
@property @property
def verbose_name(self): def verbose_name(self):
return u'%s %s' % (self.name, self.path) return '%s %s' % (self.name, self.path)
def delete(self): def delete(self):
shutil.rmtree(self.path) shutil.rmtree(self.path)
@ -111,7 +114,10 @@ class Session(BaseConfigDict):
help = 'https://github.com/jkbr/httpie#sessions' help = 'https://github.com/jkbr/httpie#sessions'
about = 'HTTPie session file' about = 'HTTPie session file'
VALID_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$')
def __init__(self, host, name, *args, **kwargs): def __init__(self, host, name, *args, **kwargs):
assert self.VALID_NAME_PATTERN.match(name)
super(Session, self).__init__(*args, **kwargs) super(Session, self).__init__(*args, **kwargs)
self.host = host self.host = host
self.name = name self.name = name
@ -119,8 +125,8 @@ class Session(BaseConfigDict):
self['cookies'] = {} self['cookies'] = {}
self['auth'] = { self['auth'] = {
'type': None, 'type': None,
'username': '', 'username': None,
'password': '' 'password': None
} }
@property @property
@ -129,7 +135,7 @@ class Session(BaseConfigDict):
@property @property
def verbose_name(self): def verbose_name(self):
return u'%s %s %s' % (self.host.name, self.name, self.path) return '%s %s %s' % (self.host.name, self.name, self.path)
@property @property
def cookies(self): def cookies(self):
@ -161,7 +167,7 @@ class Session(BaseConfigDict):
def auth(self): def auth(self):
auth = self.get('auth', None) auth = self.get('auth', None)
if not auth or not auth['type']: if not auth or not auth['type']:
return None return
Auth = {'basic': HTTPBasicAuth, Auth = {'basic': HTTPBasicAuth,
'digest': HTTPDigestAuth}[auth['type']] 'digest': HTTPDigestAuth}[auth['type']]
return Auth(auth['username'], auth['password']) return Auth(auth['username'], auth['password'])
@ -176,21 +182,19 @@ class Session(BaseConfigDict):
} }
################################################################## ##################################################################
# Session management commands # Session management commands
# TODO: write tests # TODO: write tests
################################################################## ##################################################################
def command_session_list(args): def command_session_list(hostname=None):
"""Print a list of all sessions or only """Print a list of all sessions or only
the ones from `args.host`, if provided. the ones from `args.host`, if provided.
""" """
if args.host: if hostname:
for session in Host(args.host): for session in Host(hostname):
print(session.verbose_name) print(session.verbose_name)
else: else:
for host in Host.all(): for host in Host.all():
@ -198,9 +202,9 @@ def command_session_list(args):
print(session.verbose_name) print(session.verbose_name)
def command_session_show(args): def command_session_show(hostname, session_name):
"""Print session JSON data for `args.host` and `args.name`.""" """Print JSON data for a session."""
session = Session(Host(args.host), args.name) session = Session(Host(hostname), session_name)
path = session.path path = session.path
if not os.path.exists(path): if not os.path.exists(path):
sys.stderr.write('Session does not exist: %s\n' sys.stderr.write('Session does not exist: %s\n'
@ -214,20 +218,19 @@ def command_session_show(args):
print('') print('')
def command_session_delete(args): def command_session_delete(hostname, session_name=None):
"""Delete a session by host and name, or delete all the """Delete a session by host and name, or delete all the
host's session if name not provided. host's session if name not provided.
""" """
host = Host(args.host) host = Host(hostname)
if not args.name: if not session_name:
host.delete() host.delete()
else: session = Session(host, session_name)
session = Session(host, args.name)
session.delete() session.delete()
def command_session_edit(args): def command_session_edit(hostname, session_name):
"""Open a session file in EDITOR.""" """Open a session file in EDITOR."""
editor = os.environ.get('EDITOR', None) editor = os.environ.get('EDITOR', None)
if not editor: if not editor:
@ -235,7 +238,7 @@ def command_session_edit(args):
'You need to configure the environment variable EDITOR.\n') 'You need to configure the environment variable EDITOR.\n')
sys.exit(1) sys.exit(1)
session = Session(Host(args.host), args.name) session = Session(Host(hostname), session_name)
if session.is_new: if session.is_new:
session.save() session.save()