Jump to content

[Python] Conversor de Moedas sempre actualizado


Recommended Posts

Bem, já existem muitas aplicações que fazem o mesmo, mas como queria aprender alguma coisa de XML e de GUIs em Python, resolvi fazer esta aplicação.

Em que consiste:

A aplicação vê quais os feeds online e saca uma lista de moedas disponíveis para converter.

Quando o utilizador escolhe as moedas e o valor e converte, a aplicação faz download do feed, guarda-o e procura a moeda de destino e o seu valor, e esta é posta numa espécie de cache para futuras procuras.

Os feeds são actualizados de 15 em 15 minutos, pois o servidor não permite menos que isso e pode bloquear o IP 😁.

Requesitos:

wxPython

Download: http://www.box.net/shared/static/ioj476dwsw.zip

Sugestões e críticas bem vindas.😄

Código:

conversions.py

# @ author:  Mauro Pinto

import os, re, datetime
from xml.dom import minidom
from urllib import urlopen

searches = {}
path = os.path.join( os.getcwd(), 'xml' )

def getCur ( fromcur, tocur, value=0 ):

   fromcur, tocur = fromcur.upper(), tocur.upper()

   if fromcur in searches:
       if tocur in searches[fromcur]:
           return round( searches[fromcur][tocur] * value, 2 )
   else:

       searches[fromcur] = {}


   curlist = minidom.parse( os.path.join( path, fromcur + '.xml' ) ).getElementsByTagName('item')

   for el in curlist:

       currency = el.getElementsByTagName('title')[0].firstChild.data

       if currency[8:11] == tocur:

           currency = float( currency[13:-1].replace(',','') )

           searches[fromcur][tocur] = currency

           return round( value * currency, 2 )

def getXMLCur ( currency ):

   currency = currency.upper()
   filename = currency + '.xml'
   filepath = os.path.join( path, filename )
   isUpdatable, exists = True, os.path.exists( filepath )

   if exists:

       isUpdatable = ( datetime.datetime.now() - datetime.datetime.fromtimestamp( os.path.getmtime( filepath ) ) ) > datetime.timedelta( minutes = 15 )

   if isUpdatable or not exists:

       if currency in searches: del searches[currency]

       xmlData = urlopen( 'http://currencysource.ez-cdn.com/' + filename ).read()

       if len( xmlData ):

           file = open( filepath, 'w' )
           file.write( xmlData )
           file.close()

           return 1

       else: return 0

   elif exists: return 1

def getCurrencies():

   regex = re.compile('<A HREF="([A-Z]{3}).xml">')
   return regex.findall( urlopen('http://currencysource.ez-cdn.com/').read() )

if __name__ == '__main__':

   #print getCurrencies()
   if getXMLCur('eur'):
       print getCur('eur', 'usd', 1)

convercoins.py

# -*- coding: UTF-8 -*-
# @ author:  Mauro Pinto

import wx, os
import conversions

def isFloat(s):
   try: float(s)
   except: return False
   else: return True

class Window(wx.Frame):

   def __init__(self):

       wx.Frame.__init__(self, None, -1, 'ConverCoins', size=(300,130))

       panel = wx.Panel(self)

       self._fromChoices = wx.Choice( panel, choices=currencies, pos=(40,10) )
       self._fromChoices.SetSelection(0)

       self._toChoices = wx.Choice( panel, choices=currencies, pos=(200,10) )
       self._toChoices.SetSelection(1)

       self._convert = wx.Button( panel, pos=(10,50), size=(100,40), label='Convert!' )

       self._amount = wx.TextCtrl( panel, pos=(180, 50), style=wx.TE_RIGHT )
       self._amount.SetLabel('0')
       self._result = wx.TextCtrl( panel, pos=(180, 70), style=wx.TE_RIGHT )
       self._result.SetLabel('0')

       self._txt_from = wx.StaticText(panel, pos=(10,14), label='From:' )
       self._txt_to = wx.StaticText(panel, pos=(180,14), label='To:' )
       self._txt_from = wx.StaticText(panel, pos=(120,54), label='To Convert:' )
       self._txt_to = wx.StaticText(panel, pos=(120,74), label='Converted:' )

       self.Bind(wx.EVT_BUTTON, self.Convert, self._convert)

   def Convert(self, event):

       s1, s2 = self._fromChoices.GetSelection(), self._toChoices.GetSelection()
       amount = self._amount.GetLabelText()

       if isFloat(amount):

           amount = float(amount)

           if s1 == s2:

               amount = str( round( amount, 2 ) )
               self._result.SetLabel( amount )
               self._amount.SetLabel( amount )

           elif amount > 0:

               if conversions.getXMLCur( currencies[s1] ):

                   self._result.SetLabel( str( conversions.getCur( currencies[s1], currencies[s2], amount ) ) )
                   self._amount.SetLabel( str( round( amount, 2 ) ) )

       event.Skip()

if __name__ == '__main__':

   currencies = conversions.getCurrencies()

   if not os.path.exists( conversions.path ):
       os.mkdir( conversions.path )

   app = wx.PySimpleApp()
   frame = Window()
   frame.Show()
   app.SetTopWindow(frame)
   app.MainLoop()
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.