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


Python vobject.readOne函数代码示例

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


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

示例1: __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

示例2: put

    def put(cls, uri, data, content_type, cache=None):
        import vobject
        Party = Pool().get('party.party')

        party_id = cls.vcard(uri)
        if party_id is None:
            vcard = vobject.readOne(data)
            values = Party().vcard2values(vcard)
            try:
                party_id, = Party.create([values])
            except Exception:
                raise DAV_Forbidden
            party = Party(party_id)
            return (Transaction().cursor.database_name + '/Contacts/' +
                    party.uuid + '.vcf')
        if party_id:
            party = Party(party_id)
            vcard = vobject.readOne(data)
            values = party.vcard2values(vcard)
            try:
                Party.write([party], values)
            except Exception:
                raise DAV_Forbidden
            return
        return super(Collection, cls).put(uri, data, content_type,
            cache=cache)
开发者ID:kret0s,项目名称:gnuhealth-live,代码行数:26,代码来源:webdav.py

示例3: ical2text

def ical2text(ical_string):
    import vobject
    result = []
    if isinstance(ical_string, unicode):
        parsedCal = vobject.readOne(ical_string)
    else:
        try:
            parsedCal = vobject.readOne(ical_string)
        except:
            parsedCal = vobject.readOne(ical_string.decode('utf-8', 'ignore'))

    for event in parsedCal.getChildren():
        if event.name == 'VEVENT':
            if hasattr(event, 'dtstart'):
                start = event.dtstart.value.strftime('%F %H:%M')
            else:
                start = 'unknown start date'

            if hasattr(event, 'dtend'):
                end = event.dtend.value.strftime('%F %H:%M')
            else:
                end = start

            if start == end:
                date_str = start
            else:
                date_str = '%s -- %s' % (start, end)

            result.append('%s: %s' % (date_str, event.summary.value))

    return '\n'.join(result)
开发者ID:OldShatterhand77,项目名称:urlwatch,代码行数:31,代码来源:ical2txt.py

示例4: __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

示例5: testMatches

	def testMatches(self):
		strErik = """BEGIN:VCARD
VERSION:3.0
FN:null
N:;;;;
EMAIL;TYPE=INTERNET:[email protected]
END:VCARD
"""
		erikcard=vCardWithMatches(parsevCard(vobject.readOne(StringIO.StringIO(strErik))))
		strErik2 = """BEGIN:VCARD
VERSION:3.0
FN:Lars Erik Gewalli
N:Gewalli hotml;Lars;Erik;;
EMAIL;TYPE=INTERNET:[email protected]
NOTE:Phone\\:\\nUser 2\\: [email protected]\\n
END:VCARD
"""
		erikcard2=vCardWithMatches(parsevCard(vobject.readOne(StringIO.StringIO(strErik2))))
		self.assertFalse(erikcard2.matches(erikcard))
		strErik3="""BEGIN:VCARD
VERSION:3.0
FN:Erik M
N:Erik;M;;;
END:VCARD"""
		erikcard3=vCardWithMatches(parsevCard(vobject.readOne(StringIO.StringIO(strErik3))))
		#higher similarity is better
		self.assertFalse(erikcard3.matches(erikcard))

		pass
开发者ID:wallymathieu,项目名称:vcard-merger,代码行数:29,代码来源:vCardMatcherTests.py

示例6: __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

示例7: openics

def openics(invitation_file):
    with open(invitation_file) as f:
        try:
            with warnings.catch_warnings(): #vobject uses deprecated Exception stuff
                warnings.simplefilter("ignore")
                invitation = vobject.readOne(f, ignoreUnreadable=True)
        except AttributeError:
            invitation = vobject.readOne(f, ignoreUnreadable=True)
	return invitation
开发者ID:the-pete,项目名称:dotfiles,代码行数:9,代码来源:mutt-ical.py

示例8: get_invitation_from_path

def get_invitation_from_path(path):
    with open(path) as f:
        try:
            # vobject uses deprecated Exceptions
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                return vobject.readOne(f, ignoreUnreadable=True)
        except AttributeError:
            return vobject.readOne(f, ignoreUnreadable=True)
开发者ID:cptBaines,项目名称:dotfiles,代码行数:9,代码来源:dump-ical.py

示例9: merge

def merge(filenames, timezone_file):
    combined_calendar = vobject.iCalendar()

    with codecs.open(timezone_file, encoding='utf-8') as f:
        merge_timezones(combined_calendar, vobject.readOne(f))

    for filename in filenames:
        with codecs.open(filename, 'r', encoding='utf-8') as f:
            merge_events(combined_calendar, vobject.readOne(f))

    return combined_calendar.serialize()
开发者ID:basak,项目名称:community-calendar,代码行数:11,代码来源:merge.py

示例10: setUp

 def setUp(self):
     vcard_data = dict(
         nickname=u'x',
         mobile=u'3333308',
         name=u'NAME SURNAME',
         firstname=u'NAME',
         surname=u'SURNAME',
         email=u'[email protected]')
     self.vcard_data = namedtuple('Contact', vcard_data.keys())(
         **vcard_data)
     self.contact = Contact(alias=self.vcard_data.nickname,
                            mobile=self.vcard_data.mobile,
                            name=self.vcard_data.name)
     vcard_str = """
     BEGIN:VCARD
     VERSION:3.0
     FN:{name}
     N:{surname};{firstname};;;
     NICKNAME:{nickname}
     EMAIL;TYPE=INTERNET:{email}
     TEL;TYPE=CELL:{mobile}
     END:VCARD
     """.format(
         name=self.vcard_data.name,
         firstname=self.vcard_data.firstname,
         surname=self.vcard_data.surname,
         nickname=self.vcard_data.nickname,
         email=self.vcard_data.email,
         mobile=self.vcard_data.mobile)
     self.vcard_str = textwrap.dedent(vcard_str)
     self.vcard = vobject.readOne(self.vcard_str)
