I have a web-app and initially I used feedparser to pull data from my blog. Now I thought to use Google API for extending various other features.
As I didn’t want to break my old code and want to add the new API as an additional add-on type thing, I thought to setup a structure very similar to BeautifulSoup where it provides a choice to select an HTML/ XML parser depending upon the situation
BeautifulSoup(markup, "html.parser")
BeautifulSoup(markup, "lxml")
# They still support the same methods mentioned in the documentation.
This is what I did:
from apis import api1, api2
from dev_user import my_api_choice
select = { "api1" : api1, "api2": api2 }
obj = pservice (select["my_api_choice"] )
obj.method1()
# invokes method1 of the inherited class.
pservice is very close to wrap-up class. I initially thought to write it because I could have a chance to use Google API in it.
I even made sure that api2 (which provides Google API functionality) provides same kind of methods as that of api1 (even their method names are same).
So, is this a good way to do it? or else, how can I possibly do it in the other way..
You may create an
abstract classAPIwith someabstractmethod likefetchorpullandinheritit and build concrete implementations under classes likeAPI1/API2/ etc…For example implementation of
fetchfunction for Google API would be done forHTMLand same wayfetchfunction forfeedparserwould be implemented usingXML…Now based on your requirement or current configuration or whatever input; make a decision which
APIyou want to use and createdynamic instancefor the same, now as method names would be same in all classes you just need to fire appropriatefunctionfor thatinstanceand you’re done.Further more, afterwards you can introduce
API3and update your configuration – to use API3 class instance as anothercontentprovider.