0

I have a Flask app which will execute another python script in the background and fetch data from the database to be displayed to the user. The script fails as it cannot initialize the local variables.

FetchAPI.py

import FetchDataFor_P_NAME as fetch
from flask import Flask
app = Flask(__name__)

@app.route('/batch21')
def fetchBatch21Data():
    return fetch.main()

if __name__ == '__main__':
    app.run()

FetchDataFor_P_NAME.py

def main():
    '''some statements to fetch data using the start_date'''
    query = query.replace('?', "'" + start_date + "'")

if __name__ == '__main__':
    '''some statements'''
    start_date = '01-JAN-14 00:00'
    main()

Whenever I execute the Flask app and call the page /batch21 I get the following error:

query = query.replace('?', "'" + start_date + "'")
NameError: name 'start_date' is not defined

This is my first time working with an API in Python. I am not sure what I am missing here.

1 Answer 1

1

The if __name__ == '__main__': statement evaluate to True only if the script is the main one called, e.g launch via the console. So all the things happening under this condition are executed only if the script is the main one.

So, what happens here is that your variable start_date is never initialized when the function main() is called in your Flask app.

You can workaround by passing an argument to your function main(), e.g def main(start_date): and call it in your Flask App like so : fetch.main('01-JAN-14 00:00').

Sign up to request clarification or add additional context in comments.

2 Comments

Does flask run make name = main ?
@variable You should probably ask a new question. As it is, your question is a bit vague, but in most cases, flask run do not make __name__ == "__main__" . Look a the python doc for more information about __name__ and __main__.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.