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


Python firebase.Firebase类代码示例

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


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

示例1: _process_pages

    def _process_pages(self, spider):
        host = spider.get_origin_host()
        fire = Firebase('%s/pages/%s' % (self.fire_host, host))

        origin_hash = url_hash(host)

        cursor = self.db.cursor()

        query = """
SELECT content_item_id
     , content_node_id
     , object_type
     , lint_critical
     , lint_error
     , lint_warn
     , lint_info
     , lint_results
  FROM page
 WHERE request_method = 'GET'
   AND external = 0
   AND object_type IS NOT NULL
   AND content_item_id IS NOT NULL
 ORDER BY lint_critical DESC, lint_error DESC, lint_warn DESC
 LIMIT 20
        """
        cursor.execute(query)

        rows = cursor.fetchall()

        res = {}
        for row in rows:
            res[row.pop('content_item_id')] = row

        fire.update(res)
开发者ID:saymedia,项目名称:SaySpider,代码行数:34,代码来源:reports.py

示例2: get_ladder

    def get_ladder(self):
        """Parses footywire HTML to get ladder"""


        ladder_url = "ft_ladder"
        session = requests.session()
        response = session.get(self.baseURL + ladder_url, headers=self.headers)
        soup = BeautifulSoup(response.text)

        ladder = []

        for link in soup.find_all('a'):
            mylink = link.get('href')
            if mylink.find('/') == -1:
                if mylink.find('ft') == -1:
                    mylink = mylink[3:]
                    mylink = mylink.replace('-', ' ')
                    ladder.append((mylink))

        if ladder:
            f = Firebase('https://flickering-fire-9394.firebaseio.com/ladder')
            response = f.remove()
            print response
            for team in ladder:
                team = multipleReplace(team)
                print team
                r = f.push({'team_id': team })
开发者ID:choc0bot,项目名称:ftips,代码行数:27,代码来源:fwscrape.py

示例3: FirebasePlugin

class FirebasePlugin(IPlugin):

	def __init__(self):
		try:
			with open(secrets_filename, "r") as f:
				data = f.read()
		except:
			err = "Error processing {} - make sure to fill in {}!".format(secrets_filename, secrets_filename)
			with open(secrets_filename, "w") as f:
				f.write(document)
			raise Exception(err)
		try:
			conf = yaml.load(data)
			self.firebase_url = conf["firebase_url"]
			self.secret = conf["secret"]
			self.data_bucket = conf["data_bucket"]
		except:
			raise Exception("Error parsing {}!".format(secrets_filename))
		if self.firebase_url is None or self.secret is None:
			raise Exception("Error parsing {} - not all fields have been filled in!".format(secrets_filename))
		auth_payload = {"uid": "1", "auth_data": "foo", "other_auth_data": "bar"}
		token = create_token(self.secret, auth_payload)
		self._client = Firebase(self.firebase_url + self.data_bucket, auth_token=token)

	def process_message(self):
		message = messages[random.randint(0, len(messages)-1)]
		self._client.push({'timestamp': int(time.time()), 'message': message})
开发者ID:artekw,项目名称:rfm69-python,代码行数:27,代码来源:firebase.py

示例4: runForTerm

def runForTerm(term, current_time):
    last_year = (datetime.datetime.now() - timedelta(days=550))
    twitter_counts_to_save = {}
    while last_year.strftime('%Y-%m-%d') < current_time:
        print(last_year.strftime('%Y-%m-%d'))
        while True:
            try:

                r = requests.get("https://cdeservice.mybluemix.net:443/api/v1/messages/count?q=" + term + "%20posted%3A" + last_year.strftime('%Y-%m-%d') + "%2C" + last_year.strftime('%Y-%m-%d'), auth=('667dedc9-0e40-4860-abe9-55011697cd3d', 'Pxl3qyvFAH'))
                parsed_json = json.loads(r.content)
                if parsed_json == None:
                    last_year = last_year + timedelta(days=1)
                    continue
                twitter_counts_to_save[last_year.strftime('%Y-%m-%d')] = long(parsed_json['search']['results'])
                last_year = last_year + timedelta(days=1)
                break
            except:
                print("Download Error")


    f = Firebase('https://sv2.firebaseio.com/tweets/' + term)
    while True:
      try:
        f.update(twitter_counts_to_save)
        break
      except:
        print ("Upload error...trying again!")
开发者ID:patrick-ogrady,项目名称:banshee,代码行数:27,代码来源:update_twitter_historical.py

示例5: get_senadores_metadata_atual

