带有请求的 Python 3 尝试使用 Tumblr API,我收到错误 401? [英] Python 3 with Requests trying to use Tumblr API, I get error 401?

查看:82
本文介绍了带有请求的 Python 3 尝试使用 Tumblr API,我收到错误 401?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 Python 3,我正在尝试通过 API API 文档链接发布到 Tumblr.尽管感觉我做的一切都正确,但我仍然收到错误 401.Python 2 中有一个官方 API 客户端,但感觉有点难以理解,所有其他提到的似乎都是用 PHP 或 Java 编写的.我也不确定在 401 错误后发布的格式,因为文档除了/post 之外没有给出任何明确的例子.我的代码:

导入请求从 requests_oauthlib 导入 OAuth1#后面的变量client_key=""client_secret=""oauth_token=""oauth_token_secret=""#获取变量的值使用 open("API.txt", 'r') 作为 readAPI:readAPI.readline()client_key=readAPI.readline()[23:]client_secret=readAPI.readline()[23:]oauth_token=readAPI.readline()[23:]oauth_token_secret=readAPI.readline()[23:]readAPI.close()#打印它们以仔细检查它们是否被正确读取打印(客户端密钥)打印(client_secret)打印(oauth_token)打印(oauth_token_secret)#设置连接的oauthoauth = OAuth1(client_key,客户秘密,oauth_token,oauth_token_secret)#check post 应该返回各种博客统计信息r = requests.get("http://api.tumblr.com/v2/user/info",auth=oauth)打印(右)

我 100% 确定我正在获取正确的客户端密钥、客户端密钥、oauth 令牌和 oauth 令牌密钥.我已经仔细检查过,oauth 令牌都放在手动读取的文件中,并在连接尝试之前打印出来.我 100% 确定它是正确的.我想知道 Tumblr 的 API 是不是坏掉了?

这是用 print(repr())

'client_key''client_secret''oauth_token''oauth_token_secret'{"meta":{"status":401,"msg":"未授权"},"response":[]}

这是在尝试新代码并使用 Steven 的 JSON 方法后发生的情况.

b'{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}'

解决方案

而不是这样做:

print(client_key)

这个输出是什么?

print(repr(client_key))

您正在使用 readline,它在每行末尾包含一个换行符:

$ cat foo.txt钥匙秘密布拉布拉$ python3.4>>>f = open("foo.txt")>>>打印(repr(f.readline()))'键\n'>>>打印(repr(f.readline()))'秘密\n'>>>打印(repr(f.readline()))'blabla\n'

你有没有试过从每一行去掉换行符?

<小时>

编辑:根据@user2853325 的评论更新我的帖子.您的代码在 Python 3.4、requests==2.5.2 和 requests-oauthlib==0.4.2 下对我有用.

API.json(编辑密钥/秘密):

<预><代码>{"client_key": "XXXXXXXXXXXXXXXXXXXXdG7zXIMcDidwQ5pMHuQTbxyhNINrCE","client_secret": "XXXXXXXXXXXXXXXXXXXX72A5HQO1axydP5nlOWCTQx4ECfXfyX","oauth_token": "XXXXXXXXXXXXXXXXXXXX8WAnqMBWaAdnGhnc4gWhJ4j6cufK1W","oauth_token_secret": "XXXXXXXXXXXXXXXXXXXX8Kf82k65JzIcMU7QUp54ssPEzJd7my"}

tumblr.py:

导入json进口请求从 requests_oauthlib 导入 OAuth1#获取变量的值with open("API.json") as f:凭证 = json.load(f)#打印它们以仔细检查它们是否被正确读取打印(凭证)#设置连接的oauthoauth = OAuth1(凭据['client_key'],凭据['client_secret'],凭证['oauth_token'],凭证['oauth_token_secret'])#check post 应该返回各种博客统计信息r = requests.get("http://api.tumblr.com/v2/user/info", auth=oauth)打印(右)打印(r.内容)

输出(修改了 oauth 的内容):

$ bin/python tumblr.py{ 'oauth_token_secret': 'XXXXXXXXXXXXXXXXXXXX8Kf82k65JzIcMU7QUp54ssPEzJd7my', 'client_secret': 'XXXXXXXXXXXXXXXXXXXX72A5HQO1axydP5nlOWCTQx4ECfXfyX', 'client_key': 'XXXXXXXXXXXXXXXXXXXXdG7zXIMcDidwQ5pMHuQTbxyhNINrCE', '组oauth_token': 'XXXXXXXXXXXXXXXXXXXX8WAnqMBWaAdnGhnc4gWhJ4j6cufK1W'}<响应[200]>b'{"meta":{"status":200,"msg":"OK"},"response":{"user":{"name":"lost-theory","likes":0,"以下":2,"default_post_format":"html","blogs":[{"title":"Untitled","name":"lost-theory","posts":0,"url":"http:\\/\\/lost-theory.tumblr.com\\/","updated":0,"description":"","is_nsfw":false,"ask":false,"ask_page_title":"问我任何","ask_anon":false,"followed":false,"can_send_fan_mail":true,"share_likes":true,"likes":0,"twitter_enabled":false,"twitter_send":false,"facebook_opengraph_enabled":"N","tweet":"N","facebook":"N","followers":0,"primary":true,"admin":true,"messages":0,"queue":0,"草稿":0,"type":"public"}]}}}'

既然我已经为自己测试了您的代码:

  • 您是如何获得oauth_tokenoauth_token_secret 的?我通过点击 应用程序开发人员页面上的探索 API"获得了我的.
  • 您不需要调用 readAPI.close(),因为 with 块会自动为您关闭文件(请参阅 官方文档).
  • 我使用 JSON 来存储和读取凭证,这样我 100% 确定我得到了正确的字符串.代码也更简洁.我仍然怀疑您从文件中读取行并对其进行切片的方式.
  • 尝试以与我相同的方式在您的代码中打印 r.content.它是否会为您提供比401 未经授权"更具描述性的错误消息?

