Nov-14-2018, 10:07 PM
Hi,
How do you structure code around multiple context managers? I looking to make something like this:
How do you structure code around multiple context managers? I looking to make something like this:
#main.py import file_io.py import rest_api.py main(): main program flow here read something from a log file GET something from a REST API write it to the log file POST something to the REST API
#file_io.py #maybe this could be a class def read(): with open('log.txt') as log_file: read last entry in log_file return entry def write(something): with open('log.txt') as log_file: write something to log_file
#rest_api.py #maybe this could be a class too token = 'super secret' header = {"Authorization":"Bearer {}".format(token)} url = 'api.some_site/endpoint' with requests.Session() as rest_session: rest_session.headers.update(headers) GET/PUT/POST stuff depending on main() return data to mainI can live with opening and closing a file all the time for every operation, but can I avoid stuffing all my main() logic in the API context manager? Maybe at some point there will be another website with a different API that the program also needs to work with. Or is this a case where you wouldn't wrap the requests.Session() in a context manager and pass the session object around as needed while making sure you catch all exception? Sorry if this is a bit fuzzy. Please let me know if you need more clarification.