You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Django对接Printify API出现401错误:Token配置位置及参数传递问题排查

Fixing 401 Unauthorized & 404 Errors When Connecting Django to Printify API

Let's tackle your issues head-on—you mentioned seeing a 404 first, then a 401. Both are fixable with a few key checks and code tweaks.

First: Why You're Getting a 401 Unauthorized Error

A 401 means Printify isn't recognizing your authentication token. Here's what to verify:

1. Double-Check Your Token's Source & Configuration

  • Make sure settings.TOKEN_PRINTIFY holds a valid Printify API token. You generate these in your Printify account under Settings > API—it's a long random string with no extra characters or prefixes.
  • Confirm your Authorization header is formatted correctly: Your code uses 'Bearer ' + token, but ensure there's a single space between Bearer and your token. Missing that space is a super common mistake that breaks authentication.

2. Fix the 404 (Which Might Have Been a Red Herring)

Your original request used https://api.printify.com/v1/shops, but Printify's API requires a .json suffix for this endpoint. That's why you saw a 404 earlier. The correct endpoint is https://api.printify.com/v1/shops.json.

Revised View Function with Error Handling

Here's a cleaned-up version of your code with checks to avoid both issues, plus better error reporting:

def home(request):
    token = settings.TOKEN_PRINTIFY
    
    # First, make sure the token is actually set
    if not token:
        print("ERROR: Printify API token is missing from settings!")
        context = {"error": "Printify API token not configured"}
        return render(request, 'home.html', context)
    
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {token}'  # F-strings make spacing easier to spot
    }
    
    try:
        # Use the correct endpoint with .json suffix
        response = requests.get('https://api.printify.com/v1/shops.json', headers=headers)
        # Trigger an exception for any HTTP error (like 401, 404)
        response.raise_for_status()
        
        # If we get here, the request worked—parse the data
        shops = response.json()
        print("Success! Retrieved shops:", shops)
        context = {"shops": shops}
        
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP Error occurred: {http_err}")
        context = {"error": f"Request failed: {http_err}"}
    except Exception as err:
        print(f"Unexpected error: {err}")
        context = {"error": f"Unknown error: {err}"}
    
    return render(request, 'home.html', context)

Extra Troubleshooting Tips

  • Test your token outside Django first: Use curl or Postman to run curl -H "Authorization: Bearer YOUR_TOKEN" https://api.printify.com/v1/shops.json. If this returns 401, your token is invalid—regenerate it in Printify's settings.
  • Verify your token is loading correctly: Add print("Printify Token:", token) right after fetching it from settings. If it's empty or garbage, fix your settings.py configuration.

内容的提问来源于stack exchange,提问作者riccardo test

火山引擎 最新活动