在 Python 中使用 requests 模組實現 Curl 命令

Aditya Raj 2023年1月30日
  1. 在 Python 中安裝 requests 模組
  2. 在 Python 中使用 requests 模組的不同 Curl 命令
  3. まとめ
在 Python 中使用 requests 模組實現 Curl 命令

本文將討論並使用 Python 中的 requests 模組實現不同的 curl 命令。

在 Python 中安裝 requests 模組

Python 為我們提供了 requests 模組來執行 curl 命令。通過在 bash 終端中執行以下命令,使用 Pip3 在 Python 3 中安裝它。

pip3 install requests

對於以前版本的 Python,請通過執行以下命令使用 Pip 安裝 Requests 模組。

pip install requests

下一節將一一實現 Python 中的所有 curl 方法。

本教程將向 Dummy Rest API 傳送請求以執行命令,這是一個響應 curl 命令的虛擬 API。curl 命令返回的資料包含一個虛假的社交媒體平臺,其中包含不同的使用者、帖子、相簿、照片等。

在 Python 中使用 requests 模組的不同 Curl 命令

因為我們需要在與伺服器互動時執行不同的操作,所以每個任務都有特定的 curl 命令。

在 Python 中使用 Requests 模組實現 Get Curl 命令

我們使用 Get curl 方法從伺服器請求資訊。這方面的示例是任何只讀操作,例如單擊網頁、流式傳輸視訊等。

我們可以使用 requests.get() 方法,它接受 Get 方法的 URL 作為其輸入引數,並返回 requests.Response 型別的 Response 物件。

例子:

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.get(api_link)
print("The response is:", output)
print("Data type of response is:", type(output))

輸出:

The response is: <Response [200]>
Data type of response is: <class 'requests.models.Response'>

每個返回的 Response 物件都有特定的屬性,如響應程式碼、標題、內容等。我們可以按如下方式訪問它。

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.get(api_link)
print("The header in the response is:")
print(output.headers)
print("The response code is:")
print(output.status_code)
print("The response url is:")
print(output.url)
print("The response content is:")
print(output.content)

輸出:

