0

When i am importing a file in a flask route first time when i hit the route the import works but second time and so on it doesn't work. My both files are in same directory main.

├── main
│   ├── main1.py
│   └── main2.py

main1.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return "hello"

@app.route('/call')
def call():
    #This is the import i am talking about
    import main2
    print("main1")
    return "call"

if __name__ == "__main__":
    app.run(debug =True, host='0.0.0.0',port = '5005')

main2.py

print("main2")

terminal output at http://0.0.0.0:5005/call (Hit the url 3 times we can see 3 outputs)

* Serving Flask app "main1" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5005/ (Press CTRL+C to quit)
 * Restarting with inotify reloader
 * Debugger is active!
 * Debugger PIN: 226-069-185
127.0.0.1 - - [30/Apr/2020 10:48:42] "GET / HTTP/1.1" 200 -
main2
main1
127.0.0.1 - - [30/Apr/2020 10:48:46] "GET /call HTTP/1.1" 200 -
main1
127.0.0.1 - - [30/Apr/2020 10:48:49] "GET /call HTTP/1.1" 200 -
main1
127.0.0.1 - - [30/Apr/2020 10:48:50] "GET /call HTTP/1.1" 200 -

First time output is as accepted where import is working we can see 'main2' printed but while hitting again and again import doesn't work i don't see 'main2' printed.

Ajay Chinni
  • 780
  • 1
  • 6
  • 24
  • yes perfectly solved my issue and understood it [How to prevent a module from being imported twice?](https://stackoverflow.com/questions/2029523/how-to-prevent-a-module-from-being-imported-twice) thanks to @Sergey Shubin – Ajay Chinni Apr 30 '20 at 06:45

1 Answers1

2

Problem is coming from the import command: when you import a file, this file is parsed and loaded: if you have a print statement like the one you have, this one will run while you import the file. It will be run only once, this is what you observe in your log.

You need to declare a function in main2.py and call this command in main1.py. It will be then run each time you make a call access.

Here is a working example:

# File main1.py
from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello_world():
    return "hello"


@app.route('/call')
def call():
    from main2 import function2
    return "Hello from " + function2()


if __name__ == "__main__":
    app.run(debug =True, host='0.0.0.0',port = '5005')
# File main2.py
def function2():
    return 'world2'
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
  • cool, This solution solved my problem but my I was looking for this [How to prevent a module from being imported twice?](https://stackoverflow.com/questions/2029523/how-to-prevent-a-module-from-being-imported-twice) thanks to @Sergey Shubin – Ajay Chinni Apr 30 '20 at 06:44