Python magic and remote APIs
Python
magic and remote APIs
I'm a big attractive fan of Python as a programming
language. It lets in me to the application by means of discovery, that is, poke
and prod at things till they work. Not having to bring together a whole
application every time I exchange something is quite tremendous, as is the
capability to insert a debug statement and be able to break a program at that
point, then run arbitrary python code inside that context. Pretty vital to how
I write software programs. techbizcenter
Another factor I like approximately Python, which a few may
not, is the potential to do magical things. Not fairly so magic as a kid would
like us to trust. However, laugh stuff certainly.
Lately, one of the facilities at work grew a JSON API to
bang towards, and for fun, I notion I'd whip up a few Python to play with it.
My team had a few application scripts that would bang on the vintage XML-RPC
interface to get some information, and I wanted to look at how a great deal
quicker it becomes with JSON.
First, when you have to do something internet stuff, you truly
must be the use the Requests module. It is so, so much better than the use of
urllib(2) without delay.
The API I desired to program against had an Auth stop point
that might go back to you a token string. This string may be included with
later API calls to provide authentication. Requests let you create a session
item that can have attributes that carry on to all net calls, inclusive of a
custom auth header with a token.
resp =
requests.get('https://URL/api/auth/USERNAME?password=DATA')
resp.json()
u'LONGSTRING'
token =
resp.json()
session =
requests.Session()
session. headers.update({'X-Auth':
token})
Now the session object may be used similar to requests
itself, and it'll encompass the brand new header we've delivered. While this
was neat at the beginning, I fast realized that I desired to make this
consultation item a characteristic of a more popular item for working with the
API. Each time you use consultation or requests, you need to fill in a URL, and
that's tedious, so I made a python elegance to address that for me. One bit of
magic I used here was a python asset.
Python belonging is a way to populate a class attribute at
the fly / as needed without the code using your object needing to recognize
that it's happening behind the curtain. It's a getter/setter without having to
get and set, and it caches the cost for future getting. My elegance sets a few
facts for the duration of the init system and creates a belonging for the
session attribute, which can then be utilized in later capabilities, like a
login or question feature.
Class CServ(object): tipsfromcomputertechs
"A service
item that we can engage with."""
def
__init__(self):
self.API =
'URL'
self.SessURL = self.API + 'consultation/'
self.QAPI
= self.API + 'question/'
self._session = None
def
_login(self):
username =
myuser
password =
mypass
data =
'password': password
r =
requests.Get('%sauth/%s' % (self.API, username), params=data)
return
r.Json()
@belongings
def
session(self):
if not
self._session:
self._auth()
go back
self._session
def
_auth(self):
token =
self._login()
# Build up
a consultation item with the token
s =
requests.Session()
s.Headers.Update('X-Auth': token)
self._session = s
def
query(self, classname, load_arg, attributes=None):
"""Wrangle a question into the JSON interface.
Classname
-- The call of the cserv API elegance to query against
load_arg
-- The argument to query for (can be a list)
attributes
-- an optional listing of what to return
returns
jsonified effects
"""
# See if
we've got a list of load args to undergo
if
type(load_arg) == list:
#
Build up a dict of the bits we want to bypass in
bits =
[]
for
arg in load_arg:
qdict = 'elegance': classname, 'load_arg': arg
if
attributes:
qdict['attributes'] = attributes
bits.Append(qdict)
else:
bits =
'class': classname, 'load_arg': load_arg
if
attributes:
bits['attributes'] = attributes
information = self.Consultation.Put up(self.QAPI, JSON.Dumps(bits))
go back
information.Json()
With this shape, we are able to do such things as:
cv = CServ()
cserv.Query('Computer.Computer', 432807, attributes=['name'])
[u'remember': 1,
u'load_arg': 432807, u'restriction': 1, u'result':
[u'name':
u'silly.Hostname.Here.Com'], u'offset': 0,
u'elegance':
u'Computer. Computer']
We get again a JSON blob that has the API again to us. What
befell turned into that the query characteristic constructed up the information
for the bit of the request, which becomes exceeded into
self.Consultation.Publish(). Since this turned into the first time trying to
get entry to myself. During the session, we went via the @belongings tagged
session() characteristic. That feature decided that self._session become not populated
yet and referred to as _auth(). _auth() in flip did the login dance to generate
the token, constructed up a request. Session object tweaked the header and
stuffed it into self._session. Session() then lower back that to the caller,
consequently handing over the real session object. Magic! The next time session
is accessed, it's going to quickly return the value of self._session.
Properties are wonderful and useful.
A CServ() object is okay, but now not beneficial on its
personal. If I wanted to get a bit of information about a computer and use that
fact numerous times, I'd both need to save a copy of the statistics in a
neighborhood variable or do queries every time I desired the records. Neither
are green. What I really need is so one can create a Computer item, and from
that object get entry to attributes immediately, like say Computer. Name. Here
is in which some greater magic is available. We already realize we can create
houses with lower back attributes. We should go discover what all feasible things
we should look up approximately a computer in our CServ service, then write out
houses for each of these. That… doesn't sound fun. Particularly in case you
reflect on consideration on this CServ having Computer items, Switch gadgets,
Account objects, etc.… That would be lots of typing!
What if, instead, there was a way to do dynamic properties?
What if whilst we tried to get admission to Computer.Primary_ip, the code might
simply recognize to do a question to look up the primary_ip characteristic of a
Computer. Computer cserv API elegance? Well, we're in good fortune, due to the
fact there's a manner!
First, we're going to create a subclass of CServ, CServOBJ.
This magnificence could be a base magnificence for any wide variety of objects,
like Computers, Accounts, and so forth... We can store a whole lot of code
duplication with the aid of setting the shared bits in CServOBJ.
Magnificence
CServOBJ(CServ):
"""A base CServ object elegance to build
from"""
Right now, we don't want to overload the __init__ method, so
we will dive properly into the magic. In Python, while you attempt to get entry
to an item's characteristic, behind the scenes, an object's
__getattr__(attribute) technique is referred to as. Normally you don't see it
because it's all built-in, but we can override it to make attribute access do
something unique. In our case, we need to do an API appearance as much as getting
the cost if we don't already have it, so we'll overload the characteristic:
def
__getattr__(self, call):
attempt:
return
self.__dict__[name]
besides
KeyError:
self._setAttrib(name)
return
self.__dict__[name]
def
_setAttrib(self, call):
resp =
self.Session.Get('%sattribute/%s/%s/%s' %
(self.API,
self._qclass, self._qval, name))
resp.Raise_for_status()
maintains song of all the attributes. Our simple little bit
of code will attempt to go back to the cost for the call of the attribute the
function receives. If that attribute doesn't exist inside the constructed indict,
a key error will manifest. We trap that mistakes and get in touch with our
_setAttrib() function. This function is wherein the lookup is built up using
some other class attributes we'll get to later. A consultation name is made,
and the value is fed into the setattr Python integrated. All these paintings
happen behind the curtain to the bit of code just seeking to get admission to
the attribute, and the lookup most effective takes place as soon as. That's all
we really want for now inside the base magnificence, shall we create a Computer
magnificence.
Elegance
Computer(CServOBJ):
"""A class to represent the Computer.Computer CServ API
class"""
_qclass =
'Computer.Computer'
def
__init__(self, wide variety):
self.Quantity = range
self._qval
= self.Number
, it does no longer change in step with-item. It is the
magnificence call surpassed into the far-flung API. The object introduction
takes a variety of, that is, the identifier for computers in our gadget. It
assigns that to the range attribute so that if we reference the laptop. Number
we don't make another API call. _qval is the vicinity holder so as to be
commonplace across all of the gadgets for what to use as a lookup key. The
parent elegance's init known as (which skips all of the manners as much as
CServ) to complete the item introduction.
With this setup, we are able to program against it very
without difficulty to get right of entry to and cache records:
comp = Computer(432888)
print(comp.Quantity)
432888
These environments provide final tab touch, assist
functions, etc.… With our modern code although, we couldn't tab the available
attributes entirely. Only the name characteristic and the features we've
created could show up. To fix that, we want to overload the constructed in
__dir__ feature. This characteristic is used while getting a listing of what is
available to an object, dir(item). A useful exploratory device. Ipython/python
use this technique to peer what tab finishing touch options to offer you.
Luckily our internal service presents an API call to get a listing of possible
attributes, so we are able to hook that into __dir__. But of course, we
handiest want to do this API call as soon as (according to object), so we are
able to need to make it a property. Since there is nothing API elegance precise,
we can put the code into the CServOBJ elegance:
def
__init__(self):
self._attributes = None
excellent(CServOBJ, self).__init__()
@property
def
attribs(self):
if now not
self._attribs:
self._attribs = []
resp =
self.Session.Get('%sattributes/%s' %
(self.API, self._qclass))
for
att in resp.Json():
self._attribs.Append(att[0])
go back
self._attribs
def
__dir__(self):
return
taken care of(dir(type(self)) + listing(self.__dict__) + self.Attribs)
Since we're creating a property at this stage, we are able
to grow an __init__ function to prep for that. Then we outline the attributes()
characteristic. A brief-cut is taken right here; instead of calling out to some
different characteristic to load the attributes, the burden is accomplished at
once. Any time a Computer item receives a dir() name, our overloaded feature
will return a taken care of a listing. This is the combination of the
constructed-in capabilities/attributes, anything that has been added to the
specific object, and then to be had API attributes. Tab-finishing touch
achieved!
This has been a quick investigation of a number of the magic
you can do with Python. It's not pretty antigravity. However, it is beneficial
and meals for notion for every person that's programming against far off APIs.
Objects are suitable, items with dynamic attributes are higher, and the final
tab touch is the icing on the cake. Enjoy!
READ MORE ABOUT TECHNOLOGY ENTHUSIASTS @ webtechradar
928betเว็บพนันออนไลน์อันดับ 1 แทงบอลสด เกมสล็อตยอดนิยม
ReplyDeletehttps://betflixs.net BETFLIK เว็บพนันออนไลน์ รูปแบบใหม่ ฝาก-ถอน ไม่ต้องแจ้งสลิป สามารถถอนเงินออได้ตลอดทั้งวัน-ทั้งคืน ไม่จำกัดยอดเงินในการถอน ฝากเงิน 1 บาทก็ฝากได้ ทุกรายการถอนเงินของคุณไม่มีการหักค่าทำเนียม หรือค่าบริการใดๆทั้งสิ้นตลอดชีพ
ReplyDeleteThanks For sharing this Superb article. it is valuable For me Great Work. I ought to be compose greater remark on this incredible point. 스포츠토토
ReplyDeleteI am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that’s at the other blogs. 파워볼
ReplyDeleteThis is the best article for reading and gets important information, reading the article is my hobby, but I really like read your article, amazing article thank you very much!! 토토사이트
ReplyDeleteI’m very pleased to discover this site. I want to to thank you for ones time for this particularly Wonderful read.. and Wonderful website. 룰렛사이트탑
ReplyDeleteThis is a great post and enjoy the look of your blog very much. Thanks for sharing 토토
ReplyDeleteHi! this is often nice article you shared with great information. Thanks for giving such an exquisite informative information.
ReplyDelete먹튀검증
온라인경마
카지노사이트
토토
I think the admin of this website is truly working hard in support of his
ReplyDeleteweb page, because here every stuff is quality based data.
메이저사이트
온라인경마
카지노
토토
Thank you for sharing! Feel free to visit my website; 카지노사이트
ReplyDeleteThanks for sharing this valuable information for free Feel free to visit my website; 카지노사이트
ReplyDeleteNie pożałujesz porzucenia starego sposobu robienia rzeczy, gdy zobaczysz, o ile lepsze są wiaty na śmietniki pod każdym względem od producenta CoSteel! Dzięki wysokiej jakości konstrukcji, trwałości i stylowemu wyglądowi, który nie zakłóca Twojej przestrzeni, jest idealnym rozwiązaniem dla wszystkich Twoich potrzeb. Dostosowane do Twoich unikalnych potrzeb, te zadaszenia to prawdziwa inwestycja, która przetrwa lata.
ReplyDeleteThe info you provide on this site has helped me greatly. Thanks
ReplyDelete바카라사이트
카지노사이트
온라인카지노
바카라사이트닷컴
Appreciate you for sharing this blog. A must read post here.
ReplyDelete온라인카지노
바카라사이트
카지노사이트
온라인카지노
You’re doing a great job, keep it up doing a great work like this one.
ReplyDelete카지노사이트
What an awesome post, I just read it from start to end your blog post. Really an informative blog. 먹튀검증
ReplyDelete
ReplyDeleteThanks For Sharing Such An Excellent Post Enjoyed Reading it.
0
카지노
카지노
I really like you You have knowledge that can be given to me. 바카라사이트
ReplyDelete0
Pretty! This was a really wonderful post. Thank you for your provided information.
ReplyDelete토토
I blog often and I seriously appreciate your information. Your article has really peaked my interest.
ReplyDelete스포츠토토
"Daebak precisely what I was looking for, appreciate it for putting up. Kindly check the following link below Thank you in advance.
ReplyDelete스포츠 사다리게임 토토사다리타기 배당사이트
Way cool! Some very valid points! I appreciate you penning this article plus the rest of the site is very good. Kindly visit my website and learn more about casino & sports betting
ReplyDelete스페셜토토 스포츠TOTO 스포츠배팅게임 와이즈토토추천
THIS BLOG THAT YOU POSTED IS VERY FINE ARTICLE, AND WE ARE *-*-*-*-*-*-* WAITING FOR YOUR NEXT ARTICLE, THANKS
ReplyDeleteI LOVE THIS ARTICLE AND I WILL TELL TO OTHERS THAT THIS GOOD. THANKS */-*/-*/-*/-*/-*/-*/-*/-*/-*/-*/-
ReplyDeleteTHIS WEBSITE IS REALLY COOL AND SO MAY INSPIRING ARTICLE. /*/*/*/*/*/*/*/ THANKS FOR THIS!
ReplyDeleteI REALLY APPRECIATING THE PERSISTENCE THAT YOU PUT INTO +-+-+-+-+-+-+-+ YOUR BLOG, THIS IS REALLY GREAT!
ReplyDeleteAs a Python developer, you’re about to embark on a journey into the fascinating world of magic methods (also known as dunder methods). These special methods are like hidden gems within Python classes, allowing you to customize the behavior of your objects in powerful and intuitive ways.
ReplyDeletedui lawyer stafford va
Python Magic refers to Python's magic methods, which allow developers to define or customize object and operator behavior. These methods are crucial for making Python classes more powerful and flexible. Combining Python magic with remote APIs involves using magic methods with API responses, automating API interactions, and advanced data handling. These methods can be used to parse JSON data, automate API interactions, and simplify data handling. Understanding how to implement magic methods in Python code can help with specific projects or use cases criminal defense lawyer loudoun county.
ReplyDeletePython Magic and Remote APIs are often used together to automate tasks, enhance workflows, and interact with remote servers and services. Python Magic is associated with "magic methods" that enable Python objects to behave in specific ways and allow deeper customization. These methods include initializing attributes, defining string representations, and customizing object interactions. Python Magic libraries include IPython's Magic Commands and the Python-Magic library. Remote APIs allow Python programs to interact with external systems over a network, and Python provides multiple libraries to handle remote API calls and responses effectively. These libraries include the requests library for making HTTP requests, handling RESTful APIs, and API client libraries like boto3 for AWS services, Google-api-python-client for Google services, and specialized Python libraries like Twilio, Slack API, and Stripe for specific services What are The Laws for Divorce in New York.
ReplyDeleteThanks For sharing this Superb article.Face Toner
ReplyDelete