Python:使用反射来获取Web服务方法

时间:2017-01-24 07:16:16

标签: python web-services reflection

美好的一天! 我试图使用反射来进行Web服务的方法。以下是代码示例:

...

api = cf.SomeServiceAPI()

#Test1
def test_SomeMethod(self):
   result = self.sender('SomeMethod', [setofvalue])
   self.assertEqual(result, "Success", msg=result)

def sender(self, methodname, setofvalue):
   result = self.api.service.SomeMethod(setofvalue)
   return result

请帮助我了解如何使用方法名称应用该方法? 谢谢!

3 个答案:

答案 0 :(得分:0)

看起来这是this问题的重复。

您应该使用:

getattr(object, 'method_name')

答案 1 :(得分:0)

您可以使用getattr(clazzA, methodname)(setofvalue)其中clazzA是对象,methodname是字符串中方法的名称,setofvalue是您要传递给方法的参数。

以下是您请求的行为的示例:

class A:
  def some_method(self, arg):
    print ("in: ", arg)

#Test1
def test_Some_method():
   result = sender('some_method', "method")

def sender(methodname, setofvalue):
   clazzA = A()
   result = getattr(clazzA, methodname)(setofvalue)
   return result

test_Some_method()

>>>'in:  method'

答案 2 :(得分:0)

我解决了这个任务。

import sqlalchemy
from sqlalchemy.sql.expression import bindparam
from sqlalchemy.types import String
from sqlalchemy.dialects.postgresql import ARRAY

DB_URI = '...'
engine = sqlalchemy.create_engine(DB_URI)

sql = text("SELECT * FROM some_table WHERE userid = :userid").bindparams(bindparam("userid", String))
res = engine.execute(sql, userid=12345)

# in particular this bit is useful when you have a list of ids
sql = text("SELECT * FROM some_table WHERE userids = :userids").bindparams(bindparam("userids", ARRAY(String)))
res = engine.execute(sql, userids=[12345, 12346, 12347])