在API请求上获取HTTPError

克鲁斯堡斯堡:

我最近开始学习Python 3,并试图编写我的第一个程序。该程序的本质是自动在交易大厅显示商品。我使用API https://market.csgo.com/docs-v2一切都很好,如果不是的话,脚本运行时出现的错误也可以。我知道使用“ TRY and EXECPT”,但是如何正确使用呢?我的代码:

while True: 
    try:
        ip = {'18992549780':'10000', '18992548863':'20000','18992547710':'30000','18992546824':'40000', '18992545927':'50000', '18992544515':'60000', '18992543504':'70000', '18992542365':'80000', '18992541028':'90000', '18992540218':'100000'}
        for key,value in ip.items():
            url3 = ('https://market.csgo.com/api/v2/add-to-sale?key=MYAPIKEY&id={id}&price={price}&cur=RUB')
            addtosale = url3.format(id = key, price = value)
            onsale = requests.get(addtosale)
            onsale.raise_for_status()
            r = onsale.json()
            print(addtosale)
            print(onsale.raise_for_status)
            print(r)
            time.sleep(5)
    except requests.HTTPError as exception:
        print(exception)

我的任务是在出现任何错误(例如5xx)时再次在TRY和EXCEPT之间运行这段代码

Traceback (most recent call last):
  File "D:\Python\tmsolve1.py", line 30, in <module>
    onsale.raise_for_status()
  File "C:\Users\���������\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 941, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 502 Server Error: Bad Gateway for url: https://market.csgo.com/api/v2/add-to-sale?key=MYAPIKEY&id=18992545927&price=50000&cur=RUB
502 Server Error: Bad Gateway for url: https://market.csgo.com/api/v2/add-to-sale?key=MYAPIKEY&id=18992549780&price=10000&cur=RUB
格雷格:

错误处理可以通过多种方式完成。您有10个API调用。您可以在遇到第一个错误时停止代码,重试请求或继续进行其他调用。

下面的示例将继续运行所有请求。

except requests.HTTPError as exception可能不需要。将引发此错误response.raise_for_status()您可以在调用.raise_for_status()之前执行日志记录。try / catch仅允许代码在循环中继续。

import requests
import time
import json
# while True: # This will make the code loop continuously
try:
    ip = {'18992549780':'10000', '18992548863':'20000','18992547710':'30000','18992546824':'40000', '18992545927':'50000', '18992544515':'60000', '18992543504':'70000', '18992542365':'80000', '18992541028':'90000', '18992540218':'100000'}
    for key,value in ip.items():        
        url= 'https://market.csgo.com/api/v2/add-to-sale'
        payload = {'key': 'MYAPIKEY', 'id': id, 'price': value, 'cur': 'RUB'}        
        response = requests.get(url, params=payload)
        print(f'Status code: { response.status_code}')
        print(f'Response text: { response.text}') # This will contain an error message or json results.
        response.raise_for_status() # This will only error if status code is 4xx or 5xx        
        results = response.json()

        if results.get('error'): #  "results" can contains {"error":"Bad KEY","success":false}
            raise Exception('Error in response json')

        print(json.dumps(results))
        time.sleep(5)
except requests.HTTPError as exception: # Captures response.raise_for_status() - 4xx or 5xx status code. If you remove this, then code will use generic handle        
    print(exception)
except Exception as exception: # Generic error handler for raise Exception('Error in response json') and "Max retries exceeded."
    print(exception)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

HttpError 400错误请求-Google Admin Directory API(Python)

无法在 PythonAnywhere 上获取 Flask python API 的请求标头

Python删除请求以获取其他API(在GAE上)

API获取请求

获取请求API

服务器端Google API服务请求会产生googleapiclient.errors.HttpError:<HttpError 404

在@RestControllerAdvise上获取请求正文

提取API请求多个获取请求

HTTP从API获取对XML的请求

获取GET请求对API的响应

在YouTube API中获取请求

json api获取请求错误

api获取请求,处理404

获取Adsense请求的API密钥

获取 API POST 请求响应

获取请求后,托管在 Azure 上的 Web API 不返回本地数据

使用 Wordpress Rest api 获取请求不起作用(仅在 Edge 上)

从Flask API获取“请求的资源上不存在'Access-Control-Allow-Origin'标头”

在“错误”中获取和发布请求结果:在我的 Spring Boot api 上“未找到”

Google API和Directory SDK:获取每个域的组数:HttpError(“ group”)

龙卷风:获取HTTPError的log_message以便在请求处理程序的on_finish期间进行记录?

如何从Go上的请求主体获取JSON

在fcgi上的Golang中获取GET请求

从 Powershell 上的 HTTP 请求获取响应链接

在 android 上的 react native 上的 expo 上获取请求失败

django和python请求-在发布请求上获取403

如何在nginx上获取等待或排队的请求的请求主体?

猫鼬上的发布请求与获取请求不匹配

requests.exceptions.HTTPError:400客户端错误:错误的网址请求:https://accounts.spotify.com/api/token