httpie-cli/httpie/sessions.py

250 lines
7.4 KiB
Python
Raw Normal View History

"""Persistent, JSON-serialized sessions.
"""
2012-12-01 18:16:00 +01:00
import re
import os
import sys
import glob
import errno
import codecs
2012-08-21 15:45:22 +02:00
import shutil
import subprocess
import requests
from requests.cookies import RequestsCookieJar, create_cookie
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
from .compat import urlsplit
2012-09-17 02:15:00 +02:00
from .config import BaseConfigDict, DEFAULT_CONFIG_DIR
from .output import PygmentsProcessor
2012-09-17 02:15:00 +02:00
SESSIONS_DIR_NAME = 'sessions'
2012-09-21 05:43:34 +02:00
DEFAULT_SESSIONS_DIR = os.path.join(DEFAULT_CONFIG_DIR, SESSIONS_DIR_NAME)
2012-09-17 02:15:00 +02:00
def get_response(name, request_kwargs, config_dir, read_only=False):
"""Like `client.get_response`, but applies permanent
aspects of the session to the request.
"""
2012-09-17 02:15:00 +02:00
sessions_dir = os.path.join(config_dir, SESSIONS_DIR_NAME)
host = Host(
root_dir=sessions_dir,
name=request_kwargs['headers'].get('Host', None)
or urlsplit(request_kwargs['url']).netloc.split('@')[-1]
2012-09-17 02:15:00 +02:00
)
2012-08-19 04:58:14 +02:00
session = Session(host, name)
session.load()
# Update session headers with the request headers.
session['headers'].update(request_kwargs.get('headers', {}))
2012-08-19 04:58:14 +02:00
# Use the merged headers for the request
request_kwargs['headers'] = session['headers']
auth = request_kwargs.get('auth', None)
if auth:
session.auth = auth
elif session.auth:
request_kwargs['auth'] = session.auth
2013-01-03 13:49:41 +01:00
requests_session = requests.Session()
requests_session.cookies = session.cookies
2013-01-03 13:49:41 +01:00
try:
response = requests_session.request(**request_kwargs)
except Exception:
raise
else:
2012-09-07 12:48:59 +02:00
# Existing sessions with `read_only=True` don't get updated.
if session.is_new or not read_only:
2013-01-03 13:49:41 +01:00
session.cookies = requests_session.cookies
session.save()
return response
2012-08-19 04:58:14 +02:00
class Host(object):
"""A host is a per-host directory on the disk containing sessions files."""
2012-12-11 12:54:34 +01:00
VALID_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.:-]+$')
2012-12-01 18:16:00 +01:00
def __init__(self, name, root_dir=DEFAULT_SESSIONS_DIR):
2012-12-11 12:54:34 +01:00
assert self.VALID_NAME_PATTERN.match(name)
2012-08-19 04:58:14 +02:00
self.name = name
2012-09-17 02:15:00 +02:00
self.root_dir = root_dir
2012-08-19 04:58:14 +02:00
def __iter__(self):
2012-12-11 12:54:34 +01:00
"""Return an iterator yielding `Session` instances."""
2012-08-19 04:58:14 +02:00
for fn in sorted(glob.glob1(self.path, '*.json')):
2012-12-01 18:16:00 +01:00
session_name = os.path.splitext(fn)[0]
yield Session(host=self, name=session_name)
@property
def verbose_name(self):
2012-12-11 12:54:34 +01:00
return '%s %s' % (self.name, self.path)
2012-08-19 04:58:14 +02:00
def delete(self):
shutil.rmtree(self.path)
@property
def path(self):
# Name will include ':' if a port is specified, which is invalid
# on windows. DNS does not allow '_' in a domain, or for it to end
# in a number (I think?)
2012-09-17 02:15:00 +02:00
path = os.path.join(self.root_dir, self.name.replace(':', '_'))
2012-08-19 04:58:14 +02:00
try:
os.makedirs(path, mode=0o700)
except OSError as e:
if e.errno != errno.EEXIST:
2012-08-21 15:45:22 +02:00
raise
2012-08-19 04:58:14 +02:00
return path
@classmethod
2012-12-01 18:16:00 +01:00
def all(cls, root_dir=DEFAULT_SESSIONS_DIR):
"""Return a generator yielding a host at a time."""
2012-12-01 18:16:00 +01:00
for name in sorted(glob.glob1(root_dir, '*')):
if os.path.isdir(os.path.join(root_dir, name)):
# host_port => host:port
real_name = re.sub(r'_(\d+)$', r':\1', name)
yield Host(real_name, root_dir=root_dir)
2012-08-19 04:58:14 +02:00
class Session(BaseConfigDict):
""""""
2012-12-01 18:16:00 +01:00
help = 'https://github.com/jkbr/httpie#sessions'
about = 'HTTPie session file'
2012-12-11 12:54:34 +01:00
VALID_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$')
2012-08-19 04:58:14 +02:00
def __init__(self, host, name, *args, **kwargs):
2012-12-11 12:54:34 +01:00
assert self.VALID_NAME_PATTERN.match(name)
super(Session, self).__init__(*args, **kwargs)
2012-08-19 04:58:14 +02:00
self.host = host
self.name = name
2012-08-19 04:58:14 +02:00
self['headers'] = {}
self['cookies'] = {}
2012-12-01 18:16:00 +01:00
self['auth'] = {
'type': None,
2012-12-11 12:54:34 +01:00
'username': None,
'password': None
2012-12-01 18:16:00 +01:00
}
@property
def directory(self):
return self.host.path
2012-12-01 18:16:00 +01:00
@property
def verbose_name(self):
2012-12-11 12:54:34 +01:00
return '%s %s %s' % (self.host.name, self.name, self.path)
2012-12-01 18:16:00 +01:00
@property
def cookies(self):
jar = RequestsCookieJar()
for name, cookie_dict in self['cookies'].items():
2012-08-21 15:45:22 +02:00
jar.set_cookie(create_cookie(
name, cookie_dict.pop('value'), **cookie_dict))
jar.clear_expired_cookies()
return jar
@cookies.setter
def cookies(self, jar):
2012-12-19 12:30:20 +01:00
# http://docs.python.org/2/library/cookielib.html#cookie-objects
2012-08-19 04:58:14 +02:00
excluded = [
'_rest', 'name', 'port_specified',
'domain_specified', 'domain_initial_dot',
2012-12-19 12:30:20 +01:00
'path_specified', 'comment', 'comment_url',
]
self['cookies'] = {}
for host in jar._cookies.values():
for path in host.values():
for name, cookie in path.items():
cookie_dict = {}
for k, v in cookie.__dict__.items():
2012-08-19 04:58:14 +02:00
if k not in excluded:
cookie_dict[k] = v
self['cookies'][name] = cookie_dict
@property
def auth(self):
auth = self.get('auth', None)
2012-12-01 18:16:00 +01:00
if not auth or not auth['type']:
2012-12-11 12:54:34 +01:00
return
Auth = {'basic': HTTPBasicAuth,
'digest': HTTPDigestAuth}[auth['type']]
return Auth(auth['username'], auth['password'])
@auth.setter
def auth(self, cred):
self['auth'] = {
'type': {HTTPBasicAuth: 'basic',
HTTPDigestAuth: 'digest'}[type(cred)],
'username': cred.username,
'password': cred.password,
}
2012-12-01 18:16:00 +01:00
##################################################################
# Session management commands
# TODO: write tests
##################################################################
2012-12-11 12:54:34 +01:00
def command_session_list(hostname=None):
2012-12-01 18:16:00 +01:00
"""Print a list of all sessions or only
the ones from `args.host`, if provided.
"""
2012-12-11 12:54:34 +01:00
if hostname:
for session in Host(hostname):
2012-12-01 18:16:00 +01:00
print(session.verbose_name)
2012-08-19 04:58:14 +02:00
else:
for host in Host.all():
2012-12-01 18:16:00 +01:00
for session in host:
print(session.verbose_name)
2012-12-11 12:54:34 +01:00
def command_session_show(hostname, session_name):
"""Print JSON data for a session."""
session = Session(Host(hostname), session_name)
2012-12-01 18:16:00 +01:00
path = session.path
if not os.path.exists(path):
2012-12-01 18:16:00 +01:00
sys.stderr.write('Session does not exist: %s\n'
% session.verbose_name)
sys.exit(1)
with codecs.open(path, encoding='utf8') as f:
2012-12-01 18:16:00 +01:00
print(session.verbose_name + ':\n')
2012-08-19 04:58:14 +02:00
proc = PygmentsProcessor()
print(proc.process_body(f.read(), 'application/json', 'json'))
print('')
2012-12-11 12:54:34 +01:00
def command_session_delete(hostname, session_name=None):
2012-12-01 18:16:00 +01:00
"""Delete a session by host and name, or delete all the
host's session if name not provided.
"""
2012-12-11 12:54:34 +01:00
host = Host(hostname)
if not session_name:
2012-08-19 04:58:14 +02:00
host.delete()
2012-12-11 12:54:34 +01:00
session = Session(host, session_name)
2012-12-01 18:16:00 +01:00
session.delete()
2012-12-11 12:54:34 +01:00
def command_session_edit(hostname, session_name):
2012-12-01 18:16:00 +01:00
"""Open a session file in EDITOR."""
editor = os.environ.get('EDITOR', None)
if not editor:
sys.stderr.write(
'You need to configure the environment variable EDITOR.\n')
sys.exit(1)
2012-12-11 12:54:34 +01:00
session = Session(Host(hostname), session_name)
2012-12-01 18:16:00 +01:00
if session.is_new:
session.save()
2012-12-01 18:16:00 +01:00
command = editor.split()
command.append(session.path)
subprocess.call(command)