📜  Python请求状态代码

📅  最后修改于: 2020-11-06 06:28:27             🧑  作者: Mango


在接收并解释了请求消息后,服务器将以HTTP响应消息进行响应。响应消息具有状态码。它是一个三位数的整数,其中状态代码的第一位数定义了响应的类别,而后两位则没有任何分类作用。第一位数字有5个值:

状态码

S.N. Code and Description
1 1xx: Informational

It means the request was received and the process is continuing.

2 2xx: Success

It means the action was successfully received, understood, and accepted.

3 3xx: Redirection

It means further action must be taken in order to complete the request.

4 4xx: Client Error

It means the request contains incorrect syntax or cannot be fulfilled.

5 5xx: Server Error

It means the server failed to fulfill an apparently valid request.

成功回应

在下面的示例中,我们从URL访问文件,并且响应成功。因此,返回的状态码为200。

import urllib3
http = urllib3.PoolManager()

resp = http.request('GET', 'http://tutorialspoint.com/robots.txt')
print resp.data

# get the status of the response
print resp.status

当我们运行上面的程序时,我们得到以下输出-

User-agent: *
Disallow: /tmp
Disallow: /logs
Disallow: /rate/*
Disallow: /cgi-bin/*
Disallow: /videotutorials/video_course_view.php?*
Disallow: /videotutorials/course_view.php?*
Disallow: /videos/*
Disallow: /*/*_question_bank/*
Disallow: //*/*/*/*/src/*

200

回应失败

在下面的示例中,我们从不存在的url访问文件。响应不成功。因此,返回的状态码是403。

import urllib3
http = urllib3.PoolManager()

resp = http.request('GET', 'http://tutorialspoint.com/robot.txt')
print resp.data

# get the status of the response
print resp.status

当我们运行上面的程序时,我们得到以下输出-

403 Forbidden

Forbidden

You don't have permission to access /robot.txt on this server.

403