App initializes twice. Is this typical behavior? [duplicate] - python

This question already has answers here:
Why does running the Flask dev server run itself twice?
(7 answers)
Closed 4 years ago.
I'm currently testing a socket io app and I'm noticing unusual behavior.
In my init python script I'm declaring a function that instantiates a flask object and initializes it via a socketIO instance (which is global) i.e. (assuming all of these files are within the same directory scope):
#/test_app/configs/__init__.py
__socketIO__ = SocketIO()
def create_app(address, port):
app = Flask(__name__, static_url_path='')
app.config.from_pyfile('config.py')
__socketIO__.init_app(app)
return app
in another python script:
#/test_app/run_app.py
from configs import create_app
from configs import __socketIO__ as launch_socket
ip_address = '0, 0, 0, 0'
port = 5000
APP = create_app(ip_address, port)
if __name__ == '__main__':
print 'launching....'
launch_socket.run(APP, debug=True, host=ip_addres, port=port)
Given this, if I run run_app.py, 'launching...' will print twice.
Is this behavior typical? Granted I'm still learning my way around socket.io so perhaps I'm missing some point to it. It just seems odd that it initializes twice. Is there a way to circumvent this behavior if it's unnecessary or detrimental?
Thanks!

This is normal when you run in debug mode. Flask launches two processes, one for watching the code for changes and one for the actual flask process.

Related

Serving dynamic files on heroku?

I have a flask app that has two threads. One modifies flask templates to keep them up to date from scraped info, and the other is the flask server that takes incoming route requests.
from flask import Flask, render_template
import threading
import RunArbIfDown
app = Flask(__name__, static_url_path='')
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
threading.Thread(target=app.run).start()
threading.Thread(target=RunArbIfDown.start).start() # this line continuously updates index.html (every 60s)
When I check the app, index.html is never updated even though there seem to be no errors. Are we allowed to modify files on the heroku dyno? Are there any good solutions for this?
Running threads in a WSGI environment might yield unexpected results. The WSGI server usually manages threads and can create and kill them at any time.
Also you have protected your threading code with a __name__ condition. The code will execute if the file is started directly. A WSGI server will not do that. It will import the file and the the condition will not be met.
A typical way to run recurring tasks in Flask is to use a custom command via cron. It is run as a separate process.

Add Flask routes to a class's methods [duplicate]

This question already has answers here:
Extending Flask class as main App
(1 answer)
Python3 Flask - missing 1 required positional argument: 'self'
(1 answer)
Closed 5 years ago.
I'm trying to write a server to manage some data and serve webpages. I'd like to use Flask, the Python web framework.
I can easily set up a "static" Flask app that serves a page for fixed data, doing something like
from flask import Flask, render_template
DATA = [1, 2, 3]
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
#app.route('/')
def index():
return render_template('mytemplate.html', data=DATA)
if __name__ == '__main__':
app.run()
but what I'd like is a "dynamic" app, with a Server which manages changing data. I'd like the Server to serve the most current data when a page is opened. So I'd like to do something like the following:
from flask import Flask, render_template
app = Flask(__name__)
class Server():
def __init__(self, data):
self.data = data
###
### Other long-running methods which might update self.data
###
#app.route('/') # <--- causes an error
def index(self):
return render_template('mytemplate.html', data=self.data)
if __name__ == '__main__':
s = Server([1, 2, 3])
### Spawn long-running methods
app.run()
However, doing this raises an error:
TypeError: index() takes exactly 1 argument (0 given)
I've seen that I can achieve what I want by wrapping my methods in Flask routes outside the class definition, after instantiating my server, by doing this:
if __name__ == '__main__':
s = Server([1, 2, 3])
### Spawn long-running methods that might update s.data
app.route('/')(s.index)
app.run()
but this seems exceptionally messy! It would be so much clearer and more logical if the routes were attached to the actual methods I'd like to use to serve the pages.
So my question is: is there a way to add Flask routes directly to methods inside a class?
Many thanks in advance

python local host http://127.0.0.1:5000/ not refreshing to new request from flask [duplicate]

This question already has answers here:
Auto reloading python Flask app upon code changes
(14 answers)
Closed 5 years ago.
At the first time when I'm running the below code in Python, it's succesfully running in localhost by displaying hello, I'm using the atom editor.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_wrld():
return "hello"
if __name__ == '__main__':
app.run()
But when I'm changing my return to hello python as follows:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def dhineTrend():
return "hello python"
if __name__ == '__main__':
app.run()
It's running in localhost but when I'm hitting the browser it keep on showing old hello. How to overcome it?
Note: After first run I cut the run, then only request the second.
Enable DEBUG to auto reload files on change,
app = Flask(__name__)
app.debug = True
There are multiple ways to do this,
app.config.update(DEBUG=True)
Or
app.config['DEBUG'] = True
Or, Create a config.py defining all the Flask settings
app.config.from_object('config')

How to use variables created in gunicorn's server hooks?

I am using gunicorn to run my Flask application. I would like to register server hooks to perform some action at the start of the application and before shutting down, but I am confused on how to pass variables to these functions and how to extract variables created within them.
In gunicorn.conf.py:
bind = "0.0.0.0:8000"
workers = 2
loglevel = "info"
preload = True
def on_starting(server):
# register some variables here
print "Starting Flask application"
def on_exit(server):
# perform some clean up tasks here using variables from the application
print "Shutting down Flask application"
In app.py, the sample Flask application:
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.route('/hello', methods=['POST'])
def hello_world():
return jsonify(message='Hello World')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000, debug=False)
Running gunicorn like so: $ gunicorn -c gunicorn.conf.py app:app
A bit late, but you have access to the flask application instance through server.app.wsgi(). It returns the same instance used by the workers (the one that is also returned by flask.current_app).
def on_exit(server):
flask_app = server.app.wsgi()
# do whatever with the flask app
Put the data you need to pass to the hooks into environment variables.
You can also store the data to be passed to the hooks and from them in files.
What are you trying to achieve is not possible due to the wsgi interface and the way the state is managed between requests.

Threaded Flask application not working as expected

I want my flask application to be able to process more than one call at the same time.
I've been testing running with threaded=True or processes=3 with the code below but when I make two calls to the server the later always have to wait for the first one to complete.
I know that it's recommended to deploy the application on a more sophisticated WSGI container but for now I just want my small app to be able to process 2 calls at once.
from flask import Flask, Response, stream_with_context
from time import sleep
app = Flask(__name__)
def text_gen(message):
for c in message:
yield c
sleep(1)
#app.route("/")
def hello():
stream = text_gen('Hello World')
return Response(stream_with_context(stream))
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True, threaded=True)
#Lukas was right.
I was debugging in Google Chrome with two tabs. Apparently Chrome is trying to be smart by using the socket same for both tabs. How Chrome handles that can be changed with the -socket-reuse-policy flag when starting Chrome.
An easier way to test is by using different hostname in each tab or by using curl -N (-N flag for no buffer to see the streaming). Doing that it did indeed work as expected.

Categories