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


Python Cache.save方法代码示例

本文整理汇总了Python中cache.Cache.save方法的典型用法代码示例。如果您正苦于以下问题:Python Cache.save方法的具体用法?Python Cache.save怎么用?Python Cache.save使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cache.Cache的用法示例。


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

示例1: get_forecast

# 需要导入模块: from cache import Cache [as 别名]
# 或者: from cache.Cache import save [as 别名]
    def get_forecast(self, city, country):
        cache = Cache('myfile')

        cache_result = cache.load()

        if cache_result:
            return cache_result

        else:
            weather_provider = WeatherProvider()
            weather_data = weather_provider.get_weather_data(city, country)

            parser = Parser()
            parsed_data = parser.parse_weather_data(weather_data)

            weather = Weather(parsed_data)
            converter = Converter()
            temperature_celcius = converter.from_kelvin_to_celcius(weather.
                                                                   temperature)

            cache.save(temperature_celcius)
            return temperature_celcius
开发者ID:ronzohan,项目名称:DesignPatternsPython,代码行数:24,代码来源:facade.py

示例2: CachedRecovery

# 需要导入模块: from cache import Cache [as 别名]
# 或者: from cache.Cache import save [as 别名]
class CachedRecovery(object):
	"""
	Create a batch of transactions from master branch keys. Will cache each step and pick up where left off.
	"""

	def __init__(self, origin_branch, destination_branch, provider, account_gap=None, leaf_gap=None, first_account=0):  # todo - increase gaps
		self.origin_branch = origin_branch
		self.destination_branch = destination_branch
		self.cache = Cache(self.origin_branch.id)
		self.known_accounts = {}
		self.tx_db = TxDb(lookup_methods=[provider.get_tx], read_only_paths=[],	writable_cache_path='./cache/tx_db')
		self.account_gap = int(account_gap) if account_gap is not None else None
		self.leaf_gap = int(leaf_gap) if leaf_gap is not None else None
		self.first_account = first_account
		self.account_lookahead = True
		self.total_to_recover = 0

	def add_known_account(self, account_index, external_leafs=None, internal_leafs=None):
		"""
		Adding known account indexes speeds up recovery.
		If leafs are specified, these will be the only ones recovered(LEAF_GAP_LIMIT not used).
		If leafs not specified, addresses will be recovered using LEAF_GAP_LIMIT.
			batch.add_known_account(0)
			batch.add_known_account(1, external_leafs=[0,1,2,3,4], internal_leafs=[0,1,2])
			batch.add_known_account(1, external_leafs={0: "receiving addr 0", 1: "receiving addr 1", ...}, internal_leafs={0: "change addr 0", ...})
		"""
		leafs = {0: None, 1: None}
		if external_leafs is not None:
			leafs[0] = {int(v): None for v in external_leafs} if type(external_leafs) == list else {int(k): v for k, v in external_leafs.items()}
		if internal_leafs is not None:
			leafs[1] = {int(v): None for v in internal_leafs} if type(internal_leafs) == list else {int(k): v for k, v in external_leafs.items()}
		self.known_accounts[int(account_index)] = leafs  # each branch stored as {leaf_i: None or receiving address, ...} or None
		self.account_lookahead = False

	def recover_origin_accounts(self):
		"""will pick up where left off due to caching (caching part not implemented)"""
		if not self.account_lookahead:  # accounts already known
			for account_index, leafs in self.known_accounts.items():
				existed = self.recover_origin_account(account_index, internal_leafs=leafs[0], external_leafs=leafs[1])
				if not existed:
					self.known_accounts[account_index] = False
		else:  # searching for accounts
			accounts_ahead_to_check = self.account_gap
			while accounts_ahead_to_check:
				account_index = max(self.known_accounts.keys()) + 1 if self.known_accounts else 0
				existed = self.recover_origin_account(account_index)
				if existed:
					accounts_ahead_to_check = self.account_gap
					self.known_accounts[account_index] = True
				else:
					accounts_ahead_to_check -= 1
					self.known_accounts[account_index] = False

	def recover_origin_account(self, account_index, internal_leafs=None, external_leafs=None):
		"""
		:returns bool account_found
		If Oracle is one of account sources, will return True on success from Oracle.
		Else, will return True if there is any balance on the acct.
		"""
		# todo - balance caching so we don't pull it repeatedly for each acct
		# todo - not exising accounts should get cached too so we don't go through it again
		account = self.cache.load(Cache.ORIGINAL_ACCOUNT, account_index)
		if account is None:
			try:
				account = self.origin_branch.account(account_index)
				if internal_leafs is None or external_leafs is None:
					account.set_lookahead(self.leaf_gap)
					previous_balance = 0
					while True:
						address_map = account.make_address_map(do_lookahead=True)
						balance = account.balance()
						if balance == previous_balance:
							for address, path in address_map.items():
								print 'original %d/%s %s' % (account_index, path, address)
							break
						else:
							account._cache['issued']['0'] += self.leaf_gap  # todo - can be optimized
							account._cache['issued']['0'] += self.leaf_gap
							previous_balance = balance
				else:
					account.set_lookahead(0)
					for for_change, leaf_n_array in [(0, internal_leafs), (1, external_leafs)]:
						for leaf_n in leaf_n_array:
							address = account.address(leaf_n, change=int(for_change))  # this will get cached in the account object
							print "original %d/%d/%d %s" % (account_index, for_change, leaf_n, address)
				self.cache.save(Cache.ORIGINAL_ACCOUNT, account_index, account)
			except OracleUnknownKeychainException:
				print "! account %d: unkown" % account_index
				self.cache.save(Cache.ORIGINAL_ACCOUNT, account_index, False)
				return False  # todo - needs more sophisticated checks, eg bad connection, CC timeouts, etc
		return True if self.origin_branch.needs_oracle else bool(account.balance())

	def recover_destination_accounts(self):
		"""will pick up where left off due to caching"""
		for account_index in self.known_accounts:
			if self.known_accounts[account_index] and not self.cache.exists(Cache.DESTINATION_ACCOUNT, account_index):
				account = self.destination_branch.account(account_index)
				address = account.address(0, change=False)  # this will get cached in the account object
				print "destination %d/%d/%d %s" % (account_index, 0, 0, address)
				self.cache.save(Cache.DESTINATION_ACCOUNT, account_index, account)