def get_senadores_metadata_atual():
	# Gets attributes from parlamentares and saves into Firebase 
	# --> still needs to put right below 'senadores URL', now it's using FB id there...

	url = 'http://legis.senado.gov.br/dadosabertos/senador/lista/atual'
	uh = urllib.urlopen(url)
	data = uh.read()
	tree = ET.fromstring(data)
	senadores_tree = tree.findall('.//IdentificacaoParlamentar')
	
	senadores_dict = {}
	for sen in senadores_tree:
		
		codigo = sen.find('CodigoParlamentar').text
		# creates object with id 'codigo' and all data nested into that
		senadores_dict[codigo] = {}
		senadores_dict[codigo]['NomeParlamentar'] 			= sen.find('NomeParlamentar').text
		senadores_dict[codigo]['SexoParlamentar'] 			= sen.find('SexoParlamentar').text
		senadores_dict[codigo]['FormaTratamento'] 			= sen.find('FormaTratamento').text
		senadores_dict[codigo]['UrlPaginaParlamentar']		= sen.find('UrlPaginaParlamentar').text
		senadores_dict[codigo]['UrlFotoParlamentar']		= sen.find('UrlFotoParlamentar').text
		senadores_dict[codigo]['EmailParlamentar'] 			= sen.find('EmailParlamentar').text
		senadores_dict[codigo]['SiglaPartidoParlamentar'] 	= sen.find('SiglaPartidoParlamentar').text
		senadores_dict[codigo]['UfParlamentar'] 			= sen.find('UfParlamentar').text

	#firebase.post('/senadores', senadores_dict) # Substituir posteriormente por método genérico para salvar os dados
	f = Firebase(FBURL + '/senadores')
	f.put(senadores_dict)
开发者ID:luipillmann,项目名称:databr,代码行数:28,代码来源:get_clean_data.py

示例6: main

def main():
    BASE_URL = 'https://amber-fire-5569.firebaseio.com/Traffic/'
    f = Firebase(BASE_URL)
    
    results = f.get()
    
    for key in results:
        pprint(key)
        pprint(results[key])
        payload = results[key]
        
        street1 = results[key]['intersection1']
        street2 = results[key]['intersection2']

        coords = intersection_to_coords(street1, street2)
        print coords

        try:
            payload['Latitude'] = coords['Latitude']
        except TypeError:
            continue
        payload['Longitude'] = coords['Longitude']
        endpoint = Firebase(BASE_URL+key)
        pprint(payload)
        endpoint.set(payload)
开发者ID:lowellbander,项目名称:HackDukeScripts,代码行数:25,代码来源:add_coords.py

示例7: get_votos_senador

def get_votos_senador(codigo):
	#r = requests.get('https://maisbr.firebaseio.com/senadores/' + codigo + '/votos.json')
	#senadores_dict = r.json()

	f = Firebase(FBURL + '/senadores/' + codigo + '/votos')
	senadores_dict = f.get()

	return senadores_dict
开发者ID:luipillmann,项目名称:databr,代码行数:8,代码来源:db_functions.py

示例8: __init__

 def __init__(self, auth, structure_id, device_id):
     self.device_id = device_id
     self.structure_id = structure_id
     self.auth = auth
     self.fb_target_temp = Firebase(
         "https://developer-api.nest.com/devices/thermostats/" + device_id + "/target_temperature_f", auth_token=auth
     )
     self.fb_away = Firebase("https://developer-api.nest.com/structures/" + structure_id + "/away", auth_token=auth)
开发者ID:rernst76,项目名称:ACControl,代码行数:8,代码来源:Thermostat.py

示例9: schedule

    def schedule(self, file_path):
        track = Firebase(FIREBASE_URL + "tracks/")

        track_data = {}
        track_data["url"] = file_path.replace(os.path.join(os.getcwd(), "jukebox"), "")
        track_data["offset"] = self.play_time(file_path)

        track.post(track_data)
开发者ID:a2lin,项目名称:secret-octo-wookie,代码行数:8,代码来源:audio.py

示例10: upload

def upload(status):
    f = Firebase('https://amber-fire-5569.firebaseio.com/tweets')
    payload = {}
    payload['body'] = status['text']
    payload['geo'] = status['geo']
    payload['date'] = status['created_at']
    print payload
    f.push(payload)
开发者ID:lowellbander,项目名称:HackDukeScripts,代码行数:8,代码来源:twython_test.py

示例11: updateProjectFeatures

def updateProjectFeatures(id):
	fire = Firebase("https://friendlychat-1d26c.firebaseio.com/protectedResidential/9999/projects/-KLLdC7joRUmOsT11Efp")
	temp = fire.get()
	# projects_all = fire.get()
	# print json.dumps(temp, indent = 4)
	price_range,size_range = price_size_range({"-KLLdC7joRUmOsT11Efp" : temp})
	# print price_range, size_range
	updated_features = all_features_mapping(getProjectDataDoc(id), getProjectFeaturesDoc(id), price_range, size_range)
	es.update(index = 'projects', doc_type = 'features', id = id, body = {"doc" : updated_features})
