当前位置: 首页>>代码示例>>Python>>正文


Python vobject.vCard函数代码示例

本文整理汇总了Python中vobject.vCard函数的典型用法代码示例。如果您正苦于以下问题:Python vCard函数的具体用法?Python vCard怎么用?Python vCard使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了vCard函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, address_book, filename = None):
        self.vcard = None
        self.address_book = address_book
        self.filename = filename
        self.old_vobject_version = False

        # at the moment khard must support two different behavior of the vobject module
        # the versions < 0.8.2 are still widely in use and expect unicode strings for non-ascii characters
        # all newer versions use utf-8 encoded strings directly
        # so we must determine, which version is installed
        try:
            # try to compare the version numbers
            if parse_version(get_distribution("vobject").version) < parse_version("0.8.2"):
                self.old_vobject_version = True
        except Exception as e:
            # if something goes wrong during vobject version comparison, try to serialize a
            # minimal vcard object with umlauts
            # if that fails, khard still uses a vobject version < 0.8.2
            v = vobject.vCard()
            o = v.add("fn")
            o.value = "Markus Schröder"
            o = v.add("n")
            o.value = vobject.vcard.Name(family="Schröder", given="Markus")
            try:
                v.serialize()
            except UnicodeDecodeError as e:
                self.old_vobject_version = True

        # load vcard
        if self.filename is None:
            # create new vcard object
            self.vcard = vobject.vCard()
            # uid
            choice = string.ascii_uppercase + string.digits
            uid_obj = self.vcard.add('uid')
            uid_obj.value = ''.join([random.choice(choice) for _ in range(36)])
            # use uid for vcard filename
            self.filename = os.path.join(address_book.get_path(),
                    self.vcard.uid.value + ".vcf")

        else:
            # create vcard from .vcf file
            try:
                file = open(self.filename, "r")
                contents = file.read()
                file.close()
            except IOError as e:
                raise
            # create vcard object
            try:
                self.vcard = vobject.readOne(contents)
            except vobject.base.ParseError as e:
                # if creation fails, try to repair vcard contents
                try:
                    self.vcard = vobject.readOne(
                            self.filter_invalid_tags(contents))
                    self.write_to_file(overwrite=True)
                except vobject.base.ParseError as e:
                    raise
开发者ID:DamienCassou,项目名称:khard,代码行数:59,代码来源:carddav_object.py

示例2: generate_vcard

    def generate_vcard(self):
        """Generates af VCard """
        context = aq_inner(self.context)

        # XXX department type not implemented yet
        # XXX vcard download from vtu.addressbook.types not yet tested.
        department = None
        if len(context.departments) > 0:
            department = context.departments[0].to_object
        
        card = vobject.vCard()
        card.add('fn').value = context.title
        card.add('n').value = vobject.vcard.Name(given=context.firstname,
                                                 family=context.lastname,)
        card.add('org').value = [getattr(department, 'title', u''),]
        card.add('adr').value = vobject.vcard.Address(
                street=getattr(department, 'street', u''),
                city=getattr(department, 'city', u''),
                country=u'Denmark',
                code=getattr(department, 'zipcode', u''),)
                          
        card.adr.type_param = [u'WORK']
        card.add('title').value = context.jobtitle
        card.add('email').value = context.email
        card.email.type_param = [u'INTERNET', u'WORK']
        card.add('tel').value = context.phone
        card.tel.type_param = [u'WORK']
        return card.serialize()
开发者ID:collective,项目名称:collective.person,代码行数:28,代码来源:person.py

示例3: ghostbuster_to_vcard

def ghostbuster_to_vcard(gbr):
    """Convert a GhostbusterRequest object into a vCard object."""

    import vobject

    vcard = vobject.vCard()
    vcard.add('N').value = vobject.vcard.Name(family=gbr.family_name,
                                              given=gbr.given_name)

    adr_fields = ['box', 'extended', 'street', 'city', 'region', 'code',
                  'country']
    adr_dict = dict((f, getattr(gbr, f, '')) for f in adr_fields)
    if any(adr_dict.itervalues()):
        vcard.add('ADR').value = vobject.vcard.Address(**adr_dict)

    # mapping from vCard type to Ghostbuster model field
    # the ORG type is a sequence of organization unit names, so
    # transform the org name into a tuple before stuffing into the
    # vCard object
    attrs = [('FN',    'full_name',      None),
             ('TEL',   'telephone',      None),
             ('ORG',   'organization',   lambda x: (x,)),
             ('EMAIL', 'email_address',  None)]
    for vtype, field, transform in attrs:
        v = getattr(gbr, field)
        if v:
            vcard.add(vtype).value = transform(v) if transform else v
    return vcard.serialize()
