В настоящее время я работаю над тем, что я считаю своим первым «реальным» проектом python.
В настоящее время у меня есть несколько json значений, которые я пытаюсь сопоставить с двумя разными функциями. Я уже использовал json load для преобразования в словарь, однако я чувствую, что пытаюсь понять, как я структурировал свой код.
[
{
"jumpcloud-group-name":"Gsuite-Team",
"jumpcloud-group-id":"5d2f41asdasf502ee9aa0ec",
"google-group-name":"test@somewebsite.com"
},
{
"jumpcloud-group-name":"Gsuite-Team2",
"jumpcloud-group-id":"asdasda2342342sdasdasd",
"google-group-name":"test1@somewebsite.com"
}
]
with open('groups.json') as json_file:
data = json.load(json_file)
# Create a list for User ID's
user_ids = []
def jumpcloud_group_membership_ids():
# Configures and Authenticates to the Jumpcloud API V2
configuration = jcapiv2.Configuration()
configuration.api_key['x-api-key'] = jumpcloud_api_key
# create an instance of the API class
api_instance = jcapiv2.UserGroupMembersMembershipApi(jcapiv2.ApiClient(configuration))
group_id = '5dasdasfd42342345adada' # str | ObjectID of the User Group.
content_type = 'application/json' # str | (default to application/json)
accept = 'application/json' # str | (default to application/json)
limit = 100 # int | The number of records to return at once. Limited to 100. (optional) (default to 10)
skip = 0 # int | The offset into the records to return. (optional) (default to 0)
x_org_id = '' # str | (optional) (default to )
# List the members of a User Group
user_group_members_api_response = api_instance.graph_user_group_members_list(group_id, content_type, accept,limit=limit, skip=skip, x_org_id=x_org_id)
# Convert API response to a string
string_user_group_members_api_response = str(user_group_members_api_response)
# Format string to get ready for JSON Loads
# This is unfortunately needed as the Jumpcloud API returns a Graph Connection that is not valid json.
prepare_for_json = string_user_group_members_api_response.replace("\'", '\"').replace('None', 'null')
# Convert to json
json_response = json.loads(prepare_for_json)
# Adds each ID from json_response to the list user_id's
for d in json_response:
for key, value in d['to'].items():
if key == 'id':
user_ids.append(value)
jumpcloud_group_membership_ids()
# Creates a list for the email addresses that will be returned from the jumpcloud API call
email_list = []
def jumpcloud_group_membership_emails(id):
# Configures and Authenticates to the Jumpcloud API V1
configuration = jcapiv1.Configuration()
configuration.api_key['x-api-key'] = jumpcloud_api_key
api_instance = jcapiv1.SystemusersApi(jcapiv1.ApiClient(configuration))
content_type = "application/json" # str | (default to application/json)
accept = "application/json" # str | (default to application/json)
fields = "email firstname lastname username " # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned. (optional) (default to )
filter = 'none' # str | A filter to apply to the query. (optional)
x_org_id = "" # str | (optional) (default to )
api_response1 = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)
api_response2 = str(api_response1)
jsondata = ast.literal_eval(api_response2)
email = jsondata["email"]
email_list.append(email)
for id in user_ids:
jumpcloud_group_membership_emails(id)
formated_email_list = (list(map(lambda x : {'email': x}, email_list)))
def main():
# The Pickle is unique to the scope. If you change the scope then you need a new pickle
# The Pickle should also be safeguarded as it provides access to the NC Gsuite account
SCOPES = ['https://www.googleapis.com/auth/admin.directory.group']
creds = None
## The following Creates a Token Pickle once you authenticate with Oauth2.0.
## The Pickle is unique to the scope... If you change the scope then you need a new pickle
if os.path.exists('token.pickle'):
with google_pickle as token:
creds = pickle.load(token)
# prompts for credentials if there is no pickle
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
directoryService = build('admin', 'directory_v1', credentials=creds)
for emails in formated_email_list:
groupinfo = emails
directoryService.members().insert(groupKey='test@somewebsite.com', body=groupinfo).execute()
if __name__ == '__main__':
main()
У меня в основном 2 вопроса. Как я могу сопоставить ключи и значения json с полем идентификатора группы и полем ключа группы?
Меня также беспокоит, что как только я смогу сопоставить значения с функциями и запустить их непрерывно, я буду добавлять многие идентификаторы в список user_ids и email_lsit.
Любые советы будут оценены.