我试过这里的官方教程提供的例子:
http://saratoga.readthedocs.org/en/latest/serviceclasses.html
我对代码做了一些更改,这就是它的样子:
http://23.21.167.60:8094/v1/yearlength?name=earth
Run Code Online (Sandbox Code Playgroud)
我的问题是我需要在URL中提供account = 211829,就像name = earth一样.
我在下面写的是工作,因为我已经为班级提供了帐号.我该如何动态执行此操作?
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:pass@1.2.3.4/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)
Run Code Online (Sandbox Code Playgroud)
如何将account_num变量从PlanetAPI类传递给PlanetServiceClass?
您需要将您的网址更改为
http://23.21.167.60:8094/v1/yearlength?name=earth&account_num=12345
Run Code Online (Sandbox Code Playgroud)
然后在代码中您可以通过以下方式访问它
account_num = params["params"]["account_num"]
Run Code Online (Sandbox Code Playgroud)
编辑:
问题是您当前正在使用在account_num服务器运行之前对其进行初始化。所以运行后需要传入。
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)
Run Code Online (Sandbox Code Playgroud)
然后将其余代码更改回教程中的内容:
myAPI = SaratogaAPI(PlanetAPI, APIDescription, serviceClass=PlanetServiceClass())
Run Code Online (Sandbox Code Playgroud)
和
class PlanetServiceClass(DefaultServiceClass):
def __init__(self):
Run Code Online (Sandbox Code Playgroud)