杰瑞科技汇

Python HTTP 401未授权如何解决?

Of course. The error you're seeing, http unauthor, is almost always a shorthand for HTTP 401 Unauthorized. This is a standard HTTP status code.

Python HTTP 401未授权如何解决?-图1
(图片来源网络,侵删)

Let's break down what this error means, why it happens, and how to fix it in Python.


What is HTTP 401 Unauthorized?

When a server responds with a 401 Unauthorized status code, it means:

"You are not authenticated. You need to provide valid credentials to access this resource."

Think of it like a bouncer at a club asking for your ID. You haven't proven who you are, so you're not allowed in.

Python HTTP 401未授权如何解决?-图2
(图片来源网络,侵删)

Key Point: This is different from HTTP 403 Forbidden.

  • 401 Unauthorized: "Who are you? I don't know you."
  • 403 Forbidden: "I know who you are (e.g., user123), but you don't have permission to access this specific resource."

Common Causes for a 401 Error

  1. Missing Credentials: You didn't provide a username and password or an API key at all.
  2. Incorrect Credentials: The username, password, API key, or token you provided is wrong.
  3. Expired Credentials: Your API key or token has a time limit and has expired.
  4. Incorrect Authentication Header: You provided credentials, but the format of the header was wrong. For example, using Basic auth when the server expects Bearer token auth.
  5. Malformed Token: Your token might have extra spaces, incorrect characters, or not be properly encoded (e.g., not base64 encoded for Basic auth).

How to Fix It in Python: Examples

Here are the most common scenarios using Python's popular requests library.

Scenario 1: Basic Authentication (Username/Password)

This is the most common case for web apps and older APIs. You need to provide a username and password.

The Fix: Use the requests.auth.HTTPBasicAuth object.

Python HTTP 401未授权如何解决?-图3
(图片来源网络,侵删)
import requests
from requests.auth import HTTPBasicAuth
# The URL that requires authentication
url = 'https://api.example.com/protected-resource'
# Your credentials
username = 'your_username'
password = 'your_password'
# Use the auth parameter to pass credentials
try:
    response = requests.get(url, auth=HTTPBasicAuth(username, password))
    # Raise an exception for bad status codes (4xx or 5xx)
    response.raise_for_status() 
    print("Successfully accessed the resource!")
    print(response.json())
except requests.exceptions.HTTPError as err:
    print(f"HTTP Error: {err}")
    # This will catch the 401 error
    if response.status_code == 401:
        print("Authentication failed. Check your username and password.")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Scenario 2: Bearer Token Authentication (Common for Modern APIs)

Many modern APIs (like those for Twitter, GitHub, etc.) use a Bearer token, which is a long string.

The Fix: Add the token to the Authorization header manually.

import requests
url = 'https://api.example.com/v1/data'
api_token = 'your_long_api_token_string_goes_here'
# The token must be prefixed with 'Bearer ' and sent in the Authorization header
headers = {
    'Authorization': f'Bearer {api_token}'
}
try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    print("Successfully accessed the resource!")
    print(response.json())
except requests.exceptions.HTTPError as err:
    print(f"HTTP Error: {err}")
    if response.status_code == 401:
        print("Authentication failed. Check if your API token is correct and not expired.")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Scenario 3: API Key in the Query String

Some APIs expect the API key as a query parameter.

The Fix: Add the key to the URL's query string.

import requests
url = 'https://api.example.com/endpoint'
api_key = 'your_api_key'
# Add the key to the params dictionary
params = {
    'api_key': api_key,
    'param1': 'value1'
}
try:
    response = requests.get(url, params=params)
    response.raise_for_status()
    print("Successfully accessed the resource!")
    print(response.json())
except requests.exceptions.HTTPError as err:
    print(f"HTTP Error: {err}")
    if response.status_code == 401:
        print("Authentication failed. Check if your API key is correct.")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Troubleshooting Checklist

If you're still getting a 401 error, go through this checklist:

  1. Read the Docs: This is the most important step. The API documentation will tell you exactly which authentication method to use (Basic, Bearer, API Key, etc.) and how to format the request.

  2. Check Your Credentials: Are you sure the username, password, or token is correct? Copy and paste it directly from the source to avoid typos.

  3. Check for Expiration: If it's a token, is it expired? Some tokens last for an hour, others for years.

  4. Inspect the Headers: Use a tool like Postman or curl to make a successful request and inspect the Authorization header. Compare it to what your Python script is sending.

  5. Use curl for Testing: Before debugging your Python code, try the request with curl from your terminal. It's simpler and helps isolate the problem.

    # Example for Basic Auth
    curl -u your_username:your_password https://api.example.com/protected-resource
    # Example for Bearer Token
    curl -H "Authorization: Bearer your_long_api_token_string" https://api.example.com/v1/data

    If curl also gives a 401, the problem is with your credentials, not your Python code. If curl works but Python doesn't, the problem is in how you're constructing the request in Python.

分享:
扫描分享到社交APP
上一篇
下一篇