Python program seems to be running twice [duplicate] - python

This question already has answers here:
How to stop Flask from initialising twice in Debug Mode? [duplicate]
(2 answers)
Closed 8 years ago.
I have a python program which is running Flask. I noticed a strange thing, it looks like the program is running twice, which I do not want.
Here is the file for starting the program(runserver.py, in the root folder /):
from myapp import app
if __name__ == "__main__":
print "woho"
app.run(host='0.0.0.0',debug=True)
When running this, I can see two "woho" in the terminal, indicating that something is strange.
in the folder /myapp I have __init__.py:
from flask import Flask
app = Flask(__name__)
import myapp.views
and then in my views.py (also in /myapp) I have all the views like:
from myapp import app
from flask import render_template
#app.route('/')
def index():
return render_template('index.html')

it's due to the reloader of flask/werkzeug, which reloads automatically when you change the code.
so give debug=False if you don't want/need that, e.g. for "production".
How to stop Flask from initialising twice in Debug Mode?

Related

How do I run a Flask application directly in the browser? [duplicate]

This question already has answers here:
How can I open a website in my web browser using Python?
(10 answers)
Closed 1 year ago.
I want to start my Flask application directly in the browser when I run my Python file. I now just copied the localhost address into my browser and started it that way. Is it possible to do it without copying the link every time?
Try this:
import webbrowser
from flask import Flask
app = Flask(__name__)
#your staff
#app.route("/")
def hello():
return("Hello World!")
def open_browser():
webbrowser.open_new('http://127.0.0.1:5000/')
if __name__ == "__main__":
# the command you want
open_browser()
app.run(port=5000)
Use the webbrowser module:
import webbrowser
webbrowser.get("google-chrome").open("https://www.bing.com")
You can replace 'google-chrome' with another browser you would like.

Flask Python - basic program does not work

I wrote this super basic application. It runs but does not do a thing:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def Index():
return "<h1>Hello!</h1>"
if __name__ == "__name__":
app.run(debug=True)
The console shows:
C:\Users\TalT\PycharmProjects\FlaskBeginners\venv\Scripts\python.exe
C:/Users/TalT/PycharmProjects/FlaskBeginners/MyFirstWebPage.py
Process finished with exit code 0
I work on Win10, PyCharm 2019.3.3 and Python 3.7 .
I don't understand where is the problem? Is it a python issue or maybe project configuration?
Your problem is:
if __name__ == "__name__":
Must change to:
if __name__ == '__main__':
To start a flask app you have 2 easy different ways.
1. Rename your main file to app.py or wsgi.py and go to path of the file in terminal and type flask run. In this way, if you want to run app in debug mode, In the same path, type set FLASK_ENV=development in terminal (Windows) and then write flask run.
Tip: In this way, you must delete the following code from your project:
if __name__ == '__main__':
app.run()
2. Write your code in a python file (name is not matter) for example with main.py name write like this:
from flask import Flask
app = Flask(__name__)
app.config['DEBUG']=True
#app.route('/')
def Index():
return '<h1>Hello!</h1>'
if __name__ == '__main__':
app.run()
And run the application by running this command in the path of your file: python main.py . Remember, add this code app.config['DEBUG']=True only if you want to run your code in debug mode.

How do I use Flask.route with Flask

A brief introduction to the directory structure is as follows:
__init__.py contain the application factory.
page.py
from app import app
# a simple page that says hello
#app.route('/hello')
def hello():
return 'Hello, World!'
app.py
from flaskr import create_app
app = create_app()
if __name__ == '__main__':
app.run()
When I start the server and go to the '/hello', it says 404.
What's the problem?
Here is a short solution which should run.
page.py
from flaskr import app
#app.route('/hello')
def hello():
return 'Hello'
__index__.py
from flask import Flask
app = Flask(__name__)
from flaskr import page
app.py
from flaskr import app
To run this you just need to define a Environment Variable on the Commandline like this:
export FLASK_APP=microblog.py
And then run it with
flask run
The way you have structured your code is not right. That's the reason you are not able to access your "/hello" API.
Let's assume that you run the app.py file. In this case, you haven't imported page.py right? So, how will the app.py know that there is a route defined in page.py?
Alternatively, let's assume you run page.py. In this case, when you do an "from app import app" , the main definition does not get executed. Here too, the route will now be present, but the app will not be run, thereby you will be unable to access your API.
The simplest solution would be to combine the contents of app.py and page.py into a single file.

Flask not finding routes in imported modules

I'm having a problem with Flask wherein routes declared in imported modules are not be registered and always result in a 404. I am running the latest version Flask on Python 2.7.
I have the following directory structure:
run.py has the following code:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
import views.home
if __name__ == '__main__':
app.run()
home.py has the following code:
from run import app
#app.route('/test')
def test():
return "test"
When I run run.py the route declared in home.py (http://localhost:5000/test) always returns a 404 even though run.py imports views.home. The root view (http://localhost:5000) declared in run.py works fine.
I have written a function that prints out all the registered routes and /test is not in there (get a list of all routes defined in the app).
Any idea why?
I have discovered that switching the import statement in run.py from
import views.home
to
from views.home import *
makes everything work, which gave me the clue as to why the modules are not being registered using import views.home.
Basically, when run.py is run as a script it is given the name __main__ and this is the name given to the module in sys.modules (Importing modules: __main__ vs import as module)
Then when I import app from run.py in views.home.py a new instance of run.py is registered in sys.modules with the name run. As this point, the reference to app in run.py and views.home.py are two different references hence the routes not being registered.
The solution was to move the creation of the app variable out of run.py and in to a separate python file (I called it web_app.py) that is imported into run.py. This guarantees that the Flask app variable declared inside web_app.py is the always referenced correctly wherever web_app.py is imported.
So run.py now looks like this:
from web_app import app
if __name__ == '__main__':
app.run()
and web_app.py looks like this:
from flask import Flask
app = Flask(__name__)
import view.home
You can do it by reorganizing your code as it is described here Larger Applications, but it is more recommended to divide them into smaller groups where each group is implemented with the help of a blueprint. For a gentle introduction into this topic refer to the Modular Applications with Blueprints chapter of the documentation.
Modular Applications with Blueprints

Flask app does not use routes defined in another module

I can't get it to work to use one module that creates the Flask application object and runs it, and one module that implements the views (routes and errorhandlers). The modules are not contained in a Python package.
app.py
from flask import Flask
app = Flask('graphlog')
import config
import views
if __name__ == '__main__':
app.run(host=config.host, port=config.port, debug=config.debug)
views.py
from app import app
#app.route('/')
def index():
return 'Hello!'
config.py
host = 'localhost'
port = 8080
debug = True
I always get Flask's default "404 Not Found" page. If I move the contents of view.py to app.py however, it works. What's the problem here?
You have four modules here:
__main__, the main script, the file you gave to the Python command to run.
config, loaded from the config.py file.
views, loaded from the views.py file.
app, loaded from app.py when you use import app.
Note that the latter is separate from the first! The initial script is not loaded as app and Python sees it as different. You have two Flask objects, one referenced as __main__.app, the other as app.app.
Create a separate file to be the main entry point for your script; say run.py:
from app import app
import config
if __name__ == '__main__':
app.run(host=config.host, port=config.port, debug=config.debug)
and remove the import config line from app.py, as well as the last two lines.
Alternatively (but much uglier), use from __main__ import app in views.py.

Categories

Resources