Newbie help - Currency calculator with Python
Tags: beginners, programming, python, issue
Published: 2022-02-14 08:50:46

Hello I am newbie in Python and from a Company send me a task to solve it.

Application Programming Task

The task is to implement an API that will have retrieve, store and expose currency exchange rates. All endpoints should use a database of your choice as a persistence layer. The following endpoints are needed: - POST - /register (No Auth needed) This endpoint should accept username, password, confirmPassword in JSON format. After validating the input it should create and persist a user in the DB. - POST - /login (No Auth needed) This endpoint should accept username, password in JSON format. After validating the input and checking that user exists and password is correct should return a Json Web Token (JWT) that should
be used to communicate with the other 2 endpoints of the API. - POST - /seed (Needs Authentication) This endpoint should use a free currency API of your choice. (e.g: https://freecurrencyapi.net/). Keep in mind that you will need to potentially register with this API to use it and also respect potential request rate limits. When called it should retrieve the exchange rates for all currencies with EUR, USD, CHF andGBP as base currency respectively. e.g. {base: EUR, currencies: [{ EUR: 1, USD: 0.86, CAD: 1.23, SGD: 2.7 ... }} // Base EUR {base: USD, currencies: [{ EUR: 1.23, USD: 1, CAD: 0.67, SGD: 8.2 ... }} // Base USD .... The exchange rates should then be persisted in the database using a schema that makes
sense. - GET - /rates/{base} (Needs Authentication) This endpoint should return all exchange rate from the database in both JSON and XML format. It should support pagination and sorting alphabetically or by exchange rate. - GET - /rates/{base}/{target} (Needs Authentication)
Should return the particular exchange rate. - POST - /rates/{base}/{target} (Needs Authentication) Should create / update the particular exchange rate. In order to be able to discover, test and understand the API make sure it utilizes the OpenAPISpecification (Swagger) which will automatically create a UI interface that will serve as API documentation and testing bed.

Ι'm not sure if i started right and I am trying many hours but I would like your help.
Thanks in advance

Below is the code:
`print "Content-type:text/html"
print ""

import requests
import getpass
import json
import argparse
from datetime import date
import time

This is a short program to hit an api (freecurrencyapi.net) , pull conversions on dates from a csv
and save the output in json format. the input csv should be a list of dates YYYY-MM-DD.
The program will need an api key, which can be obtained from freecurrencyapi.net
sample url https://freecurrencyapi.net/api/v2/latest?apikey=ccc0b100-8a55-11ec-8276-b71d1ddd6a9b
def callAPI(sourcelist, sourcecurrency, destcurrency):

jsonlist = [] 

APIKEY=getpass.getpass(prompt="ccc0b100-8a55-11ec-8276-b71d1ddd6a9b (hidden)")
URLBASE='https://freecurrencyapi.net/dashboard'
    for date in sourcelist:

            url=f'{URLBASE}?access_key={APIKEY}&date={date}&currencies={sourcecurrency},{destcurrency}&format=1c'
            convert=requests.get(url)
            jsonlist.append(convert.json())
            time.sleep(1) 

return(jsonlist)
print("Exchange Rates via 'https://freecurrencyapi.net/'")

sourcepath='e:/dougsprogs/exchangerates/'
jsonfile=''
csvfile=''
today = date.today()
sourcecurrency=''
destcurrency=''
sourcelist = []
jsonlist=[]

inputargs=argparse.ArgumentParser(description='This is a short program to hit an api \
(/freecurrencyapi.net) , pull conversions on dates from a csv \
and save the output in json format. ',
epilog='the input csv should be a list of dates YYYY-MM-DD.\
The program will need an api key, which can be obtained from api.currencylayer.com .')

inputargs.add_argument('-c', help='conversion request, source-destination, default AUD-USD')
inputargs.add_argument('-d', help='date in YYYY-MM-DD , for a single day conversion')
inputargs.add_argument('-l', help='csv file for input with a list of dates, YYYY-MM-DD')
inputargs.add_argument('-j', help='json file to save output')
inputargs.add_argument('-p', help='file path for both input and output files')

cliargs = inputargs.parse_args()
currencies = cliargs.c
sourcedate = cliargs.d
sourcelist = cliargs.l

if cliargs.p:
sourcepath = cliargs.p
if cliargs.j:
jsonfile = cliargs.j

if currencies:
sourcecurrency,destcurrency = currencies.split('-')

else:
sourcecurrency = 'AUD'
destcurrency = 'USD'

if not sourcedate and sourcelist:
with open((sourcepath + sourcelist), 'r' ) as sourcefile:
sourcein = sourcefile.read()

    sourcelist = sourcein.split()
elif sourcedate:

sourcelist = [str(sourcedate)]
else:
sourcelist=[str(today)]

print("no csv or date provided")
print(f"source list is {sourcelist}")
print(f"source list type is {type(sourcelist)}")

jsonlist = callAPI(sourcelist, sourcecurrency, destcurrency)

if jsonfile:
print(f"writing json file {jsonfile}")
with open((sourcepath + jsonfile + '.json'), 'a') as fileout:
for element in jsonlist:
json.dump(element,fileout)
print(element)
print(f"filename-path will be {sourcepath + jsonfile + '.json'}")
else:
print("no json filename")

for element in jsonlist:
print(element)`