Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
with open(f'{directory}/{file_name}', 'r') as f:
template_file = f.read()
return template_file.format(**kwargs)
def create_id() -> str:
"""
Create a unique ID, UUIDv4 style
Returns:
str:
"""
return str(uuid.uuid4())
class EnumEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, enum.Enum):
return o.value
return super(EnumEncoder, self).default(o)
def create_random_string(size=12, chars=string.ascii_letters + string.digits):
"""
Generate a cryptographically strong random string
http://stackoverflow.com/a/2257449/771901
Args:
size (int): length of string to generate
chars (str): set of digits that will be used to generate the string
Returns:
from datetime import date, datetime
import simplejson
class date_encoder(simplejson.JSONEncoder):
"""
Encode a datetime.date object in ISO 8601 format.
http://simplejson.readthedocs.org/en/latest/index.html#simplejson.JSONEncoder
"""
def default(self, obj):
if isinstance(obj, date):
return obj.isoformat()
else:
return super(self, obj)
def date_decoder(d):
"""
Decode a date in ISO 8601 format to a datetime.date object.
urllib2.Request.__init__(self, url, data, headers,
origin_req_host, unverifiable)
self.method = method
def get_method(self):
if self.method:
return self.method
return urllib2.Request.get_method(self)
class GanetiRapiClient(object): # pylint: disable-msg=R0904
"""Ganeti RAPI client.
"""
USER_AGENT = "Ganeti RAPI Client"
_json_encoder = simplejson.JSONEncoder(sort_keys=True)
def __init__(self, host, port=GANETI_RAPI_PORT,
username=None, password=None, logger=logging,
curl_config_fn=None, curl_factory=None):
"""Initializes this class.
@type host: string
@param host: the ganeti cluster master to interact with
@type port: int
@param port: the port on which the RAPI is running (default is 5080)
@type username: string
@param username: the username to connect with
@type password: string
@param password: the password to connect with
@type curl_config_fn: callable
@param curl_config_fn: Function to configure C{pycurl.Curl} object
except:
return json.JSONEncoder().encode({"success": "false"})
elif method == "remove_dl":
try:
downloads = self.session.get_downloads()
for dl in downloads:
if dl.get_def().get_infohash() == infohash:
wx.CallAfter(self.bgApp.gui_webui_remove_download, dl)
return json.JSONEncoder().encode({"success": "true"})
except:
return json.JSONEncoder().encode({"success": "false"})
def default(self, obj):
if isinstance(obj, datetime):
# Convert date/datetime to ms-since-epoch ("new Date()").
ms = time.mktime(value.utctimetuple()) * 1000
ms += getattr(value, 'microseconds', 0) / 1000
return int(ms)
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
elif isinstance(obj, ObjectId):
return unicode(obj)
return json.JSONEncoder.default(self, obj)
def deserialize(shows_file_path):
shows_file = open(shows_file_path, 'r')
contents = shows_file.read()
shows_file.close()
# The following test is to guarantee retro-compatibility with the
# old jsonpickle generated json
if contents.startswith('[{"py/object": "SeriesFinale.series.Show"'):
return deserialize_from_old_format(contents)
return json.loads(contents, object_hook = show_encoder)
def deserialize_from_old_format(contents):
shows_list = jsonpickle.decode(contents)
shows_json = json.dumps(shows_list, cls = ShowDecoder)
return json.loads(shows_json, object_hook = show_encoder)
class ShowDecoder(json.JSONEncoder):
def default(self, show):
show_json = dict(show.__dict__)
show_json['json_type'] = 'show'
del show_json['downloading_season_image']
del show_json['downloading_show_image']
episode_list = show_json['episode_list']
remove_private_vars(show_json)
show_json['episode_list'] = [self._decode_episode(episode) \
for episode in episode_list]
if isinstance(show.actors, list):
show_json['actors'] = '|'.join(show.actors)
return show_json
def _decode_episode(self, episode):
episode_json = dict(episode.__dict__)
def default(self, obj):
try:
return default_json_serializer(obj)
except TypeError:
pass
return json.JSONEncoder.default(self, obj)
from bson.errors import InvalidId
import datetime
import mmh3
try:
import json
except ImportError:
import simplejson as json
try:
from bson.objectid import ObjectId
except:
pass
class APIEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.ctime()
elif isinstance(obj, datetime.time):
return obj.isoformat()
elif isinstance(obj, ObjectId):
return str(obj)
return json.JSONEncoder.default(self, obj)
def jsonify(data):
return Response(json.dumps(data, cls=APIEncoder),
mimetype='application/json')