2017-09-24 52 views
0

我正在嘗試一個web2py應用here,我收到錯誤消息。我在StackOverFlow和其他Web資源上嘗試了多種解決方案,但無法使其工作。我知道這是列表中的問題,但是指向正確的方向很有幫助。然而,我嘗試了幾個解決方案,沒有爲我工作。Web2py錯誤:<type'exceptions.IndexError'>列表索引超出範圍

CODE:

def __edit_survey(): 
    surveys=db(db.survey.code_edit==request.args[0]).select() 
    if not surveys: 
     session.flash='survey not found' 
     redirect(URL('index')) 
    return surveys[0] 

def __take_survey(): 
    surveys=db(db.survey.code_take==request.args[0]).select() 
    if not surveys: 
     session.flash='survey not found' 
     redirect(URL('index')) 
    return surveys[0] 

ERROR:

Error ticket for "SurveyAppFlourish" 
Ticket ID 
127.0.0.1.2017-09-23.04-40-15.58fadb34-fbc0-4064-b9e1-ecc67362eafa 
<type 'exceptions.IndexError'> list index out of range 
Version 
web2py™ 
Version 2.15.3-stable+timestamp.2017.08.07.12.51.45 
Python 
Python 2.7.12: C:\Python27\python.exe (prefix: C:\Python27) 
Traceback 
1. 
2. 
3. 
4. 
5. 
6. 
7. 
8. 
9. 
10. 
11. 
12. 
Traceback (most recent call last): 
    File "C:\Users\Mudassar\PycharmProjects\web2pydemoproject\web2py\gluon\restricted.py", line 219, in restricted 
    exec(ccode, environment) 
    File "C:/Users/Mudassar/PycharmProjects/web2pydemoproject/web2py/applications/SurveyAppFlourish/controllers/survey.py", line 299, in <module> 
    File "C:\Users\Mudassar\PycharmProjects\web2pydemoproject\web2py\gluon\globals.py", line 409, in <lambda> 
    self._caller = lambda f: f() 
    File "C:/Users/Mudassar/PycharmProjects/web2pydemoproject/web2py/applications/SurveyAppFlourish/controllers/survey.py", line 88, in take 
    survey=__take_survey() 
    File "C:/Users/Mudassar/PycharmProjects/web2pydemoproject/web2py/applications/SurveyAppFlourish/controllers/survey.py", line 45, in __take_survey 
    surveys=db(db.survey.code_take==request.args[0]).select() 
IndexError: list index out of range 

錯誤是在surveys=db(db.survey.code_edit==request.args[0]).select()

+0

'request.args'是一個空列表或空字符串。你不能得到空的第零索引。我建議先檢查request.args的存在性,然後再嘗試索引它。 – JacobIRR

回答

0

在形式/app/controller/function/a/b/c,路徑的function後(該部分的URL即,a,bc)作爲列表存儲在request.args中。如果request.args[0]正在拋出IndexError,表示請求的URL中沒有URL參數。

request.args不是一個標準的Python列表,而是一個類gluon.storage.List的對象。它是可調用的並且需要一些額外的參數來處理特殊情況。

db(db.survey.code_edit == request.args(0, default=my_default)).select() 

如果你只是想的None值時,該項目不存在,你沒有明確指定一個默認:

例如,你可以在沒有URL ARGS指定一個默認
db(db.survey.code_edit == request.args(0)).select() 

以上,request.args(0)將返回None而不是產生IndexError

作爲替代,你的物品丟失時可以指定重定向URL:

db(db.survey.code_edit == request.args(0, otherwise=URL('index')).select() 

如果沒有request.args[0],上面會重定向到URL index。參數otherwise也可以是一個函數(例如,您可以使用它來設置response.flash然後執行重定向)。