如何将所有参数都放入webapp2中的数据结构(list / dict / etc)中

时间:2015-09-24 20:12:59

标签: python request webapp2

我正在编写一个简单的webapp2脚本,它接受传递给它的参数并吐出结果。最终我想将这些参数传递给特定的函数,具体取决于正在进行的请求类型。

代码:

class partyHandler(webapp2.RequestHandler):
    def get(self, requestType):
        PROCESS = partyRequests();
        self.response.headers['Content-Type'] = 'text/plain'

    #Here's where I would normally request the paramters,
    #There's too many to list
    #EX:
    # name = cgi.escape(self.request.get('name'))
    #
    options = {
        'create':   PROCESS.createParty,
        'retrieve': PROCESS.retrieveParty,
        'update':   PROCESS.updateParty,
        'delete':   PROCESS.deleteParty,
        'join':     PROCESS.joinParty,
        'broadcast':PROCESS.broadcastParty,
        'leave':    PROCESS.leaveParty,
    }
    #THE PARAMETERS WOULD BE PASSED TO ANY FUNCTION ABOVE DEPENDING ON requestType.
    return self.response.write(options[requestType](<PARAMS>))

app = webapp2.WSGIApplication([
('/party/(create|retrieve|update|delete|broadcast|join|leave)/', partyHandler)
], debug=True)

正如您所看到的,不是每次对脚本发出请求时都不需要对参数值进行冗余请求,是否有办法将所有参数收集到数据结构(列表/字典)中并传递那个功能?

修改

澄清一下,我的意思是 函数创建需要参数:

name
partyImg
latitudeRestaurant
longitudeRestaurant
address

函数检索需要参数:

partyId

我之前的做法是这样做:

#IF I'M CALLING retrieve, THESE ARE POINTLESS
name = cgi.escape(self.request.get('name'))
partyImg = cgi.escape(self.request.get('partyImg'))
latitudeRestaurant = cgi.escape(self.request.get('latitudeRestaurant'))
longitudeRestaurant = cgi.escape(self.request.get('longitudeRestaurant'))
address = cgi.escape(self.request.get('address'))

#IF I'M CALLING create, THESE ARE POINTLESS
partyId = cgi.escape(self.request.get('partyId'))


options = {
    'create':   PROCESS.createParty(name, partyImg,latitudeRestaurant,longitudeRestaurant,address),
    'retrieve': PROCESS.retrieveParty(partyId)
}

我不想请求单个参数,而是将所有参数放入数据结构并将其传递给函数。

2 个答案:

答案 0 :(得分:1)

我相信你正在寻找* args和** kwargs。

以下是有关它的信息: What does ** (double star) and * (star) do for parameters?

最终,对于args和kwargs,他们采用任意参数集合,并根据他们传递给谁,你可以在该方法内验证你期望的参数。

因此,例如,对于您的一种方法,例如创建,你想要参数x和y,然后你的创建可能如下所示:

def create(*args, **kwargs):
 ## check for parameters x and y is available in kwargs here and proceed

答案 1 :(得分:0)

查看webapp2文档中的请求,我发现这有效:

#!/usr/bin/env bash

调用这些方法时,它看起来像这样:

class partyHandler(webapp2.RequestHandler):
    def get(self, requestType):
        PROCESS = partyRequests();
        self.response.headers['Content-Type'] = 'text/plain'

    options = {
        'create':   PROCESS.createParty,
        'retrieve': PROCESS.retrieveParty,
        'update':   PROCESS.updateParty,
        'delete':   PROCESS.deleteParty,
        'join':     PROCESS.joinParty,
        'broadcast':PROCESS.broadcastParty,
        'leave':    PROCESS.leaveParty
    }
    self.response.write(options[requestType](self.request.GET)) <--THIS WORKS