捕捉错误不会部分起作用!
我要做的是检测用户上传的是真实图片还是伪造图片(例如重命名为的文本文件.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 不知道)。`