2012-08-18 23:03:31 +02:00
|
|
|
"""Persistent, JSON-serialized sessions.
|
|
|
|
|
|
|
|
"""
|
2012-12-01 18:16:00 +01:00
|
|
|
import re
|
2012-08-17 23:23:02 +02:00
|
|
|
import os
|
2012-08-18 23:03:31 +02:00
|
|
|
import glob
|
2012-08-17 23:23:02 +02:00
|
|
|
import errno
|
2012-08-21 15:45:22 +02:00
|
|
|
import shutil
|
2012-08-18 23:03:31 +02:00
|
|
|
|
2012-09-07 12:38:52 +02:00
|
|
|
import requests
|
2012-08-18 23:03:31 +02:00
|
|
|
from requests.cookies import RequestsCookieJar, create_cookie
|
|
|
|
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
|
2012-08-17 23:23:02 +02:00
|
|
|
|
2013-01-03 14:12:27 +01:00
|
|
|
from .compat import urlsplit
|
2012-09-17 02:15:00 +02:00
|
|
|
from .config import BaseConfigDict, DEFAULT_CONFIG_DIR
|
2012-08-17 23:23:02 +02:00
|
|
|
|
|
|
|
|
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-08-17 23:23:02 +02:00
|
|
|
|
|
|
|
|
2013-05-13 11:54:49 +02:00
|
|
|
# Request headers starting with these prefixes won't be stored in sessions.
|
|
|
|
# They are specific to each request.
|
|
|
|
# http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Requests
|
|
|
|
SESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-']
|
|
|
|
|
|
|
|
|
|
|
|
def get_response(name, requests_kwargs, config_dir, read_only=False):
|
2012-09-07 12:38:52 +02:00
|
|
|
"""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,
|
2013-05-13 11:54:49 +02:00
|
|
|
name=requests_kwargs['headers'].get('Host', None)
|
|
|
|
or urlsplit(requests_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()
|
2012-08-18 23:03:31 +02:00
|
|
|
|
2013-05-13 11:54:49 +02:00
|
|
|
# Merge request and session headers to get final headers for this request.
|
|
|
|
request_headers = requests_kwargs.get('headers', {})
|
|
|
|
merged_headers = session.headers.copy()
|
|
|
|
merged_headers.update(request_headers)
|
|
|
|
requests_kwargs['headers'] = merged_headers
|
2012-08-18 23:03:31 +02:00
|
|
|
# Update session headers with the request headers.
|
2013-05-13 11:54:49 +02:00
|
|
|
session.update_headers(request_headers)
|
2012-08-18 23:03:31 +02:00
|
|
|
|
2013-05-13 11:54:49 +02:00
|
|
|
auth = requests_kwargs.get('auth', None)
|
2012-08-18 23:03:31 +02:00
|
|
|
if auth:
|
|
|
|
session.auth = auth
|
|
|
|
elif session.auth:
|
2013-05-13 11:54:49 +02:00
|
|
|
requests_kwargs['auth'] = session.auth
|
2012-08-18 23:03:31 +02:00
|
|
|
|
2013-01-03 13:49:41 +01:00
|
|
|
requests_session = requests.Session()
|
2013-01-04 02:59:05 +01:00
|
|
|
requests_session.cookies = session.cookies
|
2013-01-03 13:49:41 +01:00
|
|
|
|
2012-08-17 23:23:02 +02:00
|
|
|
try:
|
2013-05-13 11:54:49 +02:00
|
|
|
response = requests_session.request(**requests_kwargs)
|
2012-08-17 23:23:02 +02:00
|
|
|
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
|
2012-09-07 12:38:52 +02:00
|
|
|
session.save()
|
2012-08-17 23:23:02 +02:00
|
|
|
return response
|
|
|
|
|
|
|
|
|
2012-08-19 04:58:14 +02:00
|
|
|
class Host(object):
|
2012-09-07 12:38:52 +02:00
|
|
|
"""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)
|
|
|
|
|
2013-01-22 20:02:39 +01:00
|
|
|
@staticmethod
|
|
|
|
def _quote_name(name):
|
|
|
|
"""host:port => host_port"""
|
|
|
|
return name.replace(':', '_')
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _unquote_name(name):
|
|
|
|
"""host_port => host:port"""
|
|
|
|
return re.sub(r'_(\d+)$', r':\1', name)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def all(cls, root_dir=DEFAULT_SESSIONS_DIR):
|
|
|
|
"""Return a generator yielding a host at a time."""
|
|
|
|
for name in sorted(glob.glob1(root_dir, '*')):
|
|
|
|
if os.path.isdir(os.path.join(root_dir, name)):
|
|
|
|
yield Host(cls._unquote_name(name), root_dir=root_dir)
|
|
|
|
|
2012-12-01 18:16:00 +01:00
|
|
|
@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):
|
2013-01-22 20:02:39 +01:00
|
|
|
path = os.path.join(self.root_dir, self._quote_name(self.name))
|
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
|
|
|
|
|
|
|
|
|
2012-09-17 00:37:36 +02:00
|
|
|
class Session(BaseConfigDict):
|
2012-09-07 12:38:52 +02:00
|
|
|
|
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)
|
2012-08-18 23:03:31 +02:00
|
|
|
super(Session, self).__init__(*args, **kwargs)
|
2012-08-19 04:58:14 +02:00
|
|
|
self.host = host
|
2012-08-18 23:03:31 +02:00
|
|
|
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
|
|
|
}
|
2012-08-17 23:23:02 +02:00
|
|
|
|
2012-09-07 12:38:52 +02:00
|
|
|
@property
|
2012-09-17 00:37:36 +02:00
|
|
|
def directory(self):
|
|
|
|
return self.host.path
|
2012-09-07 12:38:52 +02:00
|
|
|
|
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
|
|
|
|
2013-05-13 11:54:49 +02:00
|
|
|
def update_headers(self, request_headers):
|
|
|
|
"""
|
|
|
|
Update the session headers with the request ones while ignoring
|
|
|
|
certain name prefixes.
|
|
|
|
|
|
|
|
:type request_headers: dict
|
|
|
|
|
|
|
|
"""
|
|
|
|
for name, value in request_headers.items():
|
|
|
|
|
|
|
|
if name == 'User-Agent' and value.startswith('HTTPie/'):
|
|
|
|
continue
|
|
|
|
|
|
|
|
for prefix in SESSION_IGNORED_HEADER_PREFIXES:
|
|
|
|
if name.lower().startswith(prefix.lower()):
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
self['headers'][name] = value
|
|
|
|
|
|
|
|
@property
|
|
|
|
def headers(self):
|
|
|
|
return self['headers']
|
|
|
|
|
2012-08-18 23:03:31 +02: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))
|
2012-08-18 23:03:31 +02:00
|
|
|
jar.clear_expired_cookies()
|
|
|
|
return jar
|
2012-08-17 23:23:02 +02:00
|
|
|
|
2012-08-18 23:03:31 +02:00
|
|
|
@cookies.setter
|
|
|
|
def cookies(self, jar):
|
2013-05-13 11:54:49 +02:00
|
|
|
"""
|
|
|
|
:type jar: CookieJar
|
|
|
|
"""
|
2012-12-19 12:30:20 +01:00
|
|
|
# http://docs.python.org/2/library/cookielib.html#cookie-objects
|
2013-01-22 20:03:28 +01:00
|
|
|
stored_attrs = ['value', 'path', 'secure', 'expires']
|
2012-08-18 23:03:31 +02:00
|
|
|
self['cookies'] = {}
|
2013-03-20 10:45:56 +01:00
|
|
|
for cookie in jar:
|
|
|
|
self['cookies'][cookie.name] = dict(
|
2013-03-20 16:07:23 +01:00
|
|
|
(attname, getattr(cookie, attname))
|
|
|
|
for attname in stored_attrs
|
|
|
|
)
|
2012-08-17 23:23:02 +02:00
|
|
|
|
2012-08-18 23:03:31 +02:00
|
|
|
@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
|
2012-08-18 23:03:31 +02:00
|
|
|
Auth = {'basic': HTTPBasicAuth,
|
|
|
|
'digest': HTTPDigestAuth}[auth['type']]
|
|
|
|
return Auth(auth['username'], auth['password'])
|
2012-08-17 23:23:02 +02:00
|
|
|
|
2012-08-18 23:03:31 +02:00
|
|
|
@auth.setter
|
|
|
|
def auth(self, cred):
|
|
|
|
self['auth'] = {
|
|
|
|
'type': {HTTPBasicAuth: 'basic',
|
|
|
|
HTTPDigestAuth: 'digest'}[type(cred)],
|
|
|
|
'username': cred.username,
|
|
|
|
'password': cred.password,
|
2012-09-07 12:38:52 +02:00
|
|
|
}
|