2013-02-06 24 views
2

我有一個金字塔的Web服務和代碼示例如下:金字塔路線匹配和查詢參數

查看聲明:

@view_config(route_name="services/Prices/GetByTicker/") 
def GET(request): 
    ticker = request.GET('ticker') 
    startDate = request.GET('startDate') 
    endDate = request.GET('endDate') 
    period = request.GET('period') 

路由:

config.add_route('services/Prices/GetByTicker/', 'services/Prices/GetByTicker/{ticker}/{startDate}/{endDate}/{period}') 

現在我知道這都搞砸了,但我不知道金字塔的慣例是什麼。目前這個工作原理是因爲請求被成功路由到視圖,但是我得到一個「Dictionary object not callable」異常。

的URL看起來可怕:

@根/服務/價格/ GetByTicker /股票= APPL /的startDate = 19981212 /結束日期= 20121231 /週期= d

理想情況下,我想能夠使用一個URL是這樣的:?

@根/服務/價格/ GetByTicker /股票= APPL &的startDate = 19981212 &結束日期= 20121231 &週期= d

任何金字塔BODS出日是否願意花五分鐘解釋我做錯了什麼?

回答

11

從你的示例代碼,我想你使用URL Dispatch

所以它應該是這樣的

config.add_route('services/Prices/GetByTicker/', 'services/Prices/GetByTicker/') 

那麼URL,如:
@根/服務/價格/ GetByTicker /股票? = APPL &的startDate = 19981212 &結束日期= 20121231 &週期= d
將匹配它

- 編輯 -
你沒有使用名稱,如 「服務/價格/ GetByTicker」 爲ROUTE_NAME,你可以得到的GET PARAMS使用request.params['key']
查看聲明:

@view_config(route_name="services_Prices_GetByTicker") 
def services_Prices_GetByTicker(request): 
    ticker = request.params['ticker'] 
    startDate = request.params['startDate'] 
    endDate = request.params['endDate'] 
    period = request.params['period'] 

路由:

config.add_route('services_Prices_GetByTicker', 'services/Prices/GetByTicker/') 
+0

謝謝。正是我在找的東西。它始終是你從文檔中找不到的簡單答案... –

5

將查詢字符串轉換爲request.GET字典。您正在使用括號來調用字典,而不是通過括號訪問項目。對於這樣的URL

@根/服務/價格/ GetByTicker /?股票= APPL &的startDate = 19981212 &結束日期= 20121231 &週期= d

request.GET['ticker'] # -> 'APPL' or an exception if not available 
request.GET.get('ticker') # -> 'APPL' or None if not available 
request.GET.get('ticker', 'foo') # -> 'APPL' or 'foo' if not available 
request.GET.getall('ticker') # -> ['APPL'] or [] if not available 

最後一個選項是非常有用如果您希望ticker多次提供。

request.paramsrequest.GETrequest.POST的組合,其中後者是表示請求在窗體上傳中的正文的字典。

無論如何,答案是request.GET('ticker')在句法上不是我提到的選項之一,停止這樣做。 :-)

+0

是的,越來越多...... ;-p –

+0

我最初被我發現的一些示例代碼誤導了。提醒永遠不要走這條路。 關於多重股票的問題。如何形成這樣的要求? 你會通過ticker = AAPL&ticker = MSFT嗎? 或ticker = [AAPL,MSFT] –

+0

'ticker = AAPL&ticker = MSFT' –