Requests 简明教程

Requests - How Http Requests Work?

Python 的 Requests 是一个 HTTP 库,它将帮助我们在客户端和服务器之间交换数据。想象一下,您有一个表单的 UI,您需要在其中输入用户详细信息,因此一旦您输入了它,您就必须提交数据,而这只不过是从客户端到服务器的保存数据的 HTTP POST 或 PUT 请求。

Python’s Requests is a HTTP library that will help us exchange data between the client and the server. Consider you have a UI with a form, wherein you need to enter the user details, so once you enter it, you have to submit the data which is nothing but a Http POST or PUT request from the client to server to save the data.

当您想要数据时,您需要从服务器获取它,这又是一个 Http GET 请求。客户端请求数据时数据在客户端和服务器之间的交换,以及服务器用所需数据进行响应,这种客户端和服务器之间的关系非常重要。

When you want the data, you need to fetch it from the server, which is again a Http GET request. The exchange of data between the client when it requests the data and the server responding with the required data, this relationship between the client and the server is very important.

请求已发送到给定的 URL,它可以是安全或非安全 URL。

The request is made to the URL given and it could be a secure or non-secure URL.

对 URL 的请求可以使用 GET、POST、PUT、DELETE。使用最广泛的是 GET 方法,主要用于您想要从服务器获取数据时。

The request to the URL can be done using GET, POST, PUT, DELETE. The most commonly used is the GET method, mainly used when you want to fetch data from the server.

您还可以将数据以查询字符串的形式发送到 URL,例如 -

You can also send data to the URL as a query string for example −

因此,在这里,我们向 URL 传递 id = 9 和 username = Delphine。所有值都在问号 (?) 之后以键/值对的形式发送,并且使用 & 符号将多个参数传递给 URL。

So here, we are passing id = 9 and username = Delphine to the URL. All the values are sent in key/value pair after the question mark(?) and multiple params are passed to the URL separated by &.

使用请求库,使用字符串字典按如下方式调用 URL。

Using the request library, the URL is called as follows using a string dictionary.

其中发送到 URL 的数据以字符串字典的形式发送。如果您想传递 id = 9 和 username = Delphine,可以按如下操作 -

Wherein the data to the URL is sent as a dictionary of strings. If you want to pass id = 9 and username = Delphine, you can do as follows −

payload = {'id': '9', 'username': 'Delphine'}

调用 requests 库按如下方式 -

The requests library is called as follows −

res = requests.get('https://jsonplaceholder.typicode.com/users',
params = payload')

Using POST, we can do as follows −

res = requests.post('https://jsonplaceholder.typicode.com/users', data =
{'id':'9', 'username':'Delphine'})

Using PUT

res = requests.put('https://jsonplaceholder.typicode.com/users', data =
{'id':'9', 'username':'Delphine'})

Using DELETE

res = requests.delete('https://jsonplaceholder.typicode.com/users')

HTTP 请求的响应可以为文本编码形式、二进制编码、json 格式或原始响应。请求和响应的详细信息将在下一章详细说明。

The response from the Http request can be in text encoded form, binary encoded, json format or raw response. The details of the request and response are explained in detail in the next chapters.