I have the flask app serving in waitress in windows, I have logger info
app = Flask(__name__)
logging.basicConfig(level=logging.ERROR)
#app.route('/run', methods=['POST'])
def RunFunction():
…………codes...……..
app.logger.info("Log 1: Starting App on Port: {}".format(LISTEN_PORT))
…………...
If I run with flask, I get the logger info
if __name__ == '__main__':
app.run(debug=True,port=8080, threaded=True,use_reloader=False)
If I use in waitress
from waitress import serve
serve(app, host='0.0.0.0', threads=WAITRESS_THREADS, port=LISTEN_PORT)
I am not getting logger info in console
I tried
app = Flask(__name__)
logger = logging.getLogger('waitress')
logger.setLevel(logging.ERROR)
and logger codes as
logger.info("Log 1: Starting App on Port: {}".format(LISTEN_PORT))
This is not working
Also I tried
from paste.translogger import TransLogger
serve(TransLogger(app, setup_console_handler=True), host='0.0.0.0', threads=WAITRESS_THREADS, port=LISTEN_PORT)
This also not working, may I know how to get the logger info in waitress
Related
I wanted to host my flask app on a specific port but the method I am using is not working. What I did is assign the host and port properties in my socket.run(). When I go to the specified address the page doesn't load. Where did I go wrong and how can I properly host a flask app with specific ip address and port. Thanks in advance.
EDIT: when I run the app with python app.py it works but when I run it with flask run it doesn't work.
from flask import Flask, render_template, Response
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'blahBlah'
socket = SocketIO(app)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socket.run(app, host='127.0.0.1', port=7000)
As of Flask version 0.11, setting the port param will not take affect unless config variable SERVER_NAME is set and debug=True.
Your regular Flask app will be running on default (localhost:5000).
Therefore the code should look like:
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'blahBlah'
app.config['SERVER_NAME'] = '127.0.0.1:8000'
socket = SocketIO(app)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socket.run(app, debug=True)
See Flask ref for more information: flask API
Edit:
Above code example will work so forth your code is structured:
project
app.py
templates
index.html
To run the code say:
python app.py
Running the code with the flask tools (flask run) will run the app and not the SocketIO part.
The right way
The right way to run the code is to do like this:
from flask import Flask, render_template
from flask_socketio import SocketIO
def create_app():
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY='BlaBla'
)
socket = SocketIO(app)
#app.route('/')
def index():
return render_template('index.html')
return app
Then in the shell run:
export FLASK_RUN_PORT=8000
Now you can run the flask app with the flask command:
flask --app app --debug run
maybe u are hosting something else on that specific port or on that specific ip or try to replace the socket.run by app.run
I am building a API that uses flask. I am going to use uWSGI and NGINX in production. The API is working as it is, but I am trying to rebuild it to use classes. When I run it after I have build it as a class it gives me Internal Server Error.
The following files are working:
src/server.py
from flask import Flask
app = Flask(__name__)
#app.route("/ping")
def ping():
return "pong"
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
src/wsgi.py
from src.server import app
if __name__ == "__main__":
app.run()
When I try to build it as class then I get Internal Server Error
src/server.py
from flask import Flask
class Main:
app = Flask(__name__)
def __init__(self):
#self.app.route("/ping")
def ping():
return "pong"
if __name__ == "__main__":
main = Main()
main.app.run(host="0.0.0.0", debug=True)
src/wsgi.py
from src.server import Main
if __name__ == "__main__":
main = Main()
main.app.run()
I have this simple script with a Flask webserver. When I try to run the Python script, nothing happens, it just freezes.
I have already installed eventlet but this has not fixed the issue.
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__, static_folder="statics", template_folder="templates")
socketio = SocketIO(app)
#app.route("/")
def main():
return render_template('index.html')
#socketio.event
def connect(sid, environ):
print(sid, 'connected')
#socketio.event
def disconnect(sid):
print(sid, 'disconnected')
if __name__ == "__main__":
socketio.run(app)
How can I stop this script from freezing and make it serve the webpage?
I am not sure what you mean by 'it freezes' but if it means you don't get any output in the terminal for debugging, you can fix that by setting debug mode to true using:
socketio.run(app, debug=True)
I have written a Flask App as follows:
import logging
from flask import Flask, jsonify
from mongo import Mongo
app = Flask(__name__)
app.config.from_object("config.ProductionConfig")
# routes to a particular change and patch number
#app.route("/<project>/")
def home(project):
app.logger.info('testing info log')
Mongo_obj = Mongo(ip=app.config["DB_HOST"], port=app.config["DB_PORT"],
username=app.config["DB_USERNAME"],
.....................
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = '5000')
Now, the problem I face is, when I look at the logs of the Flask application, all I see is the following:
* Serving Flask app "service" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
172.16.40.189 - - [01/Oct/2019 14:44:29] "GET /abc HTTP/1.1" 200 -
172.16.11.231 - - [01/Oct/2019 14:44:29] "GET /abc HTTP/1.1" 200 -
............
Is there something specific that needs to be done in order to see the log message? Do I need to run the Flask App in debug mode?
If not in debug mode the default log level is WARNING. That's why you don't see your logs. If you'd like your logs to contain INFO level ones you must set it within the logger, eg:
app = Flask(__name__)
app.logger.setLevel(logging.INFO)
This is how I set log levels in our app. I use the create_app function to create a flask app with error handling logging & other necessary configurations. Here is the snippet:
from flask import Flask
import logging
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__)
app.logger.setLevel(logging.ERROR)
# Test Log levels
app.logger.debug("debug log info")
app.logger.info("Info log information")
app.logger.warning("Warning log info")
app.logger.error("Error log info")
app.logger.critical("Critical log info")
return app
app = create_app()
Output show only error and lower logs are visible for now
* Restarting with stat
[2022-12-12 17:38:39,375] ERROR in __init__: Error log info
[2022-12-12 17:38:39,375] CRITICAL in __init__: Critical log info
I get the below error when I try and start Flask using uWSGI.
Here is how I start:
> # cd ..
> root#localhost:# uwsgi --socket 127.0.0.1:6000 --file /path/to/folder/run.py --callable app - -processes 2
Here is my directory structure:
-/path/to/folder/run.py
-|app
-|__init__.py
-|views.py
-|templates
-|static
Contents of /path/to/folder/run.py
if __name__ == '__main__':
from app import app
#app.run(debug = True)
app.run()
Contents of /path/to/folder/app/__init__.py
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
#from flaskext.babel import Babel
from config import basedir
app = Flask(__name__)
app.config.from_object('config')
#app.config.from_pyfile('babel.cfg')
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.setup_app(app)
login_manager.login_view = 'login'
login_manager.login_message = u"Please log in to access this page."
from app import views
*** Operational MODE: preforking ***
unable to find "application" callable in file /path/to/folder/run.py
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (pid: 26972, cores: 1)
spawned uWSGI worker 2 (pid: 26973, cores: 1)
I had problems with the accepted solution because my flask app was in a variable called app. You can solve that with putting just this in your wsgi:
from module_with_your_flask_app import app as application
So the problem was simply that uwsgi expects a variable called application.
uWSGI doesn't load your app as __main__, so it never will find the app (since that only gets loaded when the app is run as name __main__). Thus, you need to import it outside of the if __name__ == "__main__": block.
Really simple change:
from app import app as application # for example, should be app
if __name__ == "__main__":
application.run()
Now you can run the app directly with python run.py or run it through uWSGI the way you have it.
NOTE: if you set --callable myapp, you'd need to change it from as application to myapp (by default uwsgi expects application
The uWSGI error unable to load app 0 (mountpoint='') (callable not found or import error) occured for me if I left out the last two lines of the following minimal working example for Flask application
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
app.run()
else:
application = app
I am aware that this already implicitly said within the comments to another answer, but it still took me a while to figure that out, so I hope to save others' time.
In the case of a pure Python Dash application, I can offer the following minimal viable code snippet:
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div( html.H1(children="Hello World") )
application = app.server
if __name__ == "__main__":
app.run_server(debug=True)
Again, the application = app.server is the essential part here.