[英]kwargs sent over pyAMF channel
我正在使用Cherrypy服務器通過pyAMF通道從python客戶端接收請求。 我從下面的模擬開始,並且工作正常:
服務器:
import cherrypy
from pyamf.remoting.gateway.wsgi import WSGIGateway
def echo(*args, **kwargs):
return (args, kwargs)
class Root(object):
def index(self):
return "running"
index.exposed = True
services = {
'myService.echo': echo,
}
gateway = WSGIGateway(services, debug=True)
cherrypy.tree.graft(gateway, "/gateway/")
cherrypy.quickstart(Root())
客戶:
from pyamf.remoting.client import RemotingService
path = 'http://localhost:8080/gateway/'
gw = RemotingService(path)
service = gw.getService('myService')
print service.echo('one=1, two=3')
結果: [[u'one = 1,兩個= 3'],{}]
現在,如果不是:
def echo(*args, **kwargs):
return (args, kwargs)
我用:
def echo(**kwargs):
return kwargs
並發送相同的請求,出現以下錯誤:
TypeError:echo()正好接受0個參數(給定1個)
同時:
>>> def f(**kwargs): return kwargs
...
>>> f(one=1, two=3)
{'two': 3, 'one': 1}
>>>
問題:為什么會這樣? 請分享見解
我正在使用:python 2.5.2,cherrypy 3.1.2,pyamf 0.5.1
請注意,使用第一個echo函數,獲得結果的唯一方法是按以下方式調用它:
echo(u"one=1, two=3")
# in words: one unicode string literal, as a positional arg
# *very* different from:
echo(one=1, two=3) # which seems to be what you expect
因此,您必須編寫echo來接受位置參數或更改其調用方式。
缺省情況下,WSGIGateway設置expose_request=True
,這意味着WSGI環境dict被設置為該網關中任何服務方法的第一個參數。
這意味着回聲應寫為:
def echo(environ, *args):
return args
PyAMF提供了一個裝飾器,該裝飾器允許您強制暴露請求,即使expose_request=False
,例如:
from pyamf.remoting.gateway import expose_request
from pyamf.remoting.gateway.wsgi import WSGIGateway
@expose_request
def some_service_method(request, *args):
return ['some', 'thing']
services = {
'a_service_method': some_service_method
}
gw = WSGIGateway(services, expose_request=False)
希望可以弄清楚為什么在這種情況下會出現TypeError
。
您正確地指出,您不能直接在PyAMF客戶端/服務器調用中提供** kwarg,但是您可以使用默認的命名參數:
def update(obj, force=False):
pass
然后,您可以訪問該服務:
from pyamf.remoting.client import RemotingService
path = 'http://localhost:8080/gateway/'
gw = RemotingService(path)
service = gw.getService('myService')
print service.update('foo', True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.