Python implementation Rest Request API sample

Source: Internet
Author: User
Tags iterable
This code refers to the Sina Python API, which applies to each open Source API request

Copy the Code code as follows:


#-*-Coding:utf-8-*-
Import Collections
Import gzip
Import Urllib
Import Urllib2
From Urlparse import Urlparse

Try
From Cstringio import Stringio
Except Importerror:
From Stringio import Stringio

Try
Import JSON
Except Importerror:
Import Simplejson as JSON


__author__ = ' myth '


_http_get = 1
_http_post = 2
# time-Out (seconds)
TIMEOUT = 45
Return_type = {"JSON": 0, "xml": 1, "html": 2, "Text": 3}
_method_map = {' GET ': _http_get, ' POST ': _http_post}


Class Apierror (StandardError):
"""
Raise Apierror If receiving JSON message indicating failure.
"""
def __init__ (self, Error_code, error, request):
Self.error_code = Error_code
Self.error = Error
Self.request = Request
standarderror.__init__ (self, error)

def __str__ (self):
Return ' Apierror:%s:%s, request:%s '% (Self.error_code, Self.error, Self.request)


# def Callback_type (return_type= ' json '):
#
# Default_type = "JSON"
# default_value = Return_type.get (Default_type)
# if Return_type:
# if Isinstance (Return_type, (str, Unicode)):
# default_value = Return_type.get (Return_type.lower (), default_value)
# return Default_value


def _format_params (_pk=none, Encode=none, **kw):
"""

:p Aram KW:
: type kw:
:p Aram Encode:
: Type encode:
: return:
: Rtype:
"""

__PK = '%s[%%s] '% _pk if _pk Else '%s '
Encode = encode if encode else urllib.quote

For K, V in Kw.iteritems ():
_k = __pk% K
If Isinstance (V, basestring):
QV = V.encode (' utf-8 ') if Isinstance (V, Unicode) Else V
_v = Encode (qv)
Yield _k, _v
Elif isinstance (V, collections. iterable):
If Isinstance (V, dict):
For _ck, _CV in _format_params (_pk=_k, Encode=encode, **v):
Yield _ck, _CV
Else
For I in V:
QV = I.encode (' utf-8 ') if isinstance (i, Unicode) else str (i)
_v = Encode (qv)
Yield _k, _v
Else
QV = str (v)
_v = Encode (qv)
Yield _k, _v


