How can i use two waitress server for django app - python

I want to have 2 waitress servers for hosting django web application.One for serving statics and media files of django app and other for django on different ports.
I tried some thing like this and hit localhost:6003 in browser,but it is serving only static web page at 6003 and is not interacting with app running at 9090. what am i missing?
I have successfully deployed this app usig nginx-waitress architecture.But I want to deploy using waitress -waitress architecture.
app.py
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__,)
CORS(app)
main.py
from flask import Blueprint, send_from_directory
from waitress import serve
from app import app
#app.route('/stat/<path:filename>')
def static_file(filename):
return send_from_directory("D:/static/",filename)
#app.route('/med/<path:filename>')
def media_file(filename):
return send_from_directory("D:/media/",filename)
serve(app, host='localhost', port=6003)
runserver.py
from waitress import serve
from sarus_project.wsgi import application
if __name__ == '__main__':
serve(application, host = 'localhost', port='9090')

Related

Introducing flask_socketio to work with a simple already made flask application

I'm new to both Flask and flask-socketio.
I first made the tutorial app from Flask official docs.
And I follow this to make a simple chat app using flask-socketio.
What I need is the authentication system from Flask tutorial and the simple chat feature from the SocketIO tutorial.
The Flask tutorial runs the Flask app inside the create_app method in __init__.py.
__init__.py:
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
# ...
return app
The SocketiIO tutorial have only a main.py file that runs the SocketIO application.
main.py:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app)
#app.route('/')
def sessions():
return render_template('session.html')
# ...
if __name__ == '__main__':
socketio.run(app, debug=True)
I've been read a lot of questions about integrating flask-socketio with already made Flask application, but all of them try to integrate using a main.py file that you can put socketio.run() method to run inside the if __name__.
Is it possible to run both http server with socket server in the same app initializing the app from create_app method?
For people that reach this question, the creator of the package teaches how to deal with this issue here.
socketio = SocketIO()
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
# ...
socketio.init_app(app)
return app
It's just a matter of creating a global SocketIO object and starting after in creat_app.

Integrate multiple Dash apps into Flask

