如何使用python实现CURL cli以使用REST服务

时间:2014-04-14 23:38:31

标签: python json rest curl

有很多问题已经发布了如何使用python使用REST服务,但它们都没有为我工作, 目前使用以下curl cli我可以获得身份验证令牌。

curl cli

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

当我执行上面的cli时,我得到如下的json响应:

从curl cli上面输出剪辑

< 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 :(得分:0)

查看以下HOWTO的python文档:HOWTO Fetch Internet Resources Using urllib2。在那里,您还可以找到包含Basic authentication代码示例的部分。 HOWTO描述了如何使用模块urllib2

其他有用的库:

答案 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"

答案 2 :(得分:0)

模拟curl命令:

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

在Python中仅使用stdlib:

#!/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)))