def encode_params (**kw):
"""
Do url-encode parameters

>>> encode_params (a=1, b= ' R & R ')
' a=1&b=r%26d '
>>> encode_params (a=u ' \u4e2d\u6587 ', b=[' a ', ' B ', 123])
' A=%e4%b8%ad%e6%96%87&b=a&b=b&b=123 '

>>> encode_params (**{
' A1 ': {' Aa1 ': 1, ' Aa2 ': {' Aaa1 ': One}},
' B1 ': [1, 2, 3, 4],
' C1 ': {' cc1 ': ' C ', ' CC2 ': [' Q ', 1, ' @ '], ' cc3 ': {' ccc1 ': [' s ', 2]}}
})
' a1[aa1]=1&a1[aa2][aaa1]=11&c1[cc1]=c&c1[cc3] [Ccc1]=s&c1[cc3][ccc1]=2&c1[cc2]=q&c1[cc2]=1&c1[cc2]=%40&b1=1&b1=2&b1=3&b1=4 '
"" "
# args = []
# for K, V in Kw.iteritems ():
# if Isinstance (V, basestring):
# QV = V.encode (' Utf-8 ' If Isinstance (V, Unicode) Else v
# args.append ('%s=%s '% (k, urllib.quote (QV)))
# elif Isinstance (V, collections . iterable):
# for I in V:
# qv = I.encode (' utf-8 ') if isinstance (i, Unicode) else str (i)
# args.append ('%s=%s ' % (k, urllib.quote (QV)))
# Else:
# qv = str (v)
# args.append ('%s=%s '% (k, urllib.quote (QV)))
# return ' &A MP; '. Join (args)

args = []
_urlencode = Kw.pop (' _urlencode ', urllib.quote)
For K, V in _format_params (_pk=none, Encode=_urlencode, **kw):
Args.append ('%s=%s '% (k, v))

args = sorted (args, Key=lambda s:s.split ("=") [0])
Return ' & '. Join (args)


def _read_body (obj):
Using_gzip = Obj.headers.get (' content-encoding ', ') = = ' gzip '
BODY = Obj.read ()
If Using_gzip:
Gzipper = gzip. Gzipfile (Fileobj=stringio (body))
Fcontent = Gzipper.read ()
Gzipper.close ()
Return fcontent
return body


Class Jsondict (Dict):
"""
General JSON object This allows attributes to is bound to and also behaves like a dict
"""

def __getattr__ (self, attr):
Try
return self[attr]
Except Keyerror:
Raise Attributeerror (R "' Jsondict ' object has no attribute '%s '"% attr)

def __setattr__ (self, attr, value):
SELF[ATTR] = value


def _parse_json (s):
"""
Parse str into jsondict
"""

def _obj_hook (Pairs):
"""
Convert JSON object to Python object
"""
o = Jsondict ()
For K, V in Pairs.iteritems ():
O[str (k)] = V
Return o
Return Json.loads (S, Object_hook=_obj_hook)


def _parse_xml (s):
"""
Parse str into XML
"""

Raise Notimplementederror ()


def _parse_html (s):
"""
Parse str into HTML
"""

Raise Notimplementederror ()


def _parse_text (s):
"""
Parse str into text
"""

Raise Notimplementederror ()


def _http_call (The_url, method, return_type= "JSON", Request_type=none, Request_suffix=none, headers={}, _timeout=30, * *kwargs):
"""
The_url: Request Address
Method Request Methods (Get,post)
Return_type: Return format parsing
Request_suffix: The suffix of the request address, such as Jsp,net
_timeout: Timeout period
Kwargs: Request Parameters
"""

Http_url = "%s.%s" (The_url, Request_suffix) if request_suffix else the_url

if Request_type = = ' json ':
headers[' content-type '] = ' Application/json '
# method = _http_post
# json_data = Json.dumps (Kwargs)
# # Convert str to bytes (ensure encoding is OK)
# params = Json_data.encode (' Utf-8 ')
params = Json.dumps (Kwargs)
Else
params = Encode_params (**kwargs)
Http_url = '%s?%s '% (Http_url, params) if method = = _http_get Else http_url
Print Http_url
# u = urlparse (Http_url)
# Headers.setdefault ("host", U.hostname)
Http_body = None if method = = _http_get Else params

req = Urllib2. Request (Http_url, Data=http_body, Headers=headers)

callback = Globals (). Get (' _parse_{0} '. Format (return_type))
If not hasattr (callback, ' __call__ '):
Print "Return '%s ' unable to resolve"% return_type
callback = _parse_json
Try

RESP = Urllib2.urlopen (req, timeout=_timeout if _timeout else timeout)
BODY = _read_body (RESP)
R = Callback (body)
# if Hasattr (R, ' Error_code '):
# Raise Apierror (R.error_code, R.get (' Error ', '), R.get (' request ', '))
Return r
Except Urllib2. Httperror, E:
Try
BODY = _read_body (e)
R = Callback (body)
Return r
Except
r = None
# if Hasattr (R, ' Error_code '):
# Raise Apierror (R.error_code, R.get (' Error ', '), R.get (' request ', '))
Raise E


Class Httpobject (object):

def __init__ (self, Client, method):
self.client = Client
Self.method = method

def __getattr__ (self, attr):

def wrap (**KW):
If attr:
The_url = '%s/%s '% (Self.client.api_url, attr.replace (' __ ', '/'))
Else
The_url = Self.client.api_url
Return _http_call (The_url, Self.method, **kw)
Return wrap

def __call__ (self, **kw):
Return _http_call (Self.client.api_url, Self.method, **kw)


Class Apiclient (object):
"""
How to use:
For example: API request Address: Http://api.open.zbjdev.com/kuaiyinserv/kuaiyin/billaddress
The request is in the following way: GET
The required parameters are: user_id uid of the user
Is_all whether to query all data, 0 is the default mailing address 1 for all mailing address
Access_token Platform Certification
The return data is: JSON

