2012-08-19 00:03:31 +03:00
|
|
|
"""Persistent, JSON-serialized sessions.
|
|
|
|
|
|
|
|
"""
|
2012-12-01 20:16:00 +03:00
|
|
|
import re
|
2012-08-18 00:23:02 +03:00
|
|
|
import os
|
2012-08-19 00:03:31 +03:00
|
|
|
|
2012-09-07 13:38:52 +03:00
|
|
|
import requests
|
2012-08-19 00:03:31 +03:00
|
|
|
from requests.cookies import RequestsCookieJar, create_cookie
|
|
|
|
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
|
2012-08-18 00:23:02 +03:00
|
|
|
|
2013-01-03 16:12:27 +03:00
|
|
|
from .compat import urlsplit
|
2012-09-17 03:15:00 +03:00
|
|
|
from .config import BaseConfigDict, DEFAULT_CONFIG_DIR
|
2012-08-18 00:23:02 +03:00
|
|
|
|
|
|
|
|
2012-09-17 03:15:00 +03:00
|
|
|
SESSIONS_DIR_NAME = 'sessions'
|
2012-09-21 06:43:34 +03:00
|
|
|
DEFAULT_SESSIONS_DIR = os.path.join(DEFAULT_CONFIG_DIR, SESSIONS_DIR_NAME)
|
2013-05-13 15:47:44 +03:00
|
|
|
VALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$')
|
2013-05-13 12:54:49 +03: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-']
|
|
|
|
|
|
|
|
|
2013-05-13 15:47:44 +03:00
|
|
|
def get_response(session_name, requests_kwargs, config_dir, read_only=False):
|
2012-09-07 13:38:52 +03:00
|
|
|
"""Like `client.get_response`, but applies permanent
|
|
|
|
aspects of the session to the request.
|
|
|
|
|
|
|
|
"""
|
2013-05-13 15:47:44 +03:00
|
|
|
if os.path.sep in session_name:
|
|
|
|
path = os.path.expanduser(session_name)
|
|
|
|
else:
|
|
|
|
hostname = (
|
|
|
|
requests_kwargs['headers'].get('Host', None)
|
|
|
|
or urlsplit(requests_kwargs['url']).netloc.split('@')[-1]
|
|
|
|
)
|
|
|
|
|
|
|
|
assert re.match('^[a-zA-Z0-9_.:-]+$', hostname)
|
|
|
|
|
|
|
|
# host:port => host_port
|
|
|
|
hostname = hostname.replace(':', '_')
|
|
|
|
path = os.path.join(config_dir,
|
|
|
|
SESSIONS_DIR_NAME,
|
|
|
|
hostname,
|
|
|
|
session_name + '.json')
|
|
|
|
|
|
|
|
session = Session(path)
|
2012-08-19 05:58:14 +03:00
|
|
|
session.load()
|
2012-08-19 00:03:31 +03:00
|
|
|
|
2013-05-13 12:54:49 +03:00
|
|
|
request_headers = requests_kwargs.get('headers', {})
|
2013-05-14 13:14:08 +03:00
|
|
|
requests_kwargs['headers'] = dict(session.headers, **request_headers)
|
2013-05-13 12:54:49 +03:00
|
|
|
session.update_headers(request_headers)
|
2012-08-19 00:03:31 +03:00
|
|
|
|
2013-05-13 12:54:49 +03:00
|
|
|
auth = requests_kwargs.get('auth', None)
|
2012-08-19 00:03:31 +03:00
|
|
|
if auth:
|
|
|
|
session.auth = auth
|
|
|
|
elif session.auth:
|
2013-05-13 12:54:49 +03:00
|
|
|
requests_kwargs['auth'] = session.auth
|
2012-08-19 00:03:31 +03:00
|
|
|
|
2013-01-03 15:49:41 +03:00
|
|
|
requests_session = requests.Session()
|
2013-01-04 04:59:05 +03:00
|
|
|
requests_session.cookies = session.cookies
|
2013-01-03 15:49:41 +03:00
|
|
|
|
2012-08-18 00:23:02 +03:00
|
|
|
try:
|
2013-05-13 12:54:49 +03:00
|
|
|
response = requests_session.request(**requests_kwargs)
|
2012-08-18 00:23:02 +03:00
|
|
|
except Exception:
|
|
|
|
raise
|
|
|
|
else:
|
2012-09-07 13:48:59 +03:00
|
|
|
# Existing sessions with `read_only=True` don't get updated.
|
|
|
|
if session.is_new or not read_only:
|
2013-01-03 15:49:41 +03:00
|
|
|
session.cookies = requests_session.cookies
|
2012-09-07 13:38:52 +03:00
|
|
|
session.save()
|
2012-08-18 00:23:02 +03:00
|
|
|
return response
|
|
|
|
|
|
|
|
|
2012-09-17 01:37:36 +03:00
|
|
|
class Session(BaseConfigDict):
|
2013-05-13 15:47:44 +03:00
|
|
|
helpurl = 'https://github.com/jkbr/httpie#sessions'
|
2012-12-01 20:16:00 +03:00
|
|
|
about = 'HTTPie session file'
|
|
|
|
|
2013-05-13 15:47:44 +03:00
|
|
|
def __init__(self, path, *args, **kwargs):
|
2012-08-19 00:03:31 +03:00
|
|
|
super(Session, self).__init__(*args, **kwargs)
|
2013-05-13 15:47:44 +03:00
|
|
|
self._path = path
|
2012-08-19 05:58:14 +03:00
|
|
|
self['headers'] = {}
|
|
|
|
self['cookies'] = {}
|
2012-12-01 20:16:00 +03:00
|
|
|
self['auth'] = {
|
|
|
|
'type': None,
|
2012-12-11 14:54:34 +03:00
|
|
|
'username': None,
|
|
|
|
'password': None
|
2012-12-01 20:16:00 +03:00
|
|
|
}
|
2012-08-18 00:23:02 +03:00
|
|
|
|
2013-05-13 15:47:44 +03:00
|
|
|
def _get_path(self):
|
|
|
|
return self._path
|
2012-12-01 20:16:00 +03:00
|
|
|
|
2013-05-13 12:54:49 +03: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-19 00:03:31 +03:00
|
|
|
@property
|
|
|
|
def cookies(self):
|
|
|
|
jar = RequestsCookieJar()
|
|
|
|
for name, cookie_dict in self['cookies'].items():
|
2012-08-21 16:45:22 +03:00
|
|
|
jar.set_cookie(create_cookie(
|
|
|
|
name, cookie_dict.pop('value'), **cookie_dict))
|
2012-08-19 00:03:31 +03:00
|
|
|
jar.clear_expired_cookies()
|
|
|
|
return jar
|
2012-08-18 00:23:02 +03:00
|
|
|
|
2012-08-19 00:03:31 +03:00
|
|
|
@cookies.setter
|
|
|
|
def cookies(self, jar):
|
2013-05-13 12:54:49 +03:00
|
|
|
"""
|
|
|
|
:type jar: CookieJar
|
|
|
|
"""
|
2012-12-19 14:30:20 +03:00
|
|
|
# http://docs.python.org/2/library/cookielib.html#cookie-objects
|
2013-01-22 22:03:28 +03:00
|
|
|
stored_attrs = ['value', 'path', 'secure', 'expires']
|
2012-08-19 00:03:31 +03:00
|
|
|
self['cookies'] = {}
|
2013-03-20 12:45:56 +03:00
|
|
|
for cookie in jar:
|
|
|
|
self['cookies'][cookie.name] = dict(
|
2013-03-20 18:07:23 +03:00
|
|
|
(attname, getattr(cookie, attname))
|
|
|
|
for attname in stored_attrs
|
|
|
|
)
|
2012-08-18 00:23:02 +03:00
|
|
|
|
2012-08-19 00:03:31 +03:00
|
|
|
@property
|
|
|
|
def auth(self):
|
|
|
|
auth = self.get('auth', None)
|
2012-12-01 20:16:00 +03:00
|
|
|
if not auth or not auth['type']:
|
2012-12-11 14:54:34 +03:00
|
|
|
return
|
2012-08-19 00:03:31 +03:00
|
|
|
Auth = {'basic': HTTPBasicAuth,
|
|
|
|
'digest': HTTPDigestAuth}[auth['type']]
|
|
|
|
return Auth(auth['username'], auth['password'])
|
2012-08-18 00:23:02 +03:00
|
|
|
|
2012-08-19 00:03:31 +03: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 13:38:52 +03:00
|
|
|
}
|