The header in the response is:
{'Date': 'Wed, 23 Feb 2022 16:29:06 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '998', 'X-Ratelimit-Reset': '1645368134', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'max-age=43200', 'Pragma': 'no-cache', 'Expires': '-1', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"116-jnDuMpjju89+9j7e0BqkdFsVRjs"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', 'Age': '2817', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=gqOambHdiHjqe%2BfpyIj5A5LYTGm%2BONF4uN9kXU9%2ByYgYx%2BbU1xmnrgw8JJk4u5am5SZn%2F1xyvb%2By4zB2zNkuT%2F1thH%2Bx8xr82N50ljyZwfBS3H6n46N%2B33UdXGh2La0Oa9%2FkhbLOzr2fYmzednU6"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6e21d4c3cfc06eec-BOM', 'Content-Encoding': 'gzip', 'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'}
The response code is:
200
The response URL is:
https://jsonplaceholder.typicode.com/posts/2
The response content is:
b'{\n  "userId": 1,\n  "id": 2,\n  "title": "qui est esse",\n  "body": "est rerum tempore vitae\\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\\nqui aperiam non debitis possimus qui neque nisi nulla"\n}'

要列印響應中的文字,我們可以使用 Response 物件的 text 屬性。

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.get(api_link)
print("The text in the response is:")
print(output.text)

輸出:

The text in the response is:
{
  "userId": 1,
  "id": 2,
  "title": "qui est esse",
  "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}

我們還可以使用 json() 以 JSON 格式列印 get() 方法的響應。

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.get(api_link)
print("The json content in the response is:")
print(output.json())

輸出:

The json content in the response is:
{'userId': 1, 'id': 2, 'title': 'qui est esse', 'body': 'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla'}

在 Python 中使用 requests 模組實現 Post Curl 命令

我們可以使用 Post 命令將資料傳送到伺服器,將其視為集合中的插入操作。在這裡,我們不需要指定資料的儲存位置。

Post 方法的示例包括在社交媒體平臺上建立使用者帳戶、在 StackOverflow 上釋出問題等。

為了實現,我們可以使用 requests.post() 方法。

post() 方法將新 Request 物件的 URL 作為其第一個輸入引數。我們可以將諸如字典、元組列表或 JSON 物件之類的物件作為輸入引數傳遞給 data 引數。

我們可以使用 headers 引數傳送標頭,使用 JSON 引數傳送 JSON 物件等。data 引數的預設值為 None

執行後,post() 方法向伺服器傳送一個 post 請求,並返回一個 requests.Response 資料型別的 Response 物件。

例子:

import requests as rq

data_object = {"userId": 111, "id": 123, "title": "Sample Title"}
api_link = "https://jsonplaceholder.typicode.com/posts/"
output = rq.post(api_link, data_object)
print("The response is:", output)
print("Data type of response is:", type(output))

輸出:

The response is: <Response [201]>
Data type of response is: <class 'requests.models.Response'>

在示例中,我們使用 Python 中的 Post curl 命令在伺服器的資料庫中建立了一條新的帖子記錄。

實際上,由於我們使用的是虛擬 REST API,因此不會在伺服器上釋出帖子。但是,伺服器會模擬一個程序並返回一個狀態碼和相關資料,表明 post() 命令已被執行。

訪問 post() 方法返回的 Response 物件的不同屬性,如下所示。

import requests as rq

data_object = {"userId": 111, "id": 123, "title": "Sample Title"}
api_link = "https://jsonplaceholder.typicode.com/posts/"
output = rq.post(api_link, data_object)
print("The header in the response is:")
print(output.headers)
print("The response code is:")
print(output.status_code)
print("The response url is:")
print(output.url)
print("The response content is:")
print(output.content)

輸出:

The header in the response is:
{'Date': 'Wed, 23 Feb 2022 16:46:37 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '61', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '999', 'X-Ratelimit-Reset': '1645634849', 'Vary': 'Origin, X-HTTP-Method-Override, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '-1', 'Access-Control-Expose-Headers': 'Location', 'Location': 'http://jsonplaceholder.typicode.com/posts//101', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"3d-uGbtVxfcg580jWo4cMrgwUKWTZA"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'DYNAMIC', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=dpGflkwdx9n%2B3elhuPKogSNjzW5A1yBpla29W5VLk6YLUzQG2i53oQXEXbF2lxPbN0qsq%2BqC%2BXSpKxAbWqN36I5sTONqyblOz%2BQ5j8mYIGGQeuWI7KiU03Vwp8BTiGwqeOBES6DOGuU22peaa78J"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6e21ee68cbd92eb6-SIN', 'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'}
The response code is:
201
The response URL is:
https://jsonplaceholder.typicode.com/posts/
The response content is:
b'{\n  "userId": "111",\n  "id": 101,\n  "title": "Sample Title"\n}'

在 Python 中使用 Requests 模組實現 Put Curl 命令

我們還使用 Put 方法將資料傳送到伺服器,但我們指定資料的去向。示例包括更新社交媒體平臺上的個人資料、釋出 StackOverflow 問題的答案等。

要實現 Put curl 命令,我們可以使用 put() 方法,類似於 post() 方法。

執行後,它還返回一個 requests.Response 資料型別的 Response 物件。

import requests as rq

data_object = {"userId": 1, "id": 2, "title": "updated title", "body": "updated body"}
api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.put(api_link, data_object)
print("The response is:", output)
print("Data type of response is:", type(output))

輸出:

The response is: <Response [200]>
Data type of response is: <class 'requests.models.Response'>

我們使用 put() 方法更新了一個 post。同樣,由於我們使用了一個虛擬 REST API,該帖子沒有在伺服器上更新。

如下所示,我們可以列印 put() 方法返回的 Response 物件的不同屬性。

import requests as rq

data_object = {"userId": 1, "id": 2, "title": "updated title", "body": "updated body"}
api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.put(api_link, data_object)
print("The header in the response is:")
print(output.headers)
print("The response code is:")
print(output.status_code)
print("The response url is:")
print(output.url)
print("The response content is:")
print(output.content)

輸出:

The header in the response is:
{'Date': 'Wed, 23 Feb 2022 16:49:24 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '999', 'X-Ratelimit-Reset': '1645634969', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '-1', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"54-RFApzrEtwBFQ4y2DO/oLSTZrNnY"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'DYNAMIC', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=ad%2B%2FEAFK338xNieWtoBeSIPLc7VH015dF65QUBuE7AknX%2BKVHgzcoY7wCDpuExtug1w3zLMXq8mO%2FDVjAKEFyXe6RsgvvwEvtg8gP5elj7sDxXGDT6nXEqG7l6Q9XQ%2BY5J0SqzQIouNZ2gyo0J91"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6e21f27ed9ea563a-SIN', 'Content-Encoding': 'gzip', 'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'}
The response code is:
200
The response URL is:
https://jsonplaceholder.typicode.com/posts/2
The response content is:
b'{\n  "userId": "1",\n  "id": 2,\n  "title": "updated title",\n  "body": "updated body"\n}'

在 Python 中使用 requests 模組實現 Delete Curl 命令

顧名思義,我們使用 Delete 方法從伺服器中刪除指定的資料。Delete 方法的示例包括從社交媒體帳戶中刪除個人資訊、刪除 StackOverflow 問題的答案等。

為了實現 Delete curl 命令,我們使用 requests.delete() 方法。

delete() 方法將我們必須執行 Delete curl 操作的 URL 和其他相關資料作為輸入引數。它還返回一個 requests.Response 資料型別的 Response 物件。

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.put(api_link)
print("The response is:", output)
print("Data type of response is:", type(output))

輸出:

The response is: <Response [200]>
Data type of response is: <class 'requests.models.Response'>

使用下面的程式碼列印返回的 Response 物件的不同屬性。

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.put(api_link)
print("The header in the response is:")
print(output.headers)
print("The response code is:")
print(output.status_code)
print("The response url is:")
print(output.url)
print("The response content is:")
print(output.content)

輸出:

The header in the response is:
{'Date': 'Wed, 23 Feb 2022 16:52:58 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '13', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '999', 'X-Ratelimit-Reset': '1645635209', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '-1', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"d-GUEcOn+YmHSF2tizNHXIHPjfR5k"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'DYNAMIC', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=WCIIO1n%2FtlmR6PYwsKbNmScEPP8ypXyY0du2MWE9cYjkX3Yjl1CD4m4XgJ%2FAdDYrPQxfyc%2B4b%2F1dn%2FbimsZi9sMn0s%2FocQdFGCulOadr%2FjMmM%2FN10STq3z7v5LklANYT%2BOwW6nZg5gYNFj8BY1Z3"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6e21f7b75ec884e9-BOM', 'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'}
The response code is:
200
The response URL is:
https://jsonplaceholder.typicode.com/posts/2
The response content is:
b'{\n  "id": 2\n}'

まとめ

本文討論了 curl 命令並使用 requests 模組在 Python 中實現了它們。Requests 模組中提供的方法比 pycurl 模組中提供的方法要慢。

作者: Aditya Raj
Aditya Raj avatar Aditya Raj avatar

Aditya Raj is a highly skilled technical professional with a background in IT and business, holding an Integrated B.Tech (IT) and MBA (IT) from the Indian Institute of Information Technology Allahabad. With a solid foundation in data analytics, programming languages (C, Java, Python), and software environments, Aditya has excelled in various roles. He has significant experience as a Technical Content Writer for Python on multiple platforms and has interned in data analytics at Apollo Clinics. His projects demonstrate a keen interest in cutting-edge technology and problem-solving, showcasing his proficiency in areas like data mining and software development. Aditya's achievements include securing a top position in a project demonstration competition and gaining certifications in Python, SQL, and digital marketing fundamentals.

GitHub