开发者ID:lukmdo,项目名称:smsgates,代码行数:31,代码来源:vcard_contacts_test.py

示例11: Sync

	def Sync(self):

		flag = raw_input("Enter '0' to exit program or any other key to continue: ")
		if flag == '0':
			exit()

		vcf_path = os.path.dirname(os.path.abspath(__file__))	
			
		vcf_list = glob.glob(vcf_path + "\*.vcf")
		count = 0

		for people in vcf_list:

			fp = open(people,"r")
			content = fp.read()
			fp.close()

			v = vobject.readOne(content)

			name=v.n.value
			number=v.tel.value

			new_contact = gdata.contacts.data.ContactEntry()
			new_contact.name = gdata.data.Name(full_name=gdata.data.FullName(text=name))
			new_contact.phone_number.append(gdata.data.PhoneNumber(text=number,rel=gdata.data.WORK_REL,primary='true'))

			contact_entry = self.gd_client.CreateContact(new_contact)
			print "Contact's ID: ", contact_entry.id.text
			name =""
			number = ""
			count = count + 1
			print "\nUploaded Contacts: " + str(count)
			time.sleep(1)
开发者ID:faisalmshaikh,项目名称:gcup,代码行数:33,代码来源:gcup.py

示例12: render_PUT

    def render_PUT(self, request):
        result = WebdavResource.render_PUT(self, request)
        if result is not None and result.has_key(request.path) and \
        request.env['CONTENT_TYPE'].strip().find('text/calendar') == 0:
            user=request.env.get('user')
            stream = self.storageProvider.get(request.path, user=user)
            try:
                event = vobject.readOne(stream)
                self.calendarProvider.store(request.path, event, user=user)

                # generate the etag data and add it to the document.
                stream.seek(0)
                md5Sum = getMD5(stream)
                md5Sum.update(request.path)
                etag = md5Sum.hexdigest()

                request.setHeader("ETag", "%s" % etag)

                self.storageProvider.setMeta(request.path,
                                        {'{DAV:}getetag': "%s" % etag,
                                         '{DAV:}getcontenttype': 'text/calendar'
                                        },
                                        user=user
                                 )
            except Exception as ex:
                logging.getLogger().warn('Not a calendar object. Got error: %s' % ex)
            finally:
                stream.close()
        return result
开发者ID:slaff,项目名称:attachix,代码行数:29,代码来源:office.py

示例13: parse_vcf

 def parse_vcf(self,response):
      v=vobject.readOne(response.body)
      print v
      item=response.meta['item']
      item['first_name']=v.n.value.given.strip()
      item['second_name']=v.n.value.family.strip()
      yield item
开发者ID:srinathreddy-1206,项目名称:university_spiders,代码行数:7,代码来源:utexas.py

示例14: _clean_private

    def _clean_private(cls, record, transp):
        '''
        Clean private record
        '''
        summary = cls.raise_user_error(transp, raise_exception=False)
        if 'summary' in record:
            record['summary'] = summary

        vevent = None
        if 'vevent' in record:
            vevent = record['vevent']
            if vevent:
                vevent = vobject.readOne(str(vevent))
                if hasattr(vevent, 'summary'):
                    vevent.summary.value = summary

        for field, value in (
                ('description', ''),
                ('categories', []),
                ('location', None),
                ('status', ''),
                ('organizer', ''),
                ('attendees', []),
                ('alarms', [])):
            if field in record:
                record[field] = value
            if field + '.rec_name' in record:
                record[field + '.rec_name'] = ''
            if vevent:
                if hasattr(vevent, field):
                    delattr(vevent, field)
        if vevent:
            record['vevent'] = vevent.serialize()
开发者ID:silpol,项目名称:tryton-bef,代码行数:33,代码来源:calendar_.py

示例15: getWakeUpTimes

	def getWakeUpTimes(self):
		retrive_iCal.retrive()
		self.lastRetrived = datetime.datetime.now()
		if os.path.exists("calender.ical") and \
		   self.lastParsed == os.path.getmtime("calender.ical"):
			return
		else:
			self.lastParsed = os.path.getmtime("calender.ical")

		self.wakeUpTimes = []
		iCalFile = open("calender.ical")
		parsedCal = vobject.readOne(iCalFile)
		for event in parsedCal.vevent_list:
			try:
				event.categories.value
			except:
				continue

			if event.categories.value == [u'WakeUp']:
				tz = event.dtstart.value.tzinfo
				start = event.dtstart.value.utctimetuple()
				end = event.dtend.value.utctimetuple()
				diff = event.dtend.value - event.dtstart.value
				now = datetime.datetime.utcnow().utctimetuple()
				#Reacuring event
				if event.rruleset:
					for date in event.rruleset:
						start = date.utctimetuple()
						end = date + diff
						end = end.utctimetuple()
						if end > now:
							break #alarm found
				#only append if alarm havent allready gone off
				if end > now:
					self.wakeUpTimes.append([start, end])
开发者ID:Norberg,项目名称:wakeUp,代码行数:35,代码来源:WakeUp.py


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