Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

supplying variables to class dynamically

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?

like image 632
shantanuo Avatar asked May 19 '15 05:05

shantanuo


1 Answers

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):
like image 158
14 revs, 12 users 16% Avatar answered Oct 16 '22 18:10

14 revs, 12 users 16%