在 API 请求上获取 HTTPError

Getting HTTPError on API request

我最近开始学习 Python 3 并且正在尝试编写我的第一个程序。该程序的本质是在交易大厅自动显示项目。我用的是APIhttps://market.csgo.com/docs-v2。一切都会好起来的,如果不是脚本 运行ning 时出现的错误。我知道使用“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)

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

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 exceptionresponse.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)