杰瑞科技汇

Python putrequest如何正确使用?

Of course! Let's break down putrequest in Python.

Python putrequest如何正确使用?-图1
(图片来源网络,侵删)

Summary

In Python, putrequest is a method used with the legacy http.client library. Its primary job is to initiate an HTTP request by sending the request line and the headers to the server.

It's a low-level method. You will almost always use it as part of the process of making an HTTP request with http.client, but you won't typically call it directly in modern applications.


Key Context: The http.client Library

First, it's important to understand where putrequest lives. It's part of Python's built-in http.client module, which is a low-level library for making HTTP requests.

  • Low-Level: You are responsible for constructing the entire HTTP message: the request line (e.g., GET /path HTTP/1.1), the headers (e.g., Host: example.com), and the body (if any).
  • Blocking: By default, it performs blocking network I/O, meaning your program will wait until the server responds.
  • Legacy: For most new applications, especially those requiring more features like connection pooling, automatic redirects, or a cleaner API, the third-party requests library is the standard. It's built on top of http.client and other libraries to provide a much more user-friendly experience.

The Role of putrequest

When you make an HTTP request, you send a structured text message to the server. putrequest helps you build the beginning of that message.

Python putrequest如何正确使用?-图2
(图片来源网络,侵删)

The standard HTTP request format is:

METHOD /path/to/resource HTTP/Version
Header-Name: Header-Value
Another-Header: Another-Value
[Optional Request Body]

The putrequest method handles the first line: the request line.

Method Signature

http_client.putrequest(method, url, skip_host=False, skip_accept_encoding=False)

Parameters

  • method (string): The HTTP method you want to use. This is the action you're asking the server to perform. Common values are:
    • "GET"
    • "POST"
    • "PUT"
    • "DELETE"
    • "HEAD"
    • "PATCH"
  • url (string): The path you are requesting on the server. This is just the path, not the full URL like http://example.com/api/data. The Host header must be set separately to specify the domain.
  • skip_host (boolean, optional, default False): If True, the putrequest method will not automatically add the Host: <host> header. You would be responsible for adding it yourself with putheader(). You usually want this to be False.
  • skip_accept_encoding (boolean, optional, default False): If True, it will not automatically add the Accept-Encoding: identity header. This is also usually left as False.

A Practical Example: Making a GET Request

Let's walk through a complete example of using http.client to make a GET request. This will show you where putrequest fits into the entire process.

import http.client
import sys
# --- Configuration ---
host = 'www.python.org'
path = '/'
try:
    # 1. Create a connection object
    # We use HTTPSConnection for secure connections (HTTPS)
    # For HTTP, you would use HTTPConnection(host)
    print(f"Connecting to {host}...")
    connection = http.client.HTTPSConnection(host)
    # 2. Initiate the request with putrequest()
    # This sends the line: "GET / HTTP/1.1"
    # It also prepares the connection to receive headers.
    print("Sending request line...")
    connection.putrequest("GET", path)
    # 3. Add necessary headers using putheader()
    # The Host header is crucial for virtual hosting.
    # putheader() adds a header line.
    connection.putheader("Host", host)
    connection.putheader("User-Agent", "My-Python-App/1.0")
    connection.putheader("Accept", "text/html")
    # 4. Signal that headers are finished with endheaders()
    # This sends a blank line, which is required to separate headers from the body.
    # For a GET request, there is no body, so this just finalizes the request.
    print("Sending headers...")
    connection.endheaders()
    # 5. Get the response from the server
    # This sends the request and waits for the server's response.
    print("Getting response...")
    response = connection.getresponse()
    # 6. Process the response
    print(f"Response status: {response.status} {response.reason}")
    print("-" * 20)
    # You can read the response body
    if response.status == 200:
        body = response.read()
        print(f"Response body (first 100 bytes): {body[:100]}")
    else:
        print("Did not receive a successful response.")
    # 7. Close the connection
    connection.close()
    print("Connection closed.")
except http.client.HTTPException as e:
    print(f"HTTP Error: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

Output of the Example:

Connecting to www.python.org...
Sending request line...
Sending headers...
Getting response...
Response status: 200 OK
--------------------
Response body (first 100 bytes): b'<!doctype html>\n<!--[if IE]><html class="no-js ie ie9" lang="en-US" > <![endif]-->\n<!--[if !(IE)]><!--><html class="no-js" lang="en-US" > <!--<![endif]-->\n<head>\n\t<meta charset="UTF-8">\n\t<meta name="viewport" content="width=device-width, initial-scale=1">\n\t<title>Wel'
Connection closed.

putrequest vs. requests Library

This is the most important comparison for a modern Python developer.

Python putrequest如何正确使用?-图3
(图片来源网络,侵删)
Feature http.client (with putrequest) requests Library
Level Low-level. You manage the raw HTTP message. High-level. You provide data, and it builds the message for you.
Simplicity Complex. Requires multiple steps (putrequest, putheader, endheaders, getresponse). Extremely simple. A single line of code: requests.get('http://...').
URL Handling You must parse the URL to get the host and path. You pass the full URL string directly.
Body/Data You must encode the data and manage Content-Length headers manually. You pass a dict or json object to the json= or data= parameter, and it handles encoding and headers automatically.
Response You get a response object and must call .read() to get the body. The response object has a .text or .json() property for easy access to decoded content.
Features Basic HTTP/HTTPS. No built-in support for sessions, cookies, or connection pooling. Rich feature set: sessions, cookies, authentication, automatic retries, connection pooling, etc.

Example: Same Task with requests

As you can see, the requests version is dramatically simpler and more readable.

import requests
url = 'https://www.python.org'
try:
    # This single line handles everything: connection, request, headers, and response parsing.
    response = requests.get(url)
    # Raise an exception for bad status codes (4xx or 5xx)
    response.raise_for_status()
    print(f"Response status: {response.status_code}")
    print("-" * 20)
    print(f"Response text (first 100 chars): {response.text[:100]}")
except requests.exceptions.RequestException as e:
    print(f"An error occurred with the requests library: {e}")

Conclusion

  • What is putrequest? It's a low-level method in http.client used to send the initial request line (e.g., GET / HTTP/1.1) of an HTTP request.
  • When should you use it? You should use it when you are working directly with the http.client library. This is rare today.
  • What should you use instead? For almost all Python applications, you should use the requests library. It is the de-facto standard for making HTTP requests in Python because it is powerful, easy to use, and handles all the low-level details for you.
分享:
扫描分享到社交APP
上一篇
下一篇