HEX
Server: Microsoft-IIS/10.0
System: Windows NT ITPWINWEBSVR22 10.0 build 20348 (Windows Server 2022) AMD64
User: www.conferencesearch.co.uk (0)
PHP: 8.3.30
Disabled: NONE
Upload Files
File: D:/bin/scripts/python/prev/4/get_worldpay_exchange_rates.py
# (SS,11/06/14) Python script to lookup EUR and USD exchanges rates from WorldPay and save to common exchangerates table
# This is a replacement for exchange-rate-update.vbs and inc-exchange-rate-utils.asp which had stopped working

import urllib2
import datetime
import MySQLdb
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import email.utils

def fetch_page(AURL): 
  print_html(AURL)
  
  req = urllib2.Request(AURL, '',  {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64)'})
  response = urllib2.urlopen(req)
  the_page = response.read()
  return the_page      
      
def get_currency_worldpay(AURL):
    html = fetch_page(AURL)
    
    print_html("")
    print_html("=============================")
    print_html(html.replace("\n", "<br>"))
    print_html("=============================")
        
    lines = html.splitlines()
    
    found_usd = False
    found_eur = False
    
    for line in lines:
      if "=" in line:
        split_line = line.split("=")
        if split_line[0] == "GBP_USD":
          save_currency("WP", "USD", split_line[1])
          print_html("USD=" + split_line[1])
          found_usd = True
        elif split_line[0] == "GBP_EUR":
          save_currency("WP", "EUR", split_line[1])
          print_html("EUR=" + split_line[1])
          found_eur = True
        elif split_line[0] == "GBP_GBP":
          save_currency("WP", "GBP", split_line[1])
          print_html("GBP=" + split_line[1])    
          
    if not found_usd or not found_eur:
      set_alert(True) # signal alert if either USD or EUR not found
      
    print_html("=============================")      

def save_currency(ASource, ACurrencyCode, AExchangeRate):
    # save in history log table
    LSQL = 'INSERT INTO exchangeratelog SET \
        Source = "%s", CurrencyCode = "%s", \
        ExchangeRate = "%s", DateTime = NOW()' % (ASource, ACurrencyCode, AExchangeRate)   
    cur.execute(LSQL)
    
    # update currencies table if <> 0
    if AExchangeRate != "":
        LSQL = 'UPDATE exchangerates SET \
            ExchangeRate = "%s", LastUpdated = NOW() \
            WHERE Source = "%s" AND CurrencyCode = "%s"' % (AExchangeRate, ASource, ACurrencyCode)
        cur.execute(LSQL)
    else:
        set_alert(True) # signal alert if exchange is ""          

def set_alert(AAlert):
    global FAlert # required to modify a global 
    FAlert = AAlert
      
def get_alert():
    return FAlert

def print_html_header():
      print """<html>
<title>WorldPay Exchange Rates</title>
<style>
html, body, h1, h2, p {
  font-family: Courier New, Arial, Helvetica, sans-serif;
}
img {
  border: 0;
}
table {
  border-collapse: collapse;
}
table, th, td {
  border: 1px solid black;
}
td, th {
  padding: 5px;
  white-space: nowrap;
}
</style>
<body>
"""

def print_html_footer():
    print """</body>
</html>"""

def print_html(AText):
    print AText + "<br>"
      
def send_email_file(AFileName, ASubject, AFrom, ATo, ABcc):
    # Open a plain text file for reading.  For this example, assume that
    # the text file contains only ASCII characters.
    fp = open(AFileName, 'rb')
    # Create a text/plain message
    #msg = MIMEText(fp.read())
    html = fp.read()
    fp.close()
    
    msg = MIMEMultipart('alternative')

    # header    
    if get_alert():
        msg['Subject'] = 'ALERT!!! ' + ASubject
    else:
        msg['Subject'] = ASubject
    msg['From'] = AFrom
    msg['To'] = ATo
    msg['Date'] = email.utils.formatdate(localtime=True)
    if get_alert():       
        msg['X-Priority'] = '2'
    
    #* html = html.replace('\r\n', '<br>')
    part1 = MIMEText(html, 'html')
    msg.attach(part1)
            
    # send the messsage using localhost
    s = smtplib.SMTP('localhost')
    s.sendmail(AFrom, [ATo, ABcc], msg.as_string())
    s.quit()
     
LOG_FILE = 'get_worldpay_exchange_rates.log'
 
FAlert = False  # global used to set alert
 
# output all prints to file
f = open(LOG_FILE, 'w')
sys.stdout = f 
        
start = datetime.datetime.now()
print_html_header()
print_html('Started: ' + start.strftime('%Y-%m-%d %H:%M:%S'))
filename_date_suffix = start.strftime('%Y-%m-%d')

con = MySQLdb.connect(host='localhost', user='common', passwd='itpcommon123', db='common')
cur = con.cursor()

get_currency_worldpay('https://select.worldpay.com/wcc/info?op=rates&instId=90440')

cur.close()
con.close()

finish = datetime.datetime.now()
time_taken = finish - start
#print_html('')
print_html('Finished: ' + finish.strftime('%Y-%m-%d %H:%M:%S'))
print_html('Time taken: %0.3f seconds' % (time_taken.seconds + time_taken.microseconds / 1E6))
print_html_footer()

# set back to default out and close the opened log file
sys.stdout = sys.__stdout__
f.close()

# send the file as an email
send_email_file(LOG_FILE, 'WorldPay Exchange Rate Result', 'exchange_rate@cliftoncollectables.co.uk', 'contactforms@itpartnership.com', '')