在处理UTF-8字符时,如何用vobject检查字符串是否有效vcard?

时间:2014-04-08 12:15:50

标签: python vcard vobject

如何用vobject检查字符串是否有效vcard?

使用try和catch是否有一些额外的方法或通用方法?

现在我这样做:

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

如何使用VOBJECT处理unicode?

2 个答案:

答案 0 :(得分: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)}

答案 1 :(得分: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'