Then use the following at this time:
Domain = "api.open.zbjdev.com"
#如果是https请求, you need to set Is_https to True
Client = apiclient (domain)
data = {"user_id": "14035462", "Is_all": 1, "Access_token": "Xxxxxxxxxx"}
# if it is a POST request, change the Get method to the Post method
result = Client.kuaiyinserv.kuaiyin.billaddress.get (return_type= "JSON", **data)
#等同于
# result = Client.kuaiyinserv__kuaiyin__billaddress__get (return_type= "JSON", **data)
# result = Client.kuaiyinserv__kuaiyin__billaddress (return_type= "JSON", **data)
"""

def __init__ (self, domain, Is_https=false):

HTTP = "http"
If Domain.startswith ("http://") or Domain.startswith ("https://"):
HTTP, domain = Domain.split ("://")
# Else:
If Is_https:
HTTP = "https"

Self.api_url = ('%s://%s '% (http, domain)). Rstrip ("/")
Self.get = Httpobject (self, _http_get)
Self.post = Httpobject (self, _http_post)

def __getattr__ (self, attr):
If ' __ ' in attr:

method = Self.get
If attr[-6:] = = "__post":
attr = attr[:-6]
method = Self.post

Elif attr[-5:] = = "__get":
attr = attr[:-5]

If attr[:2] = = ' __ ':
attr = attr[2:]
Return GetAttr (method, attr)
Return _callable (self, attr)


Class _executable (object):

def __init__ (self, client, method, path):
self._client = Client
Self._method = method
Self._path = Path

def __call__ (self, **kw):
method = _method_map[self._method]
Return _http_call ('%s/%s '% (Self._client.api_url, Self._path), method, **kw)

def __str__ (self):
Return ' _executable (%s%s) '% (Self._method, Self._path)

__repr__ = __str__


Class _callable (object):

def __init__ (self, client, name):
self._client = Client
Self._name = Name

def __getattr__ (self, attr):
if attr = = ' Get ':
Return _executable (self._client, ' GET ', self._name)
if attr = = ' Post ':
Return _executable (self._client, ' POST ', self._name)
name = '%s/%s '% (Self._name, attr)
Return _callable (self._client, name)

def __str__ (self):
Return ' _callable (%s) '% Self._name

__repr__ = __str__


Def test_logistics ():

Domain = "Https://api.kuaidi100.com/api"

#如果是https请求, you need to set Is_https to True
Client = apiclient (domain)

Data = {"id": "45F2D1F2SDS", "com": "Yunda", "Nu": "1500066330925"}
result = Client.__get (_timeout=2, **data)
Print result
Print result["message"]
Print Result.get ("message")
Print Result.message


if __name__ = = ' __main__ ':


# test_logistics ()

data = {
"Data": {
"id": 1,
"pid": 3,
"Name": "U ' in the Aston '
},
"Sign": ' Asdfdsdsfsdf ',
}

Domain = "kuaiyin.zhubajie.com"

Client = apiclient (domain)
# headers = {' Content-type ': ' Application/json '}
headers = {"host": Domain}

result = Client.api.zhubajie.fz.info.post (return_type= "JSON", request_type= "json", Headers=headers, **data)
Print result
Print result[' data ' [' msg ']

c = apiclient (' task.6.zbj.cn ')
R = GetAttr (C.api, ' Kuaiyin-action-delcache '). Post (request_type= "JSON",
headers={},
**{"sign": "",
"Data": {
"Product": "PVC",
"Category": "Card",
"Req_type": "Pack_list"
}})
Print R
Print r[' data ' [' msg ']

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.