'How to get value from csv with PYTHON and “with open ...” inside function?

I'm working on a simple currency calculator. Based on the data entered by the user, i.e. the currency code and its amount, I would like to return a value = AMOUNT * bid course.

The bid course is supposed to come from a csv file, previously downloaded using the appropriate API.

The file structure is the: fxcalculator.html + fxapi.py (in it a function for generating csv) + app.py (in it the "calculate" function that would return the searched value)+ FX.csv. Inside app.py I have:

@app.route("/calculate", methods=["post"]) 
    def calculate():
        currency_type = request.form["currencyType"]
        currency_amount = int(request.form["currencyAmount"]) 
        with open('FX.csv', newline='') as csvfile:
            reader = csv.DictReader(csvfile, delimiter =";") 
                for row in reader:
                    if row['currency']==currency_type:
                        course = int(row['bid'])
                        result=course*currency_amount
                    else:
                        return "There is an error"
        return render_template("fxcalculator.html", result=result)

The above code does not return the correct value - every time the else command is executed: "There is an error". Why “with open ...” doesn't work inside def calculate (): ?

1/ In the case when I tests the “with open ...” as a standalone object, and I assign string to “if row ['currency'] == ..” instead of “currency type:“ I get a reference value from csv.

import csv 

with open('FX.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile, delimiter =";") 
    for row in reader:
        if row['currency']=="jen (Japonia)":
            course = row['bid']
            print(course)

2/ In case “with open ...” is in the “def calculate” function and “if row ['currency'] == ...” is also assigned a string instead of “currency type”, I don't get the hijacked value - the function executes the conditional statement else.

Full code ( draft) is on the Github: https://github.com/LukaszRadominski/FXAPICalculator.git

Has anyone encountered such a problem? Thank you in advance for the hint.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source