flask socketio not starting - python

Trying to get a flask socketio app going.
Here's my init.py
import os
from flask import Flask, logging
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from config import app_config
database = SQLAlchemy()
socket_io = SocketIO()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
database.init_app(app)
socket_io.init_app(app)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
return app
and here is my run.py
#!/usr/bin/env python3
import sys
from app import create_app, socket_io
config_name = sys.argv[1]
app = create_app(config_name)
if __name__ == "__main__":
socket_io.run(app)
When I start up the app, this is the log output in the python console:
C:\AnacondaPython\python.exe D:/workspaces/App/run.py development
* Restarting with windowsapi reloader
* Debugger is active!
* Debugger PIN: 189-233-458
And then nothing happens.
When I open the app in the browser, it just keeps loading.
How do I do this correctly?
I'll provide more code if necessary.
Thanks for any help and tips!

Related

unable to host flask app on a specific ip and port

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

Why am I instantiating two different queues?

I'm trying to set-up an application which will receive HTTP GET's and POST's using python and flask-restful. The problem that I'm getting is that when I start the application I see that there are two instances of a queue being generated. I would like you to help me understand why?
Application output (terminal):
<queue.Queue object at 0x10876fdd8>
* Serving Flask app "main" (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://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
<queue.Queue object at 0x10ce48be0>
* Debugger is active!
* Debugger PIN: 292-311-362
Python code (ran with the following command python -m main):
import json
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
import requests
import os
import threading
import queue
import sys
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument("endpoint")
queue = queue.Queue()
base_path = os.path.dirname(os.path.realpath(__file__))
config = Json_Parser().get_json_object(base_path + "path")
consumer = Consumer(config, queue)
t1 = threading.Thread(target=consumer.consume)
t1.start()
class Interaction(Resource):
def get(self):
self.create_interaction()
thread_queue = consumer.get_queue()
output = thread_queue.get()
return output
api.add_resource(Interaction, '/interaction')
if __name__ == '__main__':
print(queue)
app.run(debug=True)
With the help of #Richar de Wit I changed the following line:
app.run(debug=True)
to:
app.run(debug=True, use_reloader=False)
to prevent the debugger to instantiate two queues thus giving issues later on.
The problem is referenced in this question:
Why does running the Flask dev server run itself twice?

ModuleNotFoundError: No module named '__main__.web_app'; '__main__' is not a package while importing package from sub folder

I'm getting above error while running my app. I want to import app from web_app/init.py into run.py file to run on gevent. My project structure is like:
myapp
|---config.ini
|---run.py
|---web_app
|----__init__.py
run.py
from gevent.pywsgi import WSGIServer
import configparser
from .web_app import app
# from web_app.__init__ import app
config = configparser.ConfigParser()
config.read('C:/workspace/Python/myapp/config.ini')
PORT = config.get('SERVER', 'PORT')
PORT = int(PORT)
if __name__ == '__main__':
print('Serving on port ', PORT)
WSGIServer(('localhost', PORT), app).serve_forever()
__init.py
from flask import Flask
app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/myapp'
logger = log_configuration.get_logger(__name__)
def simple(env, resp):
resp(b'200 OK', [(b'Content-Type', b'application/json')])
return [b'Hello Verimed User']
#app.route('/test', methods=['GET'])
def test():
return jsonify({'tasks': "task"})
If I keep run.py beside init then it's working fine. But I want to keep run.py outside web_app folder.
How to rosolve this. I tried all the way.
Have you tried it without the "." in front of "web_app"?
from web_app import app
You can find some more info in the following link: relative imports
I resolved above problem after added following code into the run.py.
import sys
sys.path.append('../web_app')
sys.path.insert(0,'./web_app')

Flask app not running on development configuration

i am running a flask application, the app is running but not following the configurations i have set.This is the config file
import os
class Config(object):
"parent configuration class"
DEBUG= True
class DevelopmentConfig(Config):
"Configurations for Development"
DEBUG = True
connectionVariables="dbname='store-manager' user='postgres' password="1235" host='localhost' port='5432'"
os.environ['ENVIRONMENT']='development'
class TestingConfig(Config):
"""Configurations for Testing,"""
TESTING = True
DEBUG = True
connectionVariables="dbname='store-manager-test' user='postgres' password="1235" host='localhost' port='5432'"
os.environ['ENVIRONMENT']='testing'
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig
}
Whenever i run the app it runs on testing mode even when i have specified development, however, if i remove the testing configuration, it runs on development environment.
This is how am creating the app
from flask import Flask
from flask_restful import Api
from instance.config import app_config
from connection import DbBase
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(app_config[config_name])
return app
This is how am running it.
import os
from app import create_app
config_name = 'development'
app = create_app(config_name)
# method to run app.py
if __name__ == '__main__':
app.run()
Depending on how you're actually running it and on what platform, you need to be sure to specify the location of the config.file.
export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
or for windows
set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
I'm not seeing it in the above description, so this may the the problem.
Flask Doc on using a config File

Flask and uWSGI - unable to load app 0 (mountpoint='') (callable not found or import error)

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.

Categories

Resources