I have tried the example provided by official tutorial found here:
http://saratoga.readthedocs.org/en/latest/serviceclasses.html
I have made a few changes to the code and this is how it looks like:
http://23.21.167.60:8094/v1/yearlength?name=earth
My problem is that I need to provide the account=211829 in the URL just like name=earth.
What I have written below is working because I have supplied the account number to the class. How do I do this dynamically?
import json
from saratoga.api import SaratogaAPI, DefaultServiceClass
class PlanetServiceClass(DefaultServiceClass):
def __init__(self, myaccount):
self.yearLength = {
"earth": self.myquery(myaccount),
"pluto": {"seconds": 7816176000}
}
def myquery(self, myaccount):
import pandas as pd
query = ('select * from mydata198 where account = %s ') % (myaccount)
import sqlalchemy
engine = sqlalchemy.create_engine('mysql+pymysql://dba:[email protected]/test')
conn = engine.raw_connection()
df=pd.read_sql(query, conn)
return df.to_json()
class PlanetAPI(object):
class v1(object):
def yearlength_GET(self, request, params):
planetName = params["params"]["name"].lower()
return self.yearLength.get(planetName)
APIDescription = json.load(open("planets.json"))
myAPI = SaratogaAPI(PlanetAPI, APIDescription, serviceClass=PlanetServiceClass('211829'))
myAPI.run(port=8094)
How do I pass the account_num
variable from PlanetAPI
class to PlanetServiceClass
?
You would need to change your url to
http://23.21.167.60:8094/v1/yearlength?name=earth&account_num=12345
Then in the code you can access it via
account_num = params["params"]["account_num"]
EDIT:
The problem is that you are currently using account_num
to initialize the server before it is running. So you need to pass it in after it is running.
class PlanetAPI(object):
class v1(object):
def yearlength_GET(self, request, params):
planetName = params["params"]["name"].lower()
account_num = params["params"]["account_num"]
mysql_result_json = self.myquery(account_num)
self.yearLength['earth'] = mysql_result_json # assign to earth if you want, as in your question
return self.yearLength.get(planetName)
then change the rest of the code back to what it was in the tutorial:
myAPI = SaratogaAPI(PlanetAPI, APIDescription, serviceClass=PlanetServiceClass())
and
class PlanetServiceClass(DefaultServiceClass):
def __init__(self):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With