开发者ID:dragonresearch,项目名称:rpki.net,代码行数:28,代码来源:glue.py

示例4: vcard

def vcard(name,lista):
	count = 1
	c = 0
	separado = zip(*[iter(list(lista))]*200)
	partes = len(list(lista))/150
	print partes + 1
	separado = split_list(list(lista),partes+1)
	jj=""
	for sep in separado:	
		print count
		j = vobject.vCard()
		o = j.add('fn')
		o.value = "Lista Negra IGNORAR" + str(count)

		o = j.add('n')
		o.value = vobject.vcard.Name( family='IGNORAR', given='Lista Negra' + str(count) )

		for i,num in enumerate(sep):
			c+=1
			
			o = j.add('tel')
			o.type_param = "cell"
			if isinstance(num, dict):
				o.value = "+"+num['numero']
			else:
				o.value = "+"+num.numero
		count += 1
		jj += j.serialize()
		print "vCard" + str(count)+ " " + str(c) + " numeros"
		c=0


	return(jj)
开发者ID:Andresxgf,项目名称:listahu,代码行数:33,代码来源:extras.py

示例5: vcard_object

def vcard_object(request, url):
    if request.method == "POST":
        if "emailvcard" in request.POST:
            emailvcard = request.POST['emailvcard']
            business_card = BusinessCard.objects.get(url_name=url)
            v = vobject.vCard()
            v.add('n')
            v.n.value = vobject.vcard.Name(family=business_card.name, given=business_card.name)
            v.add('fn')
            v.fn.value = "%s %s" % (business_card.name, business_card.name)
            v.add('email')
            v.email.value = u'%s' % str(business_card.fieldbusiness_set.filter(type_record_field='E')[0])
            v.add('tel')
            v.tel.value = u'%s' % str(business_card.fieldbusiness_set.filter(type_record_field='P')[0])
            v.tel.type_param = 'WORK'
            v.add('url')
            v.url.value = u'%s' % str(business_card.websitecard_set.all()[0].url)
            output = v.serialize()
            filename = "%s.vcf" % (business_card.url_name)
            #response = HttpResponse(output, mimetype="text/x-vCard")
            #response['Content-Disposition'] = 'attachment; filename=%s' % filename
            myvcf = open('%s%s' % (settings.MEDIA_ROOT, filename), 'w')
            myvcf.write(output)
            myvcf.close()
            body = u'''
            <h1 style="background: #0AA8A6; padding: 8px;"><img src="http://qmoqui.com/static/img/logo-w.png"/></h1>
            <p>Add <b>%s</b> to your contact list from the file attached</p>
            ''' % business_card.name
            emailmsg = EmailMessage('Your new contact', body, 'Qmoqui <[email protected]>', [emailvcard,])
            emailmsg.attach_file('%s%s' % (settings.MEDIA_ROOT, filename))
            emailmsg.content_subtype = "html"
            emailmsg.send()
            return HttpResponse('Please check your email inbox')
开发者ID:detourmapsdev,项目名称:qmoqui,代码行数:33,代码来源:views.py

示例6: vcard

def vcard(u):
    c = vobject.vCard()
    c.add('n')
    ln = ' '.join(reversed(map(lambda x: x.strip(),
                               u.last_name.split(',', 1))))
    c.n.value = vobject.vcard.Name(ln,
                                   given=u.first_name)
    c.add('fn')
    c.fn.value = u.full_name()
    l = c.add('email', 'kn')
    l.value = u.primary_email
    l.type_paramlist = ['INTERNET']
    c.add('X-ABLabel', 'kn').value = 'kn'
    if u.telephone is not None:
        c.add('tel', 'kn')
        c.tel.value = u.telephone
        c.tel.type_param = 'CELL'
    if (u.addr_street is not None and
            u.addr_city is not None and
            u.addr_number is not None and
            u.addr_zipCode is not None):
        l = c.add('adr', 'kn')
        l.value = vobject.vcard.Address(' '.join((u.addr_street,
                                                  u.addr_number)),
                                        u.addr_city,
                                        '',
                                        u.addr_zipCode,
                                        'Nederland')
        c.add('x-abadr', 'kn').value = 'nl'
    return c.serialize()
