I have to code multiple Web Services calls.
For this, i use requests (import requests
).
Each call has the same structure:
try:
retrieved_response = requests.get(url_call,
auth=authentication,
params=search_parameters,
verify=False)
except requests.exceptions.HTTPError as http_error:
logger.error("Bad Status Code", http_error.response)
raise http_error
except [requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout] as connection_error:
logger.error("Connection Problem ", connection_error.response)
raise connection_error
except requests.exceptions.Timeout as timeout_error:
logger.error("Time Out Exception ", timeout_error.response)
raise timeout_error
except requests.exceptions.RequestException as error:
logger.error("Request Error ", error.response)
raise error
I want to create a generic function (or class method) that: - takes as argument the request (get, post, etc) as a string - executes this request passed as a simple string - and returns the web service response
Like this:
def generic_call(call_request: str):
call of the web service by launching the corresponding call request
return the json response of the web service
Outside of this function, i just have to prepare a string storing my request call, and pass this string as parameter to this new generic function.
Until now, i do not know how launch a request from a string. Could you please indicate me how launch a request from a string (a string that will store my request) ?
Thank you very much in advance, Thomas
From your question and comments, I'm going to assume that you essentially just want to create a wrapper function that will execute the code that you give it and return the result.
You can do this a couple ways, the easiest (and not very safe) being to simply use eval
req = eval("request.call(web_service_url, auth=HTTPAuth(xxx,xxx), params={\"login\":\"toto\"})")
Wrap this into a function like:
def generic_call(requestString):
return eval(requestString)
If you want a safer way, you could use if statements within a function and pass in arguments from outside like this:
def generic_call(method, **kwargs):
if method=="GET":
requests.get(...)
elif method=="POST":
requests.post(...)
Your question is worded a little weirdly, but I assume you meant the eval route. I would advise you put in the extra effort to create the if-elif function, especially if you are using user input into any of these arguments.