Python Dash server with waitress - python

I have a dashboard application written in Dash framework.
It also has a few Restful API's written using flask.
I am adding flask app to Dash server, as
import dash
import flask
import dash_bootstrap_components as dbc
flask_server = flask.Flask(__name__)
app = dash.Dash(__name__,server=flask_server, external_stylesheets=[dbc.themes.BOOTSTRAP])
And am running the server as
from dashboard import app
from waitress import serve
if __name__ == "__main__":
app.title = 'Litmus'
app.run_server(debug=False)
# serve(app,host="0.0.0.0",port=8050)
The above code works fine when I am using app.run_server(debug=False) but it throws excetion when I use waitress to run the server.
When I use following lines
#app.run_server(debug=False)
serve(app,host="0.0.0.0",port=8050)
I get following error
ERROR:waitress:Exception while serving /
Traceback (most recent call last):
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\channel.py", line 397, in service
task.service()
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\task.py", line 168, in service
self.execute()
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\task.py", line 434, in execute
app_iter = self.channel.server.application(environ, start_response)
TypeError: 'Dash' object is not callable
ERROR:waitress:Exception while serving /favicon.ico
Traceback (most recent call last):
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\channel.py", line 397, in service
task.service()
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\task.py", line 168, in service
self.execute()
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\task.py", line 434, in execute
app_iter = self.channel.server.application(environ, start_response)
TypeError: 'Dash' object is not callable

It's not working because you're passing the Dash app instead of the Flask app to serve.
So instead of this:
serve(app,host="0.0.0.0",port=8050)
pass the Flask app instance like this:
serve(app.server, host="0.0.0.0", port=8050)

Related

Dash background callbacks not working with SQLAlchemy

