我必须编写多个 Web 服务调用代码。 为此,我使用请求 (
import requests
)。
每个调用都有相同的结构:
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
我想创建一个通用函数(或类方法): - 将请求(get、post 等)作为字符串作为参数 - 执行作为简单字符串传递的请求 - 并返回 Web 服务响应
像这样:
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
在此函数之外,我只需准备一个存储我的请求调用的字符串,并将该字符串作为参数传递给这个新的通用函数。
到目前为止,我不知道如何从字符串启动请求。 您能否指示我如何从字符串(将存储我的请求的字符串)启动请求?
提前非常感谢您, 托马斯
根据您的问题和评论,我假设您本质上只是想创建一个包装函数,该函数将执行您提供的代码并返回结果。
您可以通过几种方法来做到这一点,最简单(但不是很安全)的是简单地使用 eval
req = eval("request.call(web_service_url, auth=HTTPAuth(xxx,xxx), params={\"login\":\"toto\"})")
将其包装到一个函数中,例如:
def generic_call(requestString):
return eval(requestString)
如果你想要一种更安全的方法,你可以在函数中使用 if 语句并从外部传入参数,如下所示:
def generic_call(method, **kwargs):
if method=="GET":
requests.get(...)
elif method=="POST":
requests.post(...)
您的问题措辞有点奇怪,但我认为您指的是评估路线。我建议您付出额外的努力来创建 if-elif 函数,特别是如果您在任何这些参数中使用用户输入。