开发者ID:aykevl,项目名称:kninfra,代码行数:30,代码来源:vcard.py

示例7: vcard

def vcard(request, id):
	import vobject
	qq = Contact.objects.get(id=id)
	card = vobject.vCard()
	card.add('n')
	card.n.value=vobject.vcard.Name(family=qq.surname, given=qq.name)
	card.add('fn')
	card.fn.value="%s %s" % (qq.name, qq.surname,)
	ei = 0
	for e in qq.emails.all():
		card.add('email')
		card.email_list[ei].value=e.address
		card.email_list[ei].type_param ='INTERNET'
	pi = 0
	for p in qq.phones.all():
		card.add('tel')	
		card.tel_list[pi].type_param=str(p.phone_type)
		card.tel_list[pi].value=p.number
		pi = pi + 1
	card.add('org')
	card.org.value = [str(qq.company)]
	card.add('title')
	card.title.value = str(qq.role)

	return HttpResponse(card.serialize())#, content_type = "text/vcard")
开发者ID:sirmmo,项目名称:dj-tasty-backbone,代码行数:25,代码来源:contacts.py

示例8: __init__

 def __init__(self, addressbook_name, addressbook_path, filename=""):
     self.addressbook_name = addressbook_name
     if filename == "":
         # create new vcard
         self.vcard = vobject.vCard()
         choice = string.ascii_uppercase + string.digits
         uid_obj = self.vcard.add('uid')
         uid_obj.value = ''.join([random.choice(choice) for _ in range(36)])
         self.vcard_full_filename = os.path.join(addressbook_path,
                 self.vcard.uid.value + ".vcf")
     else:
         # create vcard from file
         self.vcard_full_filename = filename
         # open .vcf file
         try:
             file = open(filename, "r")
             contents = file.read()
             file.close()
         except IOError as e:
             raise CarddavObject.VCardParseError(e)
         # create vcard object
         try:
             self.vcard = vobject.readOne(contents)
         except vobject.base.ParseError as e:
             # if creation fails, try to repair vcard contents
             try:
                 self.vcard = vobject.readOne(
                         self.filter_invalid_tags(contents))
                 self.write_to_file(overwrite=True)
             except vobject.base.ParseError as e:
                 raise CarddavObject.VCardParseError(e)
开发者ID:geier,项目名称:khard,代码行数:31,代码来源:carddav_object.py

示例9: createRawVcard

def createRawVcard(c):
    """
    Converts internal contact entry to VObject format
    """
    j = vobject.vCard()
    _createNameAttribute(c, j)
    
    if c.attributes['firstname']:
        if c.attributes['lastname']:
            fn = c.attributes['firstname'] + ' ' +  c.attributes['lastname']
        else:
            fn = c.attributes['firstname']
    else:
        fn = c.attributes['lastname']
    _createRawAttribute(c,  j,  'fn',  "'''" + fn + "'''")
    _createRawAttribute(c,  j,  'title',  "c.attributes['title']")

    _createRawAttribute(c,  j,  'email',  "c.attributes['email']",  [['type_param',  "'INTERNET'"]])
    _createPhoneAttribute(c, j,  VCF_PHONETYPE_HOME[0])
    _createPhoneAttribute(c, j,  VCF_PHONETYPE_WORK[0])
    _createPhoneAttribute(c, j,  VCF_PHONETYPE_MOBILE[0])
    _createPhoneAttribute(c, j,  VCF_PHONETYPE_FAX[0])
    
    _createAddressAttribute(c,  j, VCF_ADDRESSTYPE_HOME[0])
    _createAddressAttribute(c,  j, VCF_ADDRESSTYPE_WORK[0])
    _createBusinessDetails(c,  j)
    return j
开发者ID:kichkasch,项目名称:pisi,代码行数:27,代码来源:vobjecttools.py

示例10: __init__

    def __init__(self, address_book, filename = None):
        self.vcard = None
        self.address_book = address_book
        self.filename = filename

        if self.filename is None:
            # create new vcard object
            self.vcard = vobject.vCard()
            # uid
            choice = string.ascii_uppercase + string.digits
            uid_obj = self.vcard.add('uid')
            uid_obj.value = ''.join([random.choice(choice) for _ in range(36)])
            # use uid for vcard filename
            self.filename = os.path.join(address_book.get_path(),
                    self.vcard.uid.value + ".vcf")

        else:
            # create vcard from .vcf file
            try:
                file = open(self.filename, "r")
                contents = file.read()
                file.close()
            except IOError as e:
                raise
            # create vcard object
            try:
                self.vcard = vobject.readOne(contents)
            except vobject.base.ParseError as e:
                # if creation fails, try to repair vcard contents
                try:
                    self.vcard = vobject.readOne(
                            self.filter_invalid_tags(contents))
                    self.write_to_file(overwrite=True)
                except vobject.base.ParseError as e:
                    raise