I'm using Dash 2.6.1 and trying to get Background Callbacks 2.6.1 to work with SQLAlchemy.
If I add from sqlalchemy import create_engine to the first example of the tutorial then click on the Run Job! button on the webpage I get the stack trace below.
from sqlalchemy import create_engine # This breaks Dash.
import time
import os
import dash
from dash import DiskcacheManager, CeleryManager, Input, Output, html
if 'REDIS_URL' in os.environ:
# Use Redis & Celery if REDIS_URL set as an env variable
from celery import Celery
celery_app = Celery(__name__, broker=os.environ['REDIS_URL'], backend=os.environ['REDIS_URL'])
background_callback_manager = CeleryManager(celery_app)
else:
# Diskcache for non-production apps when developing locally
import diskcache
cache = diskcache.Cache("./cache")
background_callback_manager = DiskcacheManager(cache)
app = dash.Dash(__name__)
app.layout = html.Div(
[
html.Div([html.P(id="paragraph_id", children=["Button not clicked"])]),
html.Button(id="button_id", children="Run Job!"),
]
)
#dash.callback(
output=Output("paragraph_id", "children"),
inputs=Input("button_id", "n_clicks"),
background=True,
manager=background_callback_manager,
)
def update_clicks(n_clicks):
time.sleep(2.0)
return [f"Clicked {n_clicks} times"]
if __name__ == "__main__":
app.run_server(debug=True)
Produces the following when run:
Dash is running on http://127.0.0.1:8050/
* Serving Flask app 'main'
* Debug mode: on
Process Process-3:
Traceback (most recent call last):
File "/Users/one/.pyenv/versions/live/lib/python3.9/site-packages/multiprocess/process.py", line 315, in _bootstrap
self.run()
File "/Users/one/.pyenv/versions/live/lib/python3.9/site-packages/multiprocess/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/Users/one/.pyenv/versions/live/lib/python3.9/site-packages/dash/long_callback/managers/diskcache_manager.py", line 179, in job_fn
cache.set(result_key, user_callback_output)
File "/Users/one/.pyenv/versions/live/lib/python3.9/site-packages/diskcache/core.py", line 796, in set
with self._transact(retry, filename) as (sql, cleanup):
File "/Users/one/.pyenv/versions/3.9.9/lib/python3.9/contextlib.py", line 119, in __enter__
return next(self.gen)
File "/Users/one/.pyenv/versions/live/lib/python3.9/site-packages/diskcache/core.py", line 710, in _transact
sql = self._sql
File "/Users/one/.pyenv/versions/live/lib/python3.9/site-packages/diskcache/core.py", line 648, in _sql
return self._con.execute
File "/Users/one/.pyenv/versions/live/lib/python3.9/site-packages/diskcache/core.py", line 623, in _con
con = self._local.con = sqlite3.connect(
sqlite3.OperationalError: disk I/O error
Is this a bug in Dash? How can I make it work?
Not sure if it works, but I think you can try the following things...
import sqlalchemy
sqlalchemy.create_engine()

Server Flask app with cheroot server results to error in HTTPServer.tick after each request

I'm trying to serve a Flask (v1.1.2) wsgi application using cheroot server of CherryPy (v18.6.0) and after each request executed via Postman or browser I'm getting the following exception in my console. I'm running python v3.8.5
Error in HTTPServer.tick
Traceback (most recent call last):
File "C:\myproject\venv\lib\site-packages\cheroot\server.py", line 1795, in serve
self.tick()
File "C:\myproject\venv\lib\site-packages\cheroot\server.py", line 2030, in tick
self.connections.expire()
File "C:\myproject\venv\lib\site-packages\cheroot\connections.py", line 107, in expire
for sock_fd, conn in timed_out_connections:
File "C:\myproject\venv\lib\site-packages\cheroot\connections.py", line 103, in <genexpr>
(sock_fd, conn)
File "C:\python\lib\_collections_abc.py", line 743, in __iter__
for key in self._mapping:
RuntimeError: dictionary changed size during iteration
Code as follows:
from cheroot.wsgi import Server
from flask import Flask
app = Flask(__name__)
#app.route("/", methods=["GET"])
def index():
return "Hello"
if __name__ == "__main__":
server = Server(bind_addr=("0.0.0.0", 3000), wsgi_app=app)
try:
server.start()
finally:
server.stop()
Any idea causing that exception and how we can resolve it?
This is a recent and acknowledged issue with cheroot, take a look to the cheroot GitHub Issue 312.

scheduling lambda function in zappa to stop instances

Here I am I created a flask application and deploying using zappa .
While deployment I am facing no module found exception but same python code it working offline below is my stop.app application
import boto3
from flask import Flask, request,Response, jsonify
app = Flask(__name__)
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
region = 'ap-south-1'
myins = ['i-043ae2fbfc26d423f','i-0df3f5ead69c6428c','i-0bac8502574c0cf1d','i-02e866c4c922f1e27']
#app.route('/', methods=['GET'])
def lambda_handler(event=None, context=None):
logger.info('Lambda function invoked index()')
ec2 = boto3.resource('ec2')
ec2client = boto3.client('ec2',region_name=region)
ec2client.stop_instances(InstanceIds=myins)
return 'Instances are stopped!!'
# if __name__ == '__main__':
# app.run(debug=True)```
Below is the error
alling tail for stage dev..
[1568791437587] No module named stop: ImportError
Traceback (most recent call last):
File "/var/task/handler.py", line 602, in lambda_handler
return LambdaHandler.lambda_handler(event, context)
File "/var/task/handler.py", line 245, in lambda_handler
handler = cls()
File "/var/task/handler.py", line 139, in __init__
self.app_module = importlib.import_module(self.settings.APP_MODULE)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named stop
Worth checking the way the zip file is created, Also check the uploaded zip if its in the correct format.
The lambda_hanlder should be at the base of the root of the zip.
User pip install -r requirements.txt -t .
Also just a small improvement move the ec2 connection outside of lambda_handler.
To start and stop the instance boto3 docs start and stop instance

Flask how to get config element from another file (for example: helper.py)

Good day.
I have one question. How to access a configuration item from another .py file
For example.
app/__init__.py
def create_app(config=None):
app = Flask(__name__, instance_relative_config=True)
app._static_folder = './static'
app.config.from_pyfile('flask.cfg')
app.app_context().push()
return app
wsgi.py
from app import create_app
from werkzeug.debug import DebuggedApplication
if __name__ == "__main__":
app = create_app()
application = DebuggedApplication(app, evalex=True)
app.logger.info("Debug status is: " + str(app.config['DEBUG']))
app.run(use_reloader=True, debug=True)
app/core/helper.py
from flask import current_app as app
def get_dir():
return app.config["PATH_CACHE_DIR"]
Try to call method app/core/cached.py
from flask_caching import Cache
from flask import current_app as app
from app.core.helper import get_dir
print get_dir()
So, i receive the following error
Traceback (most recent call last):
File "/home/stanislav/Python/mbgp/wsgi.py", line 1, in <module>
from app import create_app
File "/home/stanislav/Python/mbgp/app/__init__.py", line 4, in <module>
from app.core.cached import cache
File "/home/stanislav/Python/mbgp/app/core/cached.py", line 5, in <module>
print get_dir()
File "/home/stanislav/Python/mbgp/app/core/helper.py", line 14, in get_dir
return app.config["PATH_CACHE_DIR"]
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 51, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current applicat`enter code here`ion object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
Please tell me how to fix this, thank you very much.

Apache Web server using flask, deploying my web app

I have a small flask application, and I am trying to host in on my website. It works whenever I run it on my computer, and connect via localhost:5000/ but when I upload to my server, and run the python code, i get multiple errors. When it runs, it only runs on localhost, and can be connected to via the servers console, but when I try to specify that it is to be hosted on all public facing ip's, it says operation not permitted.
here is the terminal output
`/home/public]$ python app.py
Traceback (most recent call last):
File "app.py", line 14, in <module>
app.run(host='0.0.0.0', port=port, debug=True)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 841, in
run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line
717, in run_simple
s.bind((hostname, port))
File "/usr/local/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 1] Operation not permitted
`
my app.py
from flask import Flask, render_template, request
import time
app = Flask(__name__)
port=33
#app.route("/")
def index():
x = int(round(time.time() * 1000))
return render_template("index.html", stylevar=x)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=port, debug=True)
if I connect via the domain name, and navigate to /templates, my index.html file will show, but it wont be running the python code.
Would really appreciate any direction on how to get it to be connected to from the browser. I understand that flask is not meant for production environments, but this is just a small personal project. If there are any other environments other than flask this could be accomplished in, I am willing to try something else.
The script does not have the rights for running with a port below of 1024. If you really need to use port 33 you have to run the script as root.

Categories

Resources