openstack swift client 开发初体验,openstackswift,第一次写python代码


第一次写python代码,比较粗糙,主要想掌握swift API调用方法

写一个小程序,获取swift server上的hello.txt文件 然后打印出来

#!/usr/bin/env pythonimport httplibimport jsonfrom urlparse import urlparse, urlunparse, urljoinfrom urllib import quote from eventlet.green.httplib import HTTPConnection def http_connection(url):    '''    test http_connection    '''    parsed = urlparse(url)    conn = HTTPConnection(parsed.netloc)    return parsed, conndef json_request(method, url, **kwargs):    kwargs.setdefault('headers', {})    kwargs['headers']['Content-Type'] = 'application/json'    kwargs['body'] = json.dumps(kwargs['body'])    parsed, conn = http_connection(url)    conn.request(method, parsed.path, **kwargs)    resp = conn.getresponse()    body = resp.read()    body = json.loads(body)    return resp, bodydef get_auth():    url = 'http://192.168.4.87:5000/v2.0/'    body = {'auth': {'passwordCredentials': {'password': 'zhoubing',        'username':'swift'},'tenantName': 'service'}}    token_url = urljoin(url, "tokens")     resp, body = json_request("POST", token_url, body=body)    token_id = None    try:        url = None        catalogs = body['access']["serviceCatalog"]        for service in catalogs:            if service['type'] == 'object-store':                url = service['endpoints'][0]['publicURL']        token_id = body['access']['token']['id']    except(KeyError,IndexError):        print Error    return url, token_iddef get_object():    url, token = get_auth()    parsed, conn = http_connection(url)    path = '%s/%s/%s' % (parsed.path, quote('myfile'), quote('asd.txt'))    method = 'GET'    headers = {'X-Auth-Token': token}    conn.request(method, path,'',headers)    resp = conn.getresponse()    body = resp.read()    print bodyif __name__ == '__main__':    get_object()#该片段来自于http://byrx.net

评论关闭