开发者ID:utk12,项目名称:chatbot,代码行数:9,代码来源:project_features.py

示例12: send_data

def send_data(msg, path):
	from firebase import Firebase
	try:
		fbase = Firebase(path)
		fbase.push(msg)
	except Exception as e:
		print("FireBase: can not send the data to the server:" + str(e))
		print("FireBase: not uploading")
		return "exception"
开发者ID:Andmo,项目名称:LowCostLoRaGw,代码行数:9,代码来源:FireBase.py

示例13: get_dict_nomes_senadores

def get_dict_nomes_senadores():
	# Retorna lista com nomes de todos os senadores salvos no DB
	f = Firebase(FBURL + '/senadores')
	dados = f.get()

	dict_nomes = {}
	for key, val in dados.iteritems():
		dict_nomes[key] = val['NomeParlamentar']

	return dict_nomes
开发者ID:luipillmann,项目名称:databr,代码行数:10,代码来源:db_functions.py

示例14: createProjectsDatabase

def createProjectsDatabase():
	fire = Firebase("https://friendlychat-1d26c.firebaseio.com/protectedResidential/9999/projects/-KLLdC7joRUmOsT11Efp/")
	i = '-KLLdC7joRUmOsT11Efp'
	temp = fire.get()
	# projects_all = fire.get()
	# for i in projects_all:
	# createProjectDataIndex(i, projects_all[i])
	createProjectDataIndex(i, temp 	)
	createProjectFeaturesIndex(i)
	updateProjectFeatures(i)
开发者ID:utk12,项目名称:chatbot,代码行数:10,代码来源:project_features.py

示例15: get_votacoes_senador

def get_votacoes_senador(codigo, params):
	# Salva votações do senador no banco de dados
	# !!! Se a matéria foi votada mais de uma vez (em diferentes tramitações), somente um voto é guardado
	# |_ isso depende de qual for colocado por último no XML (elaborar rotina para ordenar por data!)
	# @params: 		JSON com as seguintes opções:
	# 	sigla:       (opcional) sigla da matéria - retorna apenas as matérias da sigla informada.
    # 	numero:      (opcional) número da matéria - retorna apenas as matérias do número informado.
    # 	ano:         (opcional) ano da matéria - retorna apenas as matérias do ano informado
    # 	tramitacao:  (opcional) (S ou N) - retorna apenas as matérias que estão tramitando (S) ou apenas as que não estão (N). Se não for informado, retorna ambas.

	if params == {}: params = {'ano':'2016', 'sigla':'PEC'}
	tree = af.votacoes_senador(codigo, params)
	votacoes_tree = tree.findall('.//Votacao')

	# Inicialização com possíveis valores de votação
	votos_dict = {
	'Sim' 	: {},
	'Nao' 	: {},
	'PNRV' 	: {},
	'MIS' 	: {},
	'LS' 	: {},
	'LL'	: {},
	'Outro'	: {}
	}	

	for vot in votacoes_tree:
		
		voto = vot.find('.//DescricaoVoto').text

		# Testes "frágeis" para adaptar nome das keys, os tipos são somente esses. Primeiro caracter somente para fugir de probs. de codificiação (unicode). Arrumar futuramente!
		if 	 voto[:1] == 'S'	: voto = 'Sim'
		elif voto[:1] == 'N'	: voto = 'Nao'
		elif voto[:1] == 'M'	: voto = 'MIS'
		elif voto[:1] == 'P'	: voto = 'PNRV'
		elif voto[:2] == 'LS'	: voto = 'LS'
		elif voto[:2] == 'LL'	: voto = 'LL'
		else: 					  voto = 'Outro'

		cod_materia = vot.find('.//CodigoMateria').text

		print cod_materia, voto

		votos_dict[voto][cod_materia] = {}
		votos_dict[voto][cod_materia]['DescricaoVoto'] 			= vot.find('.//DescricaoVoto').text
		votos_dict[voto][cod_materia]['DescricaoVotacao'] 		= vot.find('.//DescricaoVotacao').text
		votos_dict[voto][cod_materia]['DescricaoResultado'] 	= vot.find('.//DescricaoResultado').text
		votos_dict[voto][cod_materia]['AnoMateria'] 			= vot.find('.//AnoMateria').text
		votos_dict[voto][cod_materia]['SiglaSubtipoMateria'] 	= vot.find('.//SiglaSubtipoMateria').text
	
	# Salva no Firebase (teste com atualização 1 a 1)
	for key, val in votos_dict.iteritems():
		for k, v in val.iteritems():
			url = '/senadores/' + codigo + '/votos/' + key + '/' + k
 			f = Firebase(FBURL + url)
			f.patch(votos_dict[key][k])
开发者ID:luipillmann,项目名称:databr,代码行数:55,代码来源:get_clean_data.py


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