Skip to content

Instantly share code, notes, and snippets.

@shollingsworth
Last active June 26, 2018 05:25
Show Gist options
  • Save shollingsworth/da5e39b9823b2d1fe5f356aac8467698 to your computer and use it in GitHub Desktop.
Save shollingsworth/da5e39b9823b2d1fe5f356aac8467698 to your computer and use it in GitHub Desktop.
Create a slack data object given the raw json output ` ./slack-create-pyclass.py -f user.json User`
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import argparse
import json
import select
import sys
LOG = logging.getLogger()
LOG.setLevel(logging.DEBUG)
L0 = " " * 4
L1 = " " * 8
L2 = " " * 12
DICT_PLACEHOLDER = '__DICT__'
class pass_dict(object):
data_parameter = 'data'
data_name = 'raw_data'
class_name = 'ERROR'
attribute_output = 'ERROR'
l0 = L0
l1 = L1
l2 = L2
template_subclass_attribute = """
self.{sub_key}_{k} = {{data_parameter}}.get('{sub_class_name}', {dict_placeholder}).get('{k}')
""".strip()
template_attribute = """
self.{k} = {data_parameter}.get('{k}')
""".strip()
program_desc = "Generate Slack Object from JSON Sample"
parser = argparse.ArgumentParser(
description=program_desc,
add_help=True,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"class_name",
help="Class Name",
)
parser.add_argument(
"-f",
"--json_file",
help="Input File or STDOUT",
default=None,
)
"""
class args(object):
# json_file = None
json_file = "./user.json"
class_name = 'user'
"""
args = parser.parse_args()
if not args.json_file and select.select([sys.stdin], [], [], 0.0)[0]:
fh = sys.stdin
elif args.json_file:
fh = open(args.json_file, 'r')
else:
raise Exception("Error, no file or STDIN detected")
data = json.load(fh)
fh.close()
pass_dict.class_name = args.class_name.title()
attribute_list = []
dicts = []
for k, v in data.items():
_tmp_dict = pass_dict.__dict__.copy()
_tmp_dict['k'] = k
if isinstance(v, dict):
dicts.append(k)
attribute_list.append(template_attribute.format(**_tmp_dict))
for k in dicts:
sub_class_attributes_list = []
for uk in data.get(k).keys():
attr_template = template_subclass_attribute.format(**{
'sub_key': k,
'k': uk,
'dict_placeholder': DICT_PLACEHOLDER,
'sub_class_name': k,
}).format(**pass_dict.__dict__)
attribute_list.append(attr_template)
attribute_list.sort()
pass_dict.attribute_output = "\n{}".format(L1).join(attribute_list)
output = []
output.append("""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""".strip())
class_output = """
class {class_name}(object):
{l0}def __init__(
{l1}self,
{l1}{data_parameter},
{l0}):
{l1}self.{data_name}_json = {data_parameter}
{l1}{attribute_output}
""".strip().format(**pass_dict.__dict__).replace(DICT_PLACEHOLDER, '{}')
output.append(class_output)
output.append("""
# Sample Object
SAMPLE_OBJECT = {}\n\n
""".strip().format(
json.dumps(data, indent=4, separators=(',', ' : '))
).replace(
': false',
': False'
).replace(
': true',
': True'
))
output.append("""
if __name__ == '__main__':
obj = {}(SAMPLE_OBJECT)
attributes = [i for i in dir(obj) if not i.startswith('__')]
for i in attributes:
print(i, getattr(obj, i))
""".strip().format(args.class_name))
print("\n\n\n".join(output))
{
"profile" : {
"display_name" : "spengler",
"status_emoji" : ":books:",
"team" : "T012AB3C4",
"real_name" : "Egon Spengler",
"image_24" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"real_name_normalized" : "Egon Spengler",
"image_512" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"display_name_normalized" : "spengler",
"image_32" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_48" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_72" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"avatar_hash" : "ge3b51ca72de",
"status_text" : "Print is dead",
"email" : "[email protected]",
"image_192" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg"
},
"updated" : 1502138686,
"tz" : "America/Los_Angeles",
"name" : "spengler",
"deleted" : true,
"is_app_user" : false,
"is_bot" : false,
"tz_label" : "Pacific Daylight Time",
"real_name" : "Egon Spengler",
"color" : "9f69e7",
"team_id" : "T012AB3C4",
"is_admin" : true,
"is_ultra_restricted" : false,
"is_restricted" : false,
"is_owner" : false,
"tz_offset" : -25200,
"has_2fa" : false,
"id" : "W012A3CDE",
"is_primary_owner" : false
}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class User(object):
def __init__(
self,
data,
):
self.raw_data_json = data
self.color = data.get('color')
self.deleted = data.get('deleted')
self.has_2fa = data.get('has_2fa')
self.id = data.get('id')
self.is_admin = data.get('is_admin')
self.is_app_user = data.get('is_app_user')
self.is_bot = data.get('is_bot')
self.is_owner = data.get('is_owner')
self.is_primary_owner = data.get('is_primary_owner')
self.is_restricted = data.get('is_restricted')
self.is_ultra_restricted = data.get('is_ultra_restricted')
self.name = data.get('name')
self.profile = data.get('profile')
self.profile_avatar_hash = data.get('profile', {}).get('avatar_hash')
self.profile_display_name = data.get('profile', {}).get('display_name')
self.profile_display_name_normalized = data.get('profile', {}).get('display_name_normalized')
self.profile_email = data.get('profile', {}).get('email')
self.profile_image_192 = data.get('profile', {}).get('image_192')
self.profile_image_24 = data.get('profile', {}).get('image_24')
self.profile_image_32 = data.get('profile', {}).get('image_32')
self.profile_image_48 = data.get('profile', {}).get('image_48')
self.profile_image_512 = data.get('profile', {}).get('image_512')
self.profile_image_72 = data.get('profile', {}).get('image_72')
self.profile_real_name = data.get('profile', {}).get('real_name')
self.profile_real_name_normalized = data.get('profile', {}).get('real_name_normalized')
self.profile_status_emoji = data.get('profile', {}).get('status_emoji')
self.profile_status_text = data.get('profile', {}).get('status_text')
self.profile_team = data.get('profile', {}).get('team')
self.real_name = data.get('real_name')
self.team_id = data.get('team_id')
self.tz = data.get('tz')
self.tz_label = data.get('tz_label')
self.tz_offset = data.get('tz_offset')
self.updated = data.get('updated')
# Sample Object
SAMPLE_OBJECT = {
"profile" : {
"display_name" : "spengler",
"status_emoji" : ":books:",
"team" : "T012AB3C4",
"real_name" : "Egon Spengler",
"image_24" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"real_name_normalized" : "Egon Spengler",
"image_512" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"display_name_normalized" : "spengler",
"image_32" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_48" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_72" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"avatar_hash" : "ge3b51ca72de",
"status_text" : "Print is dead",
"email" : "[email protected]",
"image_192" : "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg"
},
"updated" : 1502138686,
"tz" : "America/Los_Angeles",
"name" : "spengler",
"deleted" : False,
"is_app_user" : False,
"is_bot" : False,
"tz_label" : "Pacific Daylight Time",
"real_name" : "Egon Spengler",
"color" : "9f69e7",
"team_id" : "T012AB3C4",
"is_admin" : True,
"is_ultra_restricted" : False,
"is_restricted" : False,
"is_owner" : False,
"tz_offset" : -25200,
"has_2fa" : False,
"id" : "W012A3CDE",
"is_primary_owner" : False
}
if __name__ == '__main__':
obj = User(SAMPLE_OBJECT)
attributes = [i for i in dir(obj) if not i.startswith('__')]
for i in attributes:
print(i, getattr(obj, i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment