0

如何使用 vobject 检查任一字符串是否有效?

try and catch 是否有一些额外的方法或一般方法?

现在我这样做如下:

 try:
            vobj = vobject.readOne(vcard_readable)
 except Exception as e:
            error_message = {
                "valid": False,
                "reason": "Invalid vCard\n{0}".format(e)}

如何用VOBJECT处理unicode?

4

2 回答 2

2

您当前的代码工作正常,但通常您不想捕获Exception,因为这会掩盖代码中的其他错误。例如,如果我将您的代码片段放入一个文件中然后运行它......即使我没有导入该vobject模块,我也不会收到任何错误消息。这是因为该代码实际上引发了一个NameError

Traceback (most recent call last):
  File "foo.py", line 2, in <module>
    vobj = vobject.readOne(vcard_readable)
NameError: name 'vobject' is not defined

但是因为您正在捕获所有异常,所以您将其隐藏起来。更好的技术是仅捕获您希望从vobject模块接收的特定异常,并让其他异常正常渗透。

对于vobject,它引发的所有异常都将是 的子类vobject.base.VObjectError,因此以下代码就足够了:

 try:
            vobj = vobject.readOne(vcard_readable)
 except vobject.base.VObjectError as e:
            error_message = {
                "valid": False,
                "reason": "Invalid vCard\n{0}".format(e)}
于 2014-04-08T12:59:44.440 回答
0
 vcard = put.get('vcard')
            try:
                vcard_readable = base64.decodestring(vcard)
                quoted_printable_vcard = quopri.encodestring(vcard_readable)
                vobj = vobject.readOne(quoted_printable_vcard)
            except UnicodeEncodeError as e:  # case of bad encoding
                error_message = {
                    "valid": False,
                    "reason": "Invalid vCard\n{0}".format(e)}
                return HttpResponse(json.dumps(error_message), status=200)
            except vobject.base.VObjectError as e2:  # case of invalid vcard
                error_message = {
                    "valid": False,
                    "reason": "Invalid vCard format\n{0}".format(e2)}
                return HttpResponse(json.dumps(error_message), status=200)
            except:
                error_message = {
                    "valid": False,
                    "reason": "Invalid vCard."}
                return HttpResponse(json.dumps(error_message), status=200)

好的。我解决了。要vobject使用 UNICODE (UTF-8),需要使用:

quoted printable encoding.- 以下示例:

>>> s = "gżegżółka"
>>> s
'g\xc5\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka'
>>> import quopri
>>> quopri.encodestring(s)
'g=C5=BCeg=C5=BC=C3=B3=C5=82ka'
于 2014-04-08T16:42:22.807 回答