mirror of
https://github.com/httpie/cli.git
synced 2025-02-03 13:01:58 +02:00
Added configuration file.
The "default_content_type" option can be set to "form". Closes #91.
This commit is contained in:
parent
478d654945
commit
4029dbf309
@ -24,7 +24,7 @@ def get_response(args):
|
||||
sys.stderr.write(
|
||||
'\n>>> requests.request(%s)\n\n' % pformat(requests_kwargs))
|
||||
|
||||
if not args.session and not args.session_read:
|
||||
if not args.session and not args.session_read_only:
|
||||
return requests.request(**requests_kwargs)
|
||||
else:
|
||||
return sessions.get_response(
|
||||
|
@ -1,8 +1,78 @@
|
||||
import os
|
||||
import json
|
||||
import errno
|
||||
|
||||
from . import __version__
|
||||
from requests.compat import is_windows
|
||||
|
||||
__author__ = 'jakub'
|
||||
|
||||
DEFAULT_CONFIG_DIR = (os.path.expanduser('~/.httpie')
|
||||
if not is_windows else
|
||||
os.path.expandvars(r'%APPDATA%\\httpie'))
|
||||
|
||||
|
||||
CONFIG_DIR = (os.path.expanduser('~/.httpie') if not is_windows else
|
||||
os.path.expandvars(r'%APPDATA%\\httpie'))
|
||||
class BaseConfigDict(dict):
|
||||
|
||||
name = None
|
||||
help = None
|
||||
|
||||
def __init__(self, directory=DEFAULT_CONFIG_DIR, seq=None, **kwargs):
|
||||
super(BaseConfigDict, self).__init__(seq or [], **kwargs)
|
||||
self.directory = directory
|
||||
|
||||
def __getattr__(self, item):
|
||||
return self[item]
|
||||
|
||||
@property
|
||||
def path(self):
|
||||
try:
|
||||
os.makedirs(self.directory, mode=0o700)
|
||||
except OSError as e:
|
||||
if e.errno != errno.EEXIST:
|
||||
raise
|
||||
return os.path.join(self.directory, self.name + '.json')
|
||||
|
||||
@property
|
||||
def is_new(self):
|
||||
return not os.path.exists(self.path)
|
||||
|
||||
def load(self):
|
||||
try:
|
||||
with open(self.path, 'rt') as f:
|
||||
try:
|
||||
data = json.load(f)
|
||||
except ValueError as e:
|
||||
raise ValueError(
|
||||
'Invalid %s JSON: %s [%s]' %
|
||||
(type(self).__name__, e.message, self.path)
|
||||
)
|
||||
self.update(data)
|
||||
except IOError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
|
||||
def save(self):
|
||||
self['__version__'] = __version__
|
||||
with open(self.path, 'w') as f:
|
||||
json.dump(self, f, indent=4, sort_keys=True, ensure_ascii=True)
|
||||
f.write('\n')
|
||||
|
||||
def delete(self):
|
||||
try:
|
||||
os.unlink(self.path)
|
||||
except OSError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
|
||||
|
||||
class Config(BaseConfigDict):
|
||||
|
||||
name = 'config'
|
||||
|
||||
DEFAULTS = {
|
||||
'default_content_type': 'json',
|
||||
}
|
||||
|
||||
def __init__(self, seq=None, **kwargs):
|
||||
super(Config, self).__init__(seq or [], **kwargs)
|
||||
self.update(self.DEFAULTS)
|
||||
|
@ -23,7 +23,7 @@ from .cli import parser
|
||||
from .client import get_response
|
||||
from .models import Environment
|
||||
from .output import output_stream, write, write_with_colors_win_p3k
|
||||
from .config import CONFIG_DIR
|
||||
from .config import DEFAULT_CONFIG_DIR, Config
|
||||
from . import EXIT
|
||||
|
||||
|
||||
@ -42,10 +42,10 @@ def get_exist_status(code, follow=False):
|
||||
return EXIT.OK
|
||||
|
||||
|
||||
def print_debug_info():
|
||||
def print_debug_info(env):
|
||||
sys.stderr.writelines([
|
||||
'HTTPie %s\n' % httpie_version,
|
||||
'HTTPie data: %s\n' % CONFIG_DIR,
|
||||
'HTTPie data: %s\n' % env.config.directory,
|
||||
'Requests %s\n' % requests_version,
|
||||
'Pygments %s\n' % pygments_version,
|
||||
'Python %s %s\n' % (sys.version, sys.platform)
|
||||
@ -68,7 +68,7 @@ def main(args=sys.argv[1:], env=Environment()):
|
||||
status = EXIT.OK
|
||||
|
||||
if debug:
|
||||
print_debug_info()
|
||||
print_debug_info(env)
|
||||
if args == ['--debug']:
|
||||
sys.exit(EXIT.OK)
|
||||
|
||||
|
@ -102,6 +102,9 @@ class Parser(ArgumentParser):
|
||||
|
||||
args = super(Parser, self).parse_args(args, namespace)
|
||||
|
||||
if not args.json and env.config.default_content_type == 'form':
|
||||
args.form = True
|
||||
|
||||
if args.debug:
|
||||
args.traceback = True
|
||||
|
||||
|
@ -2,6 +2,8 @@ import os
|
||||
import sys
|
||||
from requests.compat import urlparse, is_windows, bytes, str
|
||||
|
||||
from .config import DEFAULT_CONFIG_DIR, Config
|
||||
|
||||
|
||||
class Environment(object):
|
||||
"""Holds information about the execution context.
|
||||
@ -22,6 +24,8 @@ class Environment(object):
|
||||
stdin = sys.stdin
|
||||
stdout_isatty = sys.stdout.isatty()
|
||||
|
||||
config_dir = DEFAULT_CONFIG_DIR
|
||||
|
||||
if stdout_isatty and is_windows:
|
||||
from colorama.initialise import wrap_stream
|
||||
stdout = wrap_stream(sys.stdout, convert=None,
|
||||
@ -38,6 +42,17 @@ class Environment(object):
|
||||
for attr in kwargs.keys())
|
||||
self.__dict__.update(**kwargs)
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
if not hasattr(self, '_config'):
|
||||
self._config = Config()
|
||||
self._config.directory = self.config_dir
|
||||
if self._config.is_new:
|
||||
self._config.save()
|
||||
else:
|
||||
self._config.load()
|
||||
return self._config
|
||||
|
||||
|
||||
class HTTPMessage(object):
|
||||
"""Abstract class for HTTP messages."""
|
||||
|
@ -3,7 +3,6 @@
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import glob
|
||||
import errno
|
||||
import codecs
|
||||
@ -16,12 +15,11 @@ from requests.cookies import RequestsCookieJar, create_cookie
|
||||
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
|
||||
from argparse import OPTIONAL
|
||||
|
||||
from.import __version__
|
||||
from.config import CONFIG_DIR
|
||||
from.output import PygmentsProcessor
|
||||
from .config import DEFAULT_CONFIG_DIR, BaseConfigDict
|
||||
from .output import PygmentsProcessor
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(CONFIG_DIR, 'sessions')
|
||||
SESSIONS_DIR = os.path.join(DEFAULT_CONFIG_DIR, 'sessions')
|
||||
|
||||
|
||||
def get_response(name, request_kwargs, read_only=False):
|
||||
@ -94,7 +92,7 @@ class Host(object):
|
||||
yield Host(name)
|
||||
|
||||
|
||||
class Session(dict):
|
||||
class Session(BaseConfigDict):
|
||||
""""""
|
||||
|
||||
def __init__(self, host, name, *args, **kwargs):
|
||||
@ -104,39 +102,9 @@ class Session(dict):
|
||||
self['headers'] = {}
|
||||
self['cookies'] = {}
|
||||
|
||||
def load(self):
|
||||
try:
|
||||
with open(self.path, 'rt') as f:
|
||||
try:
|
||||
data = json.load(f)
|
||||
except ValueError as e:
|
||||
raise ValueError('Invalid session: %s [%s]' %
|
||||
(e.message, self.path))
|
||||
self.update(data)
|
||||
except IOError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
|
||||
def save(self):
|
||||
self['__version__'] = __version__
|
||||
with open(self.path, 'w') as f:
|
||||
json.dump(self, f, indent=4, sort_keys=True, ensure_ascii=True)
|
||||
f.write('\n')
|
||||
|
||||
def delete(self):
|
||||
try:
|
||||
os.unlink(self.path)
|
||||
except OSError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
|
||||
@property
|
||||
def path(self):
|
||||
return os.path.join(self.host.path, self.name + '.json')
|
||||
|
||||
@property
|
||||
def is_new(self):
|
||||
return not os.path.exists(self.path)
|
||||
def directory(self):
|
||||
return self.host.path
|
||||
|
||||
@property
|
||||
def cookies(self):
|
||||
|
Loading…
x
Reference in New Issue
Block a user