开发者ID:okapia,项目名称:khard,代码行数:35,代码来源:carddav_object.py

示例11: genVCardFromJson

def genVCardFromJson(infile, outfile):
    outf = open(outfile,'w')
    with open(infile,'r') as inf:
        comps = json.load(inf)
        for comp in comps:
            v = vobject.vCard()
            v.add('n')
            v.n.value = vobject.vcard.Name(family = " ".join(comp['businessName']))
            v.add('fn')
            v.fn.value =" ".join(comp["businessName"])
            for c in comp:
                if c not in requiredVC:
                    lst = comp[c]
                    if type(lst)==type([]):
                        for i in range(len(lst)):

                            if i ==0:
                                t = v.add(c)
                            else:
                                t=v.add(c+str(i))
                            t.value = "".join(comp[c][i])
                    else:
                        t=v.add(c)
                        t.value = "".join(comp[c])
            outf.write(v.serialize())
开发者ID:rui1,项目名称:web_scrapy_YP,代码行数:25,代码来源:scrape_yellowpages.py

示例12: generate_vcard

def generate_vcard(obj):
    """
    Generates a vCard from the object attributes.
    """
    # vCard
    card = vobject.vCard()
    # Name
    card.add('n')
    card.n.value = vobject.vcard.Name(
        family=(obj.lastname or ''),
        given=(obj.firstname or ''),
    )
    # Fullname
    card.add('fn')
    card.fn.value = (obj.title or '')
    # E-Mail
    card.add('email')
    card.email.value = (obj.email or '')
    # Company
    card.add('org')
    account = (obj.account or '')
    if account:
        account = account.to_object.Title()
    card.org.value = [account]
    # Account-Type
    card.add('title')
    card.title.value = (obj.type.title() or '')
    # UID
    card.add('uid')
    card.uid.value = (obj.UID() or '')
    # Phone
    card.add('tel')
    card.tel.value = (obj.phone or '')
    # Serialize
    return card.serialize()
开发者ID:operun,项目名称:operun.crm,代码行数:35,代码来源:vcard.py

示例13: generateVcard

def generateVcard(d,vcardfile,jpegfile,count,index,pprint=True):
    '''  We construct vobject using dict which represents pull from sqlite db. '''
    vcard = vobject.vCard()
    o = vcard.add('n')
    o.value = vobject.vcard.Name(
                        family=d.get(SURNAME) or '',
                        given=getForename(d.get(FORENAME),count,index),
                        additional=d.get(ADDITIONAL) or '',
                        prefix=d.get(PREFIX) or '',
                        suffix=d.get(SUFFIX) or ''
    )
    o = vcard.add('fn')
    o.value = getFullName(d.get(SURNAME) or '', d.get(FORENAME) or '',count,index)
    if d.get(ORG):
        for v in d.get(ORG):
            o = vcard.add('org')
            o.value = [v]
    for field,typ in [(NICKNAME,'nickname'),(ROLE,'role'),(BDAY,'bday')]:
        if d.get(field):
            o = vcard.add(typ)
            o.value = d.get(field)
    for fieldname,typ in [(EMAIL,'email'),(TEL,'tel'),(URL,'url')]:
        if d.get(fieldname):
            for k,v in d.get(fieldname).items():
                o = vcard.add(typ)
                o.value = v
                #o.modifier
                o.type_param = k
    if d.get(ADDR):
        for k,v in d.get(ADDR).items():
            a = vcard.add('adr')
            a.type_param = k
            a.value = vobject.vcard.Address(
                getStreet(v.get(STREET),count,index),
                city=v.get(CITY) or '',
                region=v.get(STATE) or '',
                code=v.get(POSTCODE) or '',
                country=v.get(COUNTRY) or '',
                box=v.get(POBOX) or '',
                extended=v.get(EXTADR) or ''
            )
    if d.get(NOTE):
        o=vcard.add('note')
        o.value = getNote(d,vcardfile)
    if d.get(PHOTO):
        o=vcard.add('photo')
        o.value = getPhoto(jpegfile)
        o.encoding_param = 'b'
        o.type_param = 'jpeg'
    # Enable this to prettyprint the vobject representation
    # We'd probably prefer to be in JSON here.
    if pprint:
        vcard.prettyPrint()
    # Check to see we can parse the result back to vobject
    s = vcard.serialize()
    pvcard = vobject.readOne(s)
    if d.get(SURNAME):
        assert(pvcard.n.value.family == d.get(SURNAME))
    return s
