1
0
mirror of https://github.com/httpie/cli.git synced 2024-12-10 10:00:11 +02:00
httpie-cli/httpie/sessions.py

183 lines
5.3 KiB
Python
Raw Normal View History

"""Persistent, JSON-serialized sessions.
"""
2012-12-01 20:16:00 +03:00
import re
import os
from pathlib import Path
from typing import Optional, Union
2019-08-29 08:53:56 +02:00
from urllib.parse import urlsplit
from requests.auth import AuthBase
from requests.cookies import RequestsCookieJar, create_cookie
import requests
from httpie.config import BaseConfigDict, DEFAULT_CONFIG_DIR
2013-09-22 00:46:15 +03:00
from httpie.plugins import plugin_manager
2012-09-17 03:15:00 +03:00
SESSIONS_DIR_NAME = 'sessions'
DEFAULT_SESSIONS_DIR = DEFAULT_CONFIG_DIR / SESSIONS_DIR_NAME
VALID_SESSION_NAME_PATTERN = re.compile('^[a-zA-Z0-9_.-]+$')
# Request headers starting with these prefixes won't be stored in sessions.
# They are specific to each request.
2019-08-30 10:07:01 +02:00
# https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Requests
SESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-']
def get_response(
requests_session: requests.Session,
session_name: str,
config_dir: Path,
args,
read_only=False,
) -> requests.Response:
2016-02-29 06:56:40 +02:00
"""Like `client.get_responses`, but applies permanent
aspects of the session to the request.
"""
from .client import get_requests_kwargs, dump_request
if os.path.sep in session_name:
path = os.path.expanduser(session_name)
else:
hostname = (args.headers.get('Host', None)
or urlsplit(args.url).netloc.split('@')[-1])
if not hostname:
# HACK/FIXME: httpie-unixsocket's URLs have no hostname.
hostname = 'localhost'
# host:port => host_port
hostname = hostname.replace(':', '_')
path = (
2019-08-30 21:26:51 +02:00
config_dir / SESSIONS_DIR_NAME / hostname
/ (session_name + '.json')
)
session = Session(path)
2012-08-19 05:58:14 +03:00
session.load()
kwargs = get_requests_kwargs(args, base_headers=session.headers)
if args.debug:
dump_request(kwargs)
session.update_headers(kwargs['headers'])
if args.auth_plugin:
2013-09-22 00:46:15 +03:00
session.auth = {
'type': args.auth_plugin.auth_type,
'raw_auth': args.auth_plugin.raw_auth,
2013-09-22 00:46:15 +03:00
}
elif session.auth:
kwargs['auth'] = session.auth
requests_session.cookies = session.cookies
2013-01-03 15:49:41 +03:00
try:
response = requests_session.request(**kwargs)
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
session.save()
return response
class Session(BaseConfigDict):
helpurl = 'https://httpie.org/doc#sessions'
2012-12-01 20:16:00 +03:00
about = 'HTTPie session file'
def __init__(self, path: Union[str, Path]):
super().__init__()
self._path = 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
}
def _get_path(self) -> Path:
return self._path
2012-12-01 20:16:00 +03:00
def update_headers(self, request_headers: dict):
"""
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 value is None:
continue # Ignore explicitly unset headers
2014-04-26 18:16:11 +03:00
value = value.decode('utf8')
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) -> dict:
return self['headers']
@property
def cookies(self) -> RequestsCookieJar:
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))
jar.clear_expired_cookies()
return jar
@cookies.setter
def cookies(self, jar: RequestsCookieJar):
2019-08-30 10:07:01 +02:00
# https://docs.python.org/2/library/cookielib.html#cookie-objects
2013-01-22 22:03:28 +03:00
stored_attrs = ['value', 'path', 'secure', 'expires']
self['cookies'] = {}
2013-03-20 12:45:56 +03:00
for cookie in jar:
2017-12-28 19:15:17 +02:00
self['cookies'][cookie.name] = {
attname: getattr(cookie, attname)
2013-03-20 18:07:23 +03:00
for attname in stored_attrs
2017-12-28 19:15:17 +02:00
}
@property
def auth(self) -> Optional[AuthBase]:
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
plugin = plugin_manager.get_auth_plugin(auth['type'])()
credentials = {'username': None, 'password': None}
try:
# New style
plugin.raw_auth = auth['raw_auth']
except KeyError:
# Old style
credentials = {
'username': auth['username'],
'password': auth['password'],
}
else:
if plugin.auth_parse:
from httpie.input import parse_auth
parsed = parse_auth(plugin.raw_auth)
credentials = {
'username': parsed.key,
'password': parsed.value,
}
return plugin.get_auth(**credentials)
@auth.setter
def auth(self, auth: dict):
2019-08-30 09:56:50 +02:00
assert {'type', 'raw_auth'} == auth.keys()
2013-09-22 00:46:15 +03:00
self['auth'] = auth