I have Python 3 and I am trying to post to Tumblr via API link to API documentation. I keep getting an error 401 despite feeling like I am doing everything correctly. There is an official API client in Python 2 but that feels a bit hard to follow and all other mentions of it seem to be in PHP or Java. I also am not sure of the format to post in after the 401 error because the documentation doesn't give any explicit examples other than /post. My code:

import requests
from requests_oauthlib import OAuth1
#variables for later
client_key=""
client_secret=""
oauth_token=""
oauth_token_secret=""

#gets the values for the variables
with open("API.txt", 'r') as readAPI:
    readAPI.readline()
    client_key=readAPI.readline()[23:]
    client_secret=readAPI.readline()[23:]
    oauth_token=readAPI.readline()[23:]
    oauth_token_secret=readAPI.readline()[23:]
readAPI.close()

#prints them to double check they are being read correctly
print(client_key)
print(client_secret)
print(oauth_token)
print(oauth_token_secret)

#sets oauth for the connection
oauth = OAuth1(client_key,
               client_secret,
               oauth_token,
               oauth_token_secret)

#check post that should return various blog stats
r = requests.get("http://api.tumblr.com/v2/user/info" ,auth=oauth)

print(r)

I am 100% sure I am getting the client key, the client secret, oauth token and oauth token secret correct. I have double checked, the oauth tokens are both put in the file that is being read manually and they are printed before the connection attempt. I am 100% sure it is correct. I'm wondering if Tumblr's API is broken?

Edit: This is with print(repr())

'client_key'
'client_secret'
'oauth_token'
'oauth_token_secret'
{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}

This is what happens after trying a new code and with Steven's method with JSON.

b'{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}'

解决方案

Instead of doing this:

print(client_key)

What is the output of this?

print(repr(client_key))

You're using readline, which includes a newline character at the end of each line:

$ cat foo.txt
key
secret
blabla

$ python3.4
>>> f = open("foo.txt")
>>> print(repr(f.readline()))
'key\n'
>>> print(repr(f.readline()))
'secret\n'
>>> print(repr(f.readline()))
'blabla\n'

Have you tried stripping the newline character off of each line?


Edit: Updating my post based on @user2853325's comments. Your code works for me under Python 3.4, requests==2.5.2, and requests-oauthlib==0.4.2.

API.json (redacted the keys/secrets):

{
    "client_key": "XXXXXXXXXXXXXXXXXXXXdG7zXIMcDidwQ5pMHuQTbxyhNINrCE",
    "client_secret": "XXXXXXXXXXXXXXXXXXXX72A5HQO1axydP5nlOWCTQx4ECfXfyX",
    "oauth_token": "XXXXXXXXXXXXXXXXXXXX8WAnqMBWaAdnGhnc4gWhJ4j6cufK1W",
    "oauth_token_secret": "XXXXXXXXXXXXXXXXXXXX8Kf82k65JzIcMU7QUp54ssPEzJd7my"
}

tumblr.py:

import json

import requests
from requests_oauthlib import OAuth1

#gets the values for the variables
with open("API.json") as f:
    credentials = json.load(f)

#prints them to double check they are being read correctly
print(credentials)

#sets oauth for the connection
oauth = OAuth1(
    credentials['client_key'],
    credentials['client_secret'],
    credentials['oauth_token'],
    credentials['oauth_token_secret']
)

#check post that should return various blog stats
r = requests.get("http://api.tumblr.com/v2/user/info", auth=oauth)
print(r)
print(r.content)

Output (redacted the oauth stuff):

$ bin/python tumblr.py
{'oauth_token_secret': 'XXXXXXXXXXXXXXXXXXXX8Kf82k65JzIcMU7QUp54ssPEzJd7my', 'client_secret': 'XXXXXXXXXXXXXXXXXXXX72A5HQO1axydP5nlOWCTQx4ECfXfyX', 'client_key': 'XXXXXXXXXXXXXXXXXXXXdG7zXIMcDidwQ5pMHuQTbxyhNINrCE', 'oauth_token': 'XXXXXXXXXXXXXXXXXXXX8WAnqMBWaAdnGhnc4gWhJ4j6cufK1W'}
<Response [200]>
b'{"meta":{"status":200,"msg":"OK"},"response":{"user":{"name":"lost-theory","likes":0,"following":2,"default_post_format":"html","blogs":[{"title":"Untitled","name":"lost-theory","posts":0,"url":"http:\\/\\/lost-theory.tumblr.com\\/","updated":0,"description":"","is_nsfw":false,"ask":false,"ask_page_title":"Ask me anything","ask_anon":false,"followed":false,"can_send_fan_mail":true,"share_likes":true,"likes":0,"twitter_enabled":false,"twitter_send":false,"facebook_opengraph_enabled":"N","tweet":"N","facebook":"N","followers":0,"primary":true,"admin":true,"messages":0,"queue":0,"drafts":0,"type":"public"}]}}}'

So now that I've tested your code out for myself:

  • How did you get the oauth_token and oauth_token_secret? I got mine by clicking "Explore API" on the Applications developer page.
  • You don't need to call readAPI.close(), as the with block automatically closes the file for you (see the official docs).
  • I used JSON for storing and reading the credentials, that way I'm 100% sure that I'm getting the correct strings. The code is cleaner too. I'm still suspicious about the way you're reading lines from the file and slicing them.
  • Try printing r.content in your code the same way I am. Does it give you a more descriptive error message than "401 Unauthorized"?

这篇关于带有请求的 Python 3 尝试使用 Tumblr API,我收到错误 401?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