开发者ID:malminhas,项目名称:contacts-generator,代码行数:59,代码来源:genvcards.py

示例14: process_parent

def process_parent(name, member, section, f):

    # If the name does not appear to have lastname part
    # add it from the member name.
    if len(name.strip().split(' ')) < 2:
        name = "{} {}".format(name.strip(), member['last_name'])

    j = vo.vCard()

    uid = j.add('UID')
    uid.value = "{}{}[email protected]".format(
        name.replace(" ", ""),
        member[OSM_REF_FIELD])

    j.add('n')
    j.n.value = vo.vcard.Name(
        family=f('lastname') if f('lastname').strip() else member['last_name'],
        given=f('firstname'))
    j.add('fn')
    j.fn.value = name

    next_ = next_f(j, 0).next_f

    for _ in ['phone1', 'phone2']:
        number, name = parse_tel(f(_), _)
        next_('tel', name, number)

    for _ in ['email1', 'email2']:
        if f(_).strip() == "":
            # Ignore empty emails.
            continue

        # If the email is marked as private, add it as a note.
        if (f(_).startswith('x ') or
                f("{}_leaders".format(_)) != "yes"):
            next_('note', _,
                  "Private email address: {}".format(f(_)))
        else:
            next_('email', _, f(_))

    next_('adr', 'Primary',
          vo.vcard.Address(
              street=f('address1'),
              city=f('address2'),
              region=f('address3'),
              country=f('address4'),
              code=f('postcode')))

    org = j.add('org')
    org.value = [section, ]

    note = j.add('note')
    note.value = "Child: {} {} ({})\n".format(
        member['first_name'], member['last_name'], section)

    cat = j.add('CATEGORIES')
    cat.value = ("7th", "7th Lichfield Parent")

    return j.serialize()
开发者ID:hippysurfer,项目名称:scout-records,代码行数:59,代码来源:export_group_vcard.py

示例15: _vcard_string

def _vcard_string(person):
    """
    Helper function for vcard views. Accepts a 'person' object 
    with certain attributes (firstname, lastname, email, phone, id)
    and returns a string containing serialized vCard data.
    """
    # vobject API is a bit verbose...
    v = vobject.vCard()
    v.add("n")
    v.n.value = vobject.vcard.Name(family=person.lastname, given=person.firstname)
    v.add("fn")
    v.fn.value = "%s %s" % (person.firstname, person.lastname)
    v.add("email")
    if person.personnal_address:
        a = person.personnal_address
        addr = v.add("ADR")
        addr.type_param = "HOME"
        street = a.street1
        if a.street2:
            street += ", " + a.street2
        addr.value = vobject.vcard.Address(
            street=street, city=a.city, region=a.state, code=a.zipcode, country=a.country
        )
    if person.work and person.work.address:
        a = person.work.address
        addr = v.add("ADR")
        addr.type_param = "WORK"
        street = a.street1
        if a.street2:
            street += ", " + a.street2
        addr.value = vobject.vcard.Address(
            street=street, city=a.city, region=a.state, code=a.zipcode, country=a.country
        )

    if person.email:
        email = v.add("email")
        email.value = person.email
        email.type_param = "INTERNET"
    if person.title:
        v.add("title")
        v.title.value = person.title
    if person.work:
        org = v.add("org")
        org.value = (person.work.name,)
    for tel in person.phone_set.all():
        t = v.add("tel")
        t.type_param = tel.name.upper()
        t.value = tel.number
    for url in person.url_set.all():
        u = v.add("url")
        if url.explicit_url:
            u.type_param = "HOME"
            u.value = url.explicit_url
        else:
            u.type_param = url.type.upper()
            u.value = URLS[url.type] % url.__dict__

    output = v.serialize()
    return output
开发者ID:ecometrica,项目名称:django-vcerver,代码行数:59,代码来源:views.py


注:本文中的vobject.vCard函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。