python-benedict/benedict/dicts/io/io_util.py

105 lines
2.5 KiB
Python
Raw Normal View History

2019-09-10 14:58:26 +00:00
# -*- coding: utf-8 -*-
from benedict.serializers import (
get_format_by_path, get_serializer_by_format, get_serializers_extensions, )
from six import PY2
2019-09-10 14:58:26 +00:00
import errno
import os
import requests
def autodetect_format(s):
if is_url(s) or is_filepath(s):
return get_format_by_path(s)
return None
def decode(s, format, **kwargs):
serializer = get_serializer_by_format(format)
if not serializer:
raise ValueError('Invalid format: {}.'.format(format))
decode_opts = kwargs.copy()
data = serializer.decode(s.strip(), **decode_opts)
return data
def encode(d, format, **kwargs):
serializer = get_serializer_by_format(format)
if not serializer:
raise ValueError('Invalid format: {}.'.format(format))
s = serializer.encode(d, **kwargs)
return s
2020-02-04 10:28:47 +00:00
def is_data(s):
return (len(s.splitlines()) > 1)
def is_filepath(s):
if any([s.endswith(ext) for ext in get_serializers_extensions()]):
return True
return os.path.isfile(s)
2020-02-04 10:28:47 +00:00
def is_url(s):
return any([s.startswith(protocol)
for protocol in ['http://', 'https://']])
2019-10-03 16:42:44 +00:00
def read_content(s):
# s -> filepath or url or data
2020-02-04 10:28:47 +00:00
if is_data(s):
# data
return s
2020-02-04 10:28:47 +00:00
elif is_url(s):
# url
return read_url(s)
2020-02-04 10:28:47 +00:00
elif is_filepath(s):
# filepath
2020-02-04 10:28:47 +00:00
return read_file(s)
# one-line data?!
2020-01-30 14:50:01 +00:00
return s
2019-10-03 16:42:44 +00:00
2019-09-10 14:58:26 +00:00
def read_file(filepath):
2020-02-04 10:28:47 +00:00
if os.path.isfile(filepath):
content = ''
options = {} if PY2 else { 'encoding':'utf-8' }
with open(filepath, 'r', **options) as file:
content = file.read()
2020-02-04 10:28:47 +00:00
return content
return None
2019-09-10 14:58:26 +00:00
def read_url(url, *args, **kwargs):
response = requests.get(url, *args, **kwargs)
if response.status_code == requests.codes.ok:
content = response.text
return content
2020-01-30 14:50:01 +00:00
raise ValueError(
'Invalid url response status code: {}.'.format(
response.status_code))
2019-09-10 14:58:26 +00:00
2020-01-25 11:08:24 +00:00
def write_file_dir(filepath):
2019-10-14 14:32:40 +00:00
filedir = os.path.dirname(filepath)
2020-01-30 14:50:01 +00:00
if os.path.exists(filedir):
return
try:
os.makedirs(filedir)
except OSError as e:
# Guard against race condition
if e.errno != errno.EEXIST:
raise e
2020-01-25 11:08:24 +00:00
def write_file(filepath, content):
# https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output
write_file_dir(filepath)
options = {} if PY2 else { 'encoding':'utf-8' }
with open(filepath, 'w+', **options) as file:
file.write(content)
2019-09-10 14:58:26 +00:00
return True