2017-09-24 81 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然后执行重定向)。