带有身份验证的python请求(access_token) [英] python request with authentication (access_token)

查看:97
本文介绍了带有身份验证的python请求(access_token)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 API 查询导入 Python.命令行

curl --header "Authorization:access_token myToken" https://website.com/id

给出一些 json 输出.myToken 是一个十六进制变量,始终保持不变.我想从 python 进行这个调用,以便我可以遍历不同的 id 并分析输出.有任何想法吗?在需要身份验证之前,我已经使用 urllib2 完成了这项工作.我还查看了请求模块,但不知道如何做到这一点.

非常感谢.

解决方案

requests 包有一个非常好的 HTTP 请求 API,添加自定义标头的工作方式如下(来源:官方文档):

<预><代码>>>>进口请求>>>响应 = requests.get(... 'https://website.com/id', headers={'Authorization': 'access_token myToken'})

如果不想使用外部依赖,同样使用标准库的 urllib2 看起来像这样(来源:缺少的手册):

<预><代码>>>>导入 urllib2>>>响应 = urllib2.urlopen(... urllib2.Request('https://website.com/id', headers={'Authorization': 'access_token myToken'})

I am trying to get an API query into python. The command line

curl --header "Authorization:access_token myToken" https://website.com/id

gives some json output. myToken is a hexadecimal variable that remains constant throughout. I would like to make this call from python so that I can loop through different ids and analyze the output. Any ideas? Before authentication was needed I have done that with urllib2. I have also taken a look at the requests module but couldn't figure out how to do that.

Many thanks.

解决方案

The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):

>>> import requests
>>> response = requests.get(
... 'https://website.com/id', headers={'Authorization': 'access_token myToken'})

If you don't want to use an external dependency, the same thing using urllib2 of the standard library looks like this (source: the missing manual):

>>> import urllib2
>>> response = urllib2.urlopen(
... urllib2.Request('https://website.com/id', headers={'Authorization': 'access_token myToken'})

这篇关于带有身份验证的python请求(access_token)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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