PyHole
proxy object API¶
Constructing proxy object¶
Using PyHole requires instantiating of proxy object. Proxy object is represented by PyHole class.
Building paths¶
- API URL can be easily build using object notation and PyHole proxy object with:
- getting attribute –
proxy.some.path
, - getting item (dict style) –
proxy['some']['path']
, - call –
proxy('some', 'path')
.
- getting attribute –
Tree different approaches can be used for creating path with proxy object:
By attribute get¶
Getting an attribute from proxy object, will return proxy clone with attribute appended to a path list.
- Example:
>>> from pyhole import PyHole >>> proxy = PyHole('http://domain.ltd/rest_api') >>> proxy.one http://domain.ltd/rest_api/one >>> proxy.one.two http://domain.ltd/rest_api/one/two >>> proxy.one.two.three http://domain.ltd/rest_api/one/two/three
By item get¶
Getting an item from proxy object in dict similar way will also append the key as a path bit.
>>> from pyhole import PyHole
>>> proxy = PyHole('http://domain.ltd/rest_api')
>>> proxy['one']
http://domain.ltd/rest_api/one
>>> proxy['one']['two']
http://domain.ltd/rest_api/one/two
Notice that numbers can be also used this way:
>>> proxy['one']['two'][3]
http://domain.ltd/rest_api/one/two/3
Warning
Slicing is not supported – proxy[1:4]
.
and also variables values:
>>> three="third"
>>> proxy['one']['two'][three]
http://domain.ltd/rest_api/one/two/third
Note
For creating a path to e.g. search.php
because of dot sign you will also need to use this method:
>>> proxy.one['search.php']
http://domain.ltd/rest_api/one/search.php
By call¶
Calling proxy object with unnamed urguments also appends a path list:
>>> proxy('one')
http://domain.ltd/rest_api/one
>>> proxy('one', 'two')
http://domain.ltd/rest_api/one/two
>>> proxy('one', 'two')('three')
http://domain.ltd/rest_api/one/two/three
Adding query string¶
To add parameters to HTTP request call proxy object with named argument:
>>> proxy(param1="one")
http://domain.ltd/rest_api?param1=one
>>> proxy(param1="one", param2="two")
http://domain.ltd/rest_api?param2=two¶m1=one
Note
Named arguments cannot have names reserved for python syntax keywords, e.g. class
. Following
example throws SyntaxError
exception
>>> proxy(class=12)
File "<stdin>", line 1
proxy(class=12)
^
SyntaxError: invalid syntax
To avoid clashing with syntax keywords a dict can be given as an unnamed argument for call:
>>> proxy({'class':12})
http://domain.ltd/rest_api?class=12
>>> proxy({'class':12, 'param1':'one' }, param2='two')
http://domain.ltd/rest_api?param2=two¶m1=one&class=12
Parameters can be also declared in chain:
>>> proxy.one(p1='v2').two({'p2':'v2'}).tree({'p3':'v3'})
http://domain.ltd/rest_api/one/two/tree?p2=v2&p3=v3&p1=v2