Debian Codegraph @

docs/examples/minimal_transfer_script/transfer_consent_required_reactive.py

raw
1 import argparse
2
3 import globus_sdk
4 from globus_sdk.scopes import TransferScopes
5
6 parser = argparse.ArgumentParser()
7 parser.add_argument("SRC")
8 parser.add_argument("DST")
9 args = parser.parse_args()
10
11 CLIENT_ID = "61338d24-54d5-408f-a10d-66c06b59f6d2"
12 auth_client = globus_sdk.NativeAppAuthClient(CLIENT_ID)
13
14
15 # we will need to do the login flow potentially twice, so define it as a
16 # function
17 #
18 # we default to using the Transfer "all" scope, but it is settable here
19 # look at the ConsentRequired handler below for how this is used
20 def login_and_get_transfer_client(*, scopes=TransferScopes.all):
21 auth_client.oauth2_start_flow(requested_scopes=scopes)
22 authorize_url = auth_client.oauth2_get_authorize_url()
23 print(f"Please go to this URL and login:\n\n{authorize_url}\n")
24
25 auth_code = input("Please enter the code here: ").strip()
26 tokens = auth_client.oauth2_exchange_code_for_tokens(auth_code)
27 transfer_tokens = tokens.by_resource_server["transfer.api.globus.org"]
28
29 # return the TransferClient object, as the result of doing a login
30 return globus_sdk.TransferClient(
31 authorizer=globus_sdk.AccessTokenAuthorizer(transfer_tokens["access_token"])
32 )
33
34
35 # get an initial client to try with, which requires a login flow
36 transfer_client = login_and_get_transfer_client()
37
38 # create a Transfer task consisting of one or more items
39 task_data = globus_sdk.TransferData(
40 source_endpoint=args.SRC, destination_endpoint=args.DST
41 )
42 task_data.add_item(
43 "/share/godata/file1.txt", # source
44 "/~/example-transfer-script-destination.txt", # dest
45 )
46
47
48 # define the submission step -- we will use it twice below
49 def do_submit(client):
50 task_doc = client.submit_transfer(task_data)
51 task_id = task_doc["task_id"]
52 print(f"submitted transfer, task_id={task_id}")
53
54
55 # try to submit the task
56 # if it fails, catch the error...
57 try:
58 do_submit(transfer_client)
59 except globus_sdk.TransferAPIError as err:
60 # if the error is something other than consent_required, reraise it,
61 # exiting the script with an error message
62 if not err.info.consent_required:
63 raise
64
65 # we now know that the error is a ConsentRequired
66 # print an explanatory message and do the login flow again
67 print(
68 "Encountered a ConsentRequired error.\n"
69 "You must login a second time to grant consents.\n\n"
70 )
71 transfer_client = login_and_get_transfer_client(
72 scopes=err.info.consent_required.required_scopes
73 )
74
75 # finally, try the submission a second time, this time with no error
76 # handling
77 do_submit(transfer_client)