python3 使用请求时出错:URL 带有空格

问题描述 投票:0回答:1

我想对 Prolin Smart Suite API 进行 API 调用。使用 Postman 我可以成功完成,调用必须如下所示:

https://myserver.mydomain.net:5181/odata/ConfigurationItems?$filter=Searchcode eq 'myparameter'

尝试在 Python 中执行此操作会出现以下错误:

信息 - 2024-01-10 08:10:12,540 - ci 是我的参数
信息 - 2024-01-10 08:10:12,540 - ci_url 是 http://myserver.mydomain.net:5181/odata/ConfigurationItems? $filter=搜索代码 eq 'myparameter'
错误 - 2024-01-10 08:10:12,540 - 请求期间出错:无效的 URL“myparameter”:未提供架构。也许您的意思是http://myparameter?

这是我的代码:

ci = 'myparameter'
logging.info('ci is '+ci)
ci_url = api_url + f"/ConfigurationItems?$filter=Searchcode eq '{ci}'"
logging.info('ci_url is '+ci_url)

# Get responsible workgroup
def get_responsible_workgroup(ci_url):
    try:
        ci_url = ci_url
        ci_response = requests.get(ci_url)
        #ci_response.raise_for_status()  # Check for HTTP errors
        logging.info("ci_response: "+ci_response.text)
        return ci_response
    except requests.exceptions.RequestException as e:
        logging.error(f"Error during request: {e}")
        return None
        
resp_wg = get_responsible_workgroup(ci)
logging.info('resp_wg is '+str(resp_wg))

我还尝试用相应的 URL 编码(%27 和 %20)替换引号和空格,但这给出了相同的错误。

我进一步尝试使用 ChatGPT 解决方案,但它也不起作用:

# Assuming base_url is defined somewhere in your code
base_url = "http://myserver.mydomain.net:5181/odata"

ci = "myparameter"
ci_sanitized = urllib.parse.quote(ci, safe='')
logging.info('ci is ' + ci)

api_endpoint = '/ConfigurationItems'
filter_parameter = "$filter=Searchcode eq '{}'".format(ci_sanitized)
ci_url = urllib.parse.urljoin(base_url, "{}?{}".format(api_endpoint, filter_parameter))
logging.info('ci_url is ' + ci_url)

try:
    with urllib.request.urlopen(ci_url) as response:
        data = response.read()
        # Process the response data as needed
        print(data.decode('utf-8'))
except urllib.error.URLError as e:
    print("Error during request: {}".format(e))
python python-requests
1个回答
0
投票

更换

ci_url = api_url + f"/ConfigurationItems?$filter=Searchcode eq '{ci}'"

import urllib.parse
ci_url = api_url + "/ConfigurationItems?$filter=" + urllib.parse.quote_plus(f"Searchcode eq '{ci}'")

这会将 URL 中的空格替换为

+
符号,并防止出现 RequestException(未提供架构)。

如果它对您不起作用,请使用更改后程序的输出来扩展问题。


还有一个更强大的解决方案,传递

requests.get(params={...})
,并让 requests 为您构建 URL。为此,请将程序中的
requests.get
行替换为:

requests.get(api_url + "/ConfigurationItems", params={
    "$filter": f"Searchcode eq '{ci}'"})
© www.soinside.com 2019 - 2024. All rights reserved.