Last active
October 14, 2016 13:47
-
-
Save nenodias/16dfb39699bb2a0d364087d355eb63fa to your computer and use it in GitHub Desktop.
Using Open Weather API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import socket | |
import requests | |
udp = None | |
def status_url(url): | |
return str(requests.get(url).status_code) | |
def get_dados(cidade): | |
api = '9e4a5a3c085cb78c102490f9c614bb6c' | |
unidade = 'metric' | |
lingua = 'pt' | |
retorno = requests.get('http://api.openweathermap.org/data/2.5/weather?q={cidade}&units={units}&APPID={api}&lang={lang}'.format(api=api, cidade=cidade, units=unidade,lang=lingua)) | |
if retorno.status_code == 200: | |
dados = retorno.json() | |
tempo = dados[u'weather'][0] | |
main = dados[u'main'] | |
cidade = dados[u'name'] | |
clima = tempo[u'description'] | |
temp = main[u'temp'] | |
maximo = main[u'temp_max'] | |
minimo = main[u'temp_min'] | |
mensagem = u"{cidade}: {clima}\n Temp:{temp}, Max:{max}".format(cidade=cidade, clima=clima, temp=temp, max=maximo, min=minimo) | |
return mensagem | |
else: | |
return {'erro':retorno.status_code} | |
def main(): | |
global udp | |
ip = '' | |
porta = 2222 | |
udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) | |
udp.bind( (ip, porta) ) | |
while True: | |
msg, addr = udp.recvfrom(1024) | |
udp.sendto('Olá cliente %s'%(addr[0]) , addr) | |
while True: | |
udp.sendto('\n\nDigite o nome da cidade: ', addr) | |
url, addr = udp.recvfrom(1024) | |
url = url.split('\n')[0] | |
if url == 'exit': | |
print('Flwss') | |
raise Exception('Saindo') | |
mensagem = get_dados(url) | |
udp.sendto( mensagem.encode('utf-8'), addr) | |
def cleanup(): | |
global udp | |
udp.close() | |
if __name__ == '__main__': | |
try: | |
main() | |
except Exception as ex: | |
print(ex) | |
finally: | |
cleanup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Para testar utilizar o nc -u
Ex: nc -u localhost 2222