I`m trying to integrate multiple Dash apps into a Flask application, but not able to do so.
I was able to integrate one Dash app into Flask, using the following structure:
dashboard1.py
def create_dashboard(server):
dash_app = dash.Dash(server=server,
routes_pathname_prefix='/dash1/',
external_stylesheets=[dbc.themes.BOOTSTRAP],
)
....
return dash_app.server
init.py
from flask import Flask
from flask_assets import Environment
def create_app():
"""Construct core Flask application with embedded Dash app."""
f_app = Flask(__name__, instance_relative_config=False)
f_app.config.from_object('config.Config')
assets = Environment()
assets.init_app(f_app)
with f_app.app_context():
# Import parts of our core Flask app
from . import routes
from .assets import compile_static_assets
# Import Dash application
from .plotlydash.dashboard import create_dashboard
app = create_dashboard(f_app)
# Compile static assets
compile_static_assets(assets)
return app
routes.py
from flask import render_template, redirect
from flask import current_app as app
#app.route('/dash1')
def dash1():
return render_template('dash1.html', app_data=app_data)
app.py
from application import create_app
app= create_app()
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Everything is working fine with the first Dash app. I want to create another menu/tab in the application and integrate a second dash app. How could I do this? I have tried the following but it has not resulted successful. Only the link of the first app works.
dashboard2.py
def create_dashboard2(server):
dash_app = dash.Dash(server=server,
routes_pathname_prefix='/dash2/',
external_stylesheets=[dbc.themes.BOOTSTRAP],
)
....
return dash_app.server
init.py
from flask import Flask
from flask_assets import Environment
def create_app():
"""Construct core Flask application with embedded Dash app."""
f_app = Flask(__name__, instance_relative_config=False)
f_app.config.from_object('config.Config')
assets = Environment()
assets.init_app(f_app)
with f_app.app_context():
# Import parts of our core Flask app
from . import routes
from .assets import compile_static_assets
# Import Dash application
from .plotlydash.dashboard1 import create_dashboard
from .plotlydash.dashboard2 import create_dashboard2
app = create_dashboard(f_app)
app2 = create_dashboard2(f_app)
# Compile static assets
compile_static_assets(assets)
return app, app2
routes.py
from flask import render_template, redirect
from flask import current_app as app
#app.route('/dash1')
def dash1():
return render_template('dash1.html', app_data=app_data)
#app.route('/dash2')
def dash2():
return render_template('dash2.html', app_data=app_data)
app.py
from application import create_app
app, app2= create_app()
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
app2.run(host='0.0.0.0', debug=True)
Could you please help me with some pointer/indications of what I might be doing wrong?
To answer #mLstudent33's question about callbacks initialization in the comments - there is a good blog post about it - https://hackersandslackers.com/plotly-dash-with-flask.
I followed their instructions and this worked for me:
For example, dashboard1.py:
def create_dashboard(server):
dash_app = dash.Dash(
server=server,
routes_pathname_prefix='/dash1/',
external_stylesheets=[dbc.themes.BOOTSTRAP],
)
dash_app.layout = html.Div([
# ... Layout stuff
])
# Initialize callbacks after our app is loaded
# Pass dash_app as a parameter
init_callbacks(dash_app)
return dash_app.server
def init_callbacks(dash_app):
#dash_app.callback(
# Callback input/output
....
)
def update_graph(rows):
# Callback logic
# ...

Getting 404 not found on Flask app deployed on PythonAnywhere

I've rummaged through maybe 50 different answers to this and still I haven't manage to fix it... I'm pretty new to flask and python.
I have an app which was running great locally but I've struggled with deploying on python anywhere. Initially I had a few import modules issues, now it runs but doesn't return any html template, despite not seeing any other issue. The main issue I had was that it couldn't find the "routes" app from wsgi, and I sort of fixed adding the app = Flask(name) line on routes.py (the short blueprint object is not callable).
routes.py:
from flask import Blueprint, render_template, request, redirect, send_file
import pyqrcode
from pyqrcode import QRCode
import subprocess
from extensions import db
from models import Link
app = Flask(__name__)
short = Blueprint('short', __name__, url_prefix='/')
#short.route('/index')
def index():
return render_template('index.html')
init.py
from flask import Flask
from extensions import db
from routes import short
def create_app(config_file='settings.py'):
app = Flask(__name__)
app.config.from_pyfile(config_file)
db.init_app(app)
app.register_blueprint(short)
return app
wsgi.py
import sys
# add your project directory to the sys.path
project_home = u'/home/b297py/mysite'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
# import flask app but need to call it "application" for WSGI to work
from routes import app as application
For the purpose of testing, I've placed all the html templates both in the root directory and in the specific /template directory but it just didn't fix the issue.
In wsgi.py you are not calling create_app so you are never registering the blueprint. You should replace :
from routes import app as application
by something like :
from package_name import create_app
application = create_app()
(Example: https://www.pythonanywhere.com/forums/topic/12889/#id_post_50171)
Also as you mentioned, the fix adding app = Flask(__name__) to routes.pyallows you to bypass create_app (so you should remove it if you want to stick to the create_app approach).

Flask-Restful 404 when api is started in __init__.py

I am using Twilio's flask.ext.restful extension with the following setup:
Top level folder is app
Inside of which is: ___init___.py:
from flask import Flask
from flask.ext import restful
# Basic app configuration
app = Flask(__name__)
api = restful.Api(app)
and inside this app module a file called api.py
from flask.ext.restful import Resource
from app import api
class HelloWorld(restful.Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/hello')
This setup just gives me 404s when accessing /hello
However, if I move the api.py to the __init__.py model then everything works.
Why is this the case?
I think the app gets ran before api.py gets executed and it hangs on Flask. How are you executing this?
class HelloWorld(restful.Resource)
should be
class HelloWorld(Resource)
however
Try transferring from app import api to your __init__.py
from flask import Flask
from flask.ext import restful
# Basic app configuration
app = Flask(__name__)
api = restful.Api(app)
from app import api
Also, you should rename one of the app to avoid confusion.

Circular imports on python app

I'm beginning to learn python and I'm following this tutorial on setting up Flask, but I'm having some trouble understanding the author in how he lays out his files. From what I can gather, it seems like I'm running into a circular import problem and I can't trouble shoot it.
The files are set up as follows:
__init__.py
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = "something here";
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://app.db"
app.py
from flask import render_template, request, redirect, url_for, abort, session
from app import app
#app.route('/')
.... some stuff here
models.py
from flask.ext.sqlalchemy import SQLAlchemy
from app import app
db = SQLAlchemy(app)
class User(db.Model):
.... some stuff here
manage.py
#!/usr/bin/env python
from flask.ext.script import Manage, Shell, Server
from app import app
manage = Manager(app)
manager.add_command("runserver", Server())
manager.add_command("shell", Shell())
#manager.command
def createdb():
from app.models import db
db.create_all()
manager.run()
The first error is being unable to start the server through running manage.py runserver. I was able to do it initially until I switched the files around initialized the app within init.py (originally I had everything located in app.py). I receive an error saying -
ImportError: cannot import name app
That aside, if I eliminate init.py and get the server up and running, I can't create a database because I receive an error stating -
Import Error: no module named models when running manage.py createdb

Categories

Resources