有没有办法将服务器状态代码提升为客户端?

Is there a way to raise server status code as a client?

有时由于服务器设计不佳,我得到状态码 200,而这应该是不同的。

在这种情况下,我自己在客户端如何才能提出适当的回应(例如404)。这将模拟服务器返回的效果?

我通过 django 看到了一些 answers。这是唯一的方法吗?

此外,我在标准 python 异常 here 中也没有看到任何此类内容。为什么通过标准 python 例外情况不可能做到这一点?

这是我现在的处理方式:

import time

import aiohttp
import backoff


@backoff.on_exception(backoff.expo, aiohttp.ClientError, max_tries=5, max_time=5)
async def _fetch_url(session, url, msg_handler):
    downtime = 1
    while downtime < 60:
        async with await session.get(url, raise_for_status=True) as response:
            result = await msg_handler(response, url)
            # empty results means an error in request but status code 200.
            if len(result) == 0:
                downtime = downtime * 2
                time.sleep(downtime)
            else:
                return result

假设你是运行宁SimpleHTTPServer,最简单的方法是使用SimpleHTTP404Server

您可以通过 运行nning

简单地安装它
pip install SimpleHTTP404Server

浏览到该目录,然后运行将以下内容用于端口 8000 上的服务器。

python -m SimpleHTTP404Server

异常应属于以下类别之一:

  • 语法错误
  • 处理异常
  • 引发异常

显然您在错误的地方寻找解决方案。您可能想要做的是根据特定条件引发 用户定义 异常。

考虑下面的简单示例:

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")

从您的代码来看,您似乎正试图触发一个本应在发生请求错误时触发的操作。但是,状态代码来自服务器,并且不受客户端控制。如果服务器返回 200,则表示它已正确接收并响应您的请求。

装饰器由 aiohttp.ClientError 类型的任何异常触发。因此,要手动触发它,您只需要引发该类型(或其任何派生类型)的异常。 Please refer to this page for the list of all aiohttp exceptions.

因此,当您在服务器响应中发现错误时,您可以使用以下方法引发异常:

raise aiohttp.ClientError('Server response is empty')