#.........这里部分代码省略.........
开发者ID:bit-oasis,项目名称:multisig-recovery,代码行数:103,代码来源:recovery.py

示例3: Device

# 需要导入模块: from cache import Cache [as 别名]
# 或者: from cache.Cache import save [as 别名]
class Device(object):


    def __init__(self, device_id, device_key, auth_server=DEFAULT_AUTH_SERVER, request_factory=None, cache_file=None):
        self._cache = Cache(cache_file) if cache_file else None
        self._requests = SensorCloudRequests(device_id, device_key, auth_server, requests = request_factory, cache = self._cache)
        self._sensors = {}
        if self._cache:

            self._requests._authToken = self._cache.token
            self._requests._apiServer = self._cache.server

            for sensorCache in self._cache.sensors:
                self._sensors[sensorCache.name] = Sensor(self, sensorCache.name, sensorCache)

    def __contains__(self, sensor_name):
        """
        check if a sensor exits for this device on SensorCloud
        """

        response = self.url("/sensors/%s/" % sensor_name)\
                       .param("version", "1")\
                       .accept("application/xdr").get()

        if response.status_code == httplib.OK: return True
        if response.status_code == httplib.NOT_FOUND: return False

        raise error(response, "has sensor")

    def url(self, url_path):
        return self._requests.url(url_path)

    def has_sensor(self, sensor_name):
        return self.__contains__(sensor_name)

    def __iter__(self):
        sensors = self.all_sensors()
        for sensor in sensors:
            yield sensor


    def __getitem__(self, sensor_name):
        return self.sensor(sensor_name)


    def add_sensor(self, sensor_name, sensor_type="", sensor_label="", sensor_desc=""):
        """
        Add a sensor to the device. type, label, and description are optional.
        """

        logger.debug("add_sensor(sensor_name='%s', sensor_type='%s', sensor_label='%s', sensor_desc='%s')", sensor_name, sensor_type, sensor_label, sensor_desc)

        #addSensor allows you to set the sensor type label and description.  All fileds are strings.
        #we need to pack these strings into an xdr structure
        packer = xdrlib.Packer()
        packer.pack_int(1)  #version 1
        packer.pack_string(sensor_type)
        packer.pack_string(sensor_label)
        packer.pack_string(sensor_desc)
        data = packer.get_buffer()

        response = self.url("/sensors/%s/"%sensor_name)\
                       .param("version", "1")\
                       .data(data)\
                       .content_type("application/xdr").put()

        #if response is 201 created then we know the sensor was added
        if response.status_code != httplib.CREATED:
            raise error(response, "add sensor")

        return self.sensor(sensor_name)

    def sensor(self, sensor_name):

        sensor = self._sensors.get(sensor_name)
        if not sensor:
            cache = None
            if self._cache:
                cache = self._cache.sensor(sensor_name)
            sensor = Sensor(self, sensor_name, cache)
            self._sensors[sensor_name] = sensor

        return sensor

    def save_cache(self):
        self._cache.save()

    def all_sensors(self):
        pass
开发者ID:LORD-MicroStrain,项目名称:SensorCloud,代码行数:91,代码来源:device.py


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