捕获错误不能正常工作!
我想要做的是检测用户是否上传了真实图片或伪造的(例如,文本文件重命名为.jpeg
)。
try:
image = Image.open(StringIO.StringIO(buf=avat))
type = image.format
(x, y) = image.size
print x, y
if x < y:
orientation = "portrait"
else:
orientation = "paysage"
pref = str(time.time())
nomf = pref.replace(".", "")
nomfich = nomf+"."+type
self.fs = GridFS(self.db)
avatar_id = self.fs.put(avat, content_type=avctype, filename=nomfich)
except IOError, TypeError:
self.redirect("/erreur-im")
以下是http://localhost:8000/erreur-im
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado-2.3.post1-py2.7.egg\tornado\web.py", line 1023, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "G:\Mon projet\sog-emouk\handlers.py", line 101, in get
avctype = self.db.users.find_one()["avctype"]
TypeError: 'NoneType' object has no attribute '__getitem__'
在这里,我想做的是将用户重定向到一个页面,告诉他们用户必须使用图片图片。
当我将self.redirect
更改为self.write("please upload....")
时,结果很奇怪:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado-2.3.post1-py2.7.egg\tornado\web.py", line 1023, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "G:\Mon projet\sog-emouk\handlers.py", line 153, in post
user={"pseudo":pseudo, "orientation":orientation, "avctype":avctype, "password":password, "email":email, "tel":tel, "commune":commune, "coord":coord, "statut":statut, "telf":telf, "avatar":avatar_id, "acheteur":[], "vendeur":[]}
UnboundLocalError: local variable 'orientation' referenced before assignment
所以,我想self.redirect
这里有一些奇怪的事情,因为self.write
在捕获异常之后会对代码产生影响(实际上由于文本文件而无法识别image.size) .`
答案 0 :(得分:1)
此回溯表明您正在重定向到一个代码,该代码在两个位置再次抛出未捕获的异常。
请参阅:avctype = self.db.users.find_one()["avctype"]
和
user={"pseudo":pseudo, "orientation":orientation, "avctype":avctype, "password":password, "email":email, "tel":tel, "commune":commune, "coord":coord, "statut":statut, "telf":telf, "avatar":avatar_id, "acheteur":[], "vendeur":[]}
查看两个追溯:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado-2.3.post1-py2.7.egg\tornado\web.py", line 1023, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "G:\Mon projet\sog-emouk\handlers.py", line 101, in get
avctype = self.db.users.find_one()["avctype"]
TypeError: 'NoneType' object has no attribute '__getitem__'
和
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado-2.3.post1-py2.7.egg\tornado\web.py", line 1023, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "G:\Mon projet\sog-emouk\handlers.py", line 153, in post
user={"pseudo":pseudo, "orientation":orientation, "avctype":avctype, "password":password, "email":email, "tel":tel, "commune":commune, "coord":coord, "statut":statut, "telf":telf, "avatar":avatar_id, "acheteur":[], "vendeur":[]}
UnboundLocalError: local variable 'orientation' referenced before assignment
因此,我认为您在初始化应用程序和请求处理程序的应用程序中出错。
此外,您还有一个look at如何检查文件是否实际上是jpeg。事实上,您可以检查其他媒体文件格式avi,rm等,检查前四个字符。