Rishik Mani
Rishik Mani

Reputation: 498

Unable to execute python script from Flask

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.

Upvotes: 0

Views: 845

Answers (1)

Lescurel
Lescurel

Reputation: 11631

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').

Upvotes: 1

Related Questions