Debian Codegraph @

docs/examples/create_and_run_flow/manage_flow.py

raw
1 #!/usr/bin/env python
2 import argparse
3 import os
4 import sys
5
6 import globus_sdk
7 from globus_sdk.token_storage import SimpleJSONFileAdapter
8
9 MY_FILE_ADAPTER = SimpleJSONFileAdapter(os.path.expanduser("~/.sdk-manage-flow.json"))
10
11 # tutorial client ID
12 # we recommend replacing this with your own client for any production use-cases
13 CLIENT_ID = "61338d24-54d5-408f-a10d-66c06b59f6d2"
14
15 NATIVE_CLIENT = globus_sdk.NativeAppAuthClient(CLIENT_ID)
16
17
18 def do_login_flow(scope):
19 NATIVE_CLIENT.oauth2_start_flow(requested_scopes=scope, refresh_tokens=True)
20 authorize_url = NATIVE_CLIENT.oauth2_get_authorize_url()
21 print(f"Please go to this URL and login:\n\n{authorize_url}\n")
22 auth_code = input("Please enter the code here: ").strip()
23 tokens = NATIVE_CLIENT.oauth2_exchange_code_for_tokens(auth_code)
24 return tokens
25
26
27 def get_authorizer(flow_id=None):
28 if flow_id:
29 resource_server = flow_id
30 scope = globus_sdk.SpecificFlowClient(flow_id).scopes.user
31 else:
32 resource_server = globus_sdk.FlowsClient.resource_server
33 scope = globus_sdk.FlowsClient.scopes.manage_flows
34
35 # try to load the tokens from the file, possibly returning None
36 if MY_FILE_ADAPTER.file_exists():
37 tokens = MY_FILE_ADAPTER.get_token_data(resource_server)
38 else:
39 tokens = None
40
41 if tokens is None:
42 # do a login flow, getting back initial tokens
43 response = do_login_flow(scope)
44 # now store the tokens and pull out the correct token
45 MY_FILE_ADAPTER.store(response)
46 tokens = response.by_resource_server[resource_server]
47
48 return globus_sdk.RefreshTokenAuthorizer(
49 tokens["refresh_token"],
50 NATIVE_CLIENT,
51 access_token=tokens["access_token"],
52 expires_at=tokens["expires_at_seconds"],
53 on_refresh=MY_FILE_ADAPTER.on_refresh,
54 )
55
56
57 def get_flows_client():
58 return globus_sdk.FlowsClient(authorizer=get_authorizer())
59
60
61 def get_specific_flow_client(flow_id):
62 authorizer = get_authorizer(flow_id)
63 return globus_sdk.SpecificFlowClient(flow_id, authorizer=authorizer)
64
65
66 def create_flow(args):
67 flows_client = get_flows_client()
68 print(
69 flows_client.create_flow(
70 title=args.title,
71 definition={
72 "StartAt": "DoIt",
73 "States": {
74 "DoIt": {
75 "Type": "Action",
76 "ActionUrl": "https://actions.globus.org/hello_world",
77 "Parameters": {
78 "echo_string": "Hello, Asynchronous World!",
79 },
80 "End": True,
81 }
82 },
83 },
84 input_schema={},
85 subtitle="A flow created by the SDK tutorial",
86 )
87 )
88
89
90 def delete_flow(args):
91 flows_client = get_flows_client()
92 print(flows_client.delete_flow(args.flow_id))
93
94
95 def list_flows():
96 flows_client = get_flows_client()
97 for flow in flows_client.list_flows(filter_roles="flow_owner"):
98 print(f"title: {flow['title']}")
99 print(f"id: {flow['id']}")
100 print()
101
102
103 def run_flow(args):
104 flow_client = get_specific_flow_client(args.flow_id)
105 print(flow_client.run_flow({}))
106
107
108 def logout():
109 for tokendata in MY_FILE_ADAPTER.get_by_resource_server().values():
110 for tok_key in ("access_token", "refresh_token"):
111 token = tokendata[tok_key]
112 NATIVE_CLIENT.oauth2_revoke_token(token)
113
114 os.remove(MY_FILE_ADAPTER.filename)
115
116
117 def main():
118 parser = argparse.ArgumentParser()
119 parser.add_argument("action", choices=["logout", "create", "delete", "list", "run"])
120 parser.add_argument("-f", "--flow-id", help="Flow ID for delete and run")
121 parser.add_argument("-t", "--title", help="Name for create")
122 args = parser.parse_args()
123
124 try:
125 if args.action == "logout":
126 logout()
127 elif args.action == "create":
128 if args.title is None:
129 parser.error("create requires --title")
130 create_flow(args)
131 elif args.action == "delete":
132 if args.flow_id is None:
133 parser.error("delete requires --flow-id")
134 delete_flow(args)
135 elif args.action == "list":
136 list_flows()
137 elif args.action == "run":
138 if args.flow_id is None:
139 parser.error("run requires --flow-id")
140 run_flow(args)
141 else:
142 raise NotImplementedError()
143 except globus_sdk.FlowsAPIError as e:
144 print(f"API Error: {e.code} {e.message}")
145 print(e.text)
146 sys.exit(1)
147
148
149 if __name__ == "__main__":
150 main()