如何使用Python实现CURL命令行以调用REST服务

0 投票
3 回答
1225 浏览
提问于 2025-04-18 02:45

有很多人问怎么用Python来调用REST服务,但我试过的都不管用。现在我用下面的curl命令可以获取到认证令牌。

curl命令

curl -v --user username:pass1234 -H "content-type: application/json" -X POST -d "" https://mywebsite/api/v1/auth/token-services --insecure

当我执行上面的命令时,我得到了下面这样的json响应:

从上面的curl命令得到的输出片段

< HTTP/1.1 200 OK
< Server: nginx/1.4.2
< Date: Mon, 14 Apr 2014 23:22:41 GMT
< Content-Type: application/json
< Content-Length: 201
< Connection: keep-alive
Connection #0 to host <ipaddress> left intact
* Closing connection #0
* SSLv3, TLS alert, Client hello (1):
{"kind": "object#auth-token", "expiry-time": "Mon Apr 14 23:37:41 2014", "token-id": "l3CvWcEr5rKvooOaCymFvy2qp3cY18XCs4JrW4EvPww=", "link": "https://mywebsite/api/v1/auth/token-services/1634484805"}

现在我的问题是,怎么用Python来实现这个?我应该用什么库?我需要从json响应中提取出token-id,这样我才能用这个令牌进行后续的请求来调用REST服务。

如果有人能提供这个的Python代码片段,那就太好了。

3 个回答

0

看看下面这篇关于python的文档教程:使用urllib2获取互联网资源的教程。里面还有一部分提供了关于基本认证的代码示例。这个教程讲解了如何使用一个叫做urllib2的模块。

还有一些其他有用的库:

0

要模拟curl命令:

$ curl -v --user username:pass1234 -H "accept: application/json" \
    -X POST -d "" https://mywebsite/api/v1/auth/token-services --insecure

在Python中只使用标准库:

#!/usr/bin/env python
import base64
import json
from urllib2 import urlopen, Request

credentials = base64.b64encode(b'username:pass1234')
headers={'Authorization': b'Basic ' + credentials,
         'Accept': 'application/json'}
response = urlopen(Request("https://example.com/post", b"", headers))
data = json.load(response)
token_id = data["token-id"]

如果你想查看发送到服务器或从服务器接收到的内容,特别是对于https请求,可以开启调试功能:

import urllib2

urllib2.install_opener(urllib2.build_opener(urllib2.HTTPSHandler(debuglevel=1)))
0

我找到了我想要的解决方案...

完整的示例代码...

import requests
from requests.auth import HTTPBasicAuth
import json

token = ""


def get_token(username, password, url):
    global token

    #verify=False will not verify the ssl 
    resp = requests.post(url, auth=HTTPBasicAuth(username, password), verify=False)

    print "\n", dir(resp)
    print "Status Code:", resp.status_code, "\n"
    print "text:", resp.text, "\n"
    print "json:", resp.json(), "\n"
    print "Content:", resp.content, "\n"
    print "Headers:", resp.headers, "\n"
    print "Header(Content-type:)", resp.headers.get('content-type'), "\n"
    print "Header(Content-length:)", resp.headers.get('content-length'), "\n"
    print "OK:", resp.ok, "\n"
    print "json dump:", json.dumps(resp.json())

    json_dict = json.loads(resp.text)

    token = json_dict['token-id']
    print "\ntoken-id:", json_dict['token-id']

    for key, value in json_dict.items():
        print key, "=>", value

    return token    


def get_global_users(token):
    print "\nexecuting get_global_users.."
    print "Token", token
    url = 'https://xxx.xxx.xxx.xxx/api/v1/global/users'
    headers_dict = {'content-type': 'application/json', 'Accept': 'application/json', 'X-Auth-Token': token}
    resp = requests.get(url, headers=headers_dict, verify=False)
    print "Status Code:", resp.status_code, "\n"
    print "text:", resp.text, "\n"
    print "json:", resp.json(), "\n"
    json_users = json.loads(resp.text)
    print "all users:\n", json_users['users']

    print "\n"
    for users in json_users['users']:
        for key, value in users.items():
            print key, "=>", value


def post_global_user(token):
    print "\nexecuting post_global_users.."
    print "Token:", token
    url = 'https://xxx.xxx.xxx.xxx/api/v1/global/users'
    headers_dict = {'content-type': 'application/json', 'Accept': 'application/json', 'X-Auth-Token': token}
    payload = {'username': 'myuser', 'password': 'pas1234', 'pw-type': 0, 'privilege': 15}
    resp = requests.post(url, data=json.dumps(payload), headers=headers_dict, verify=False)
    print "Status Code:", resp.status_code, "\n"

撰写回答