Flask Assets bundles not compiling when run under uWSGI - flask

They run normally when I run the flask app directly but don't compile or replace the address in the template when run under uWSGI.
How can I debug this?
EDIT:
code:
assets = Environment(app)
...
if __name__ == "__main__":
assets.register(YAMLLoader(os.path.join(DIR,"assets.yml")).load_bundles())
if os.environ.get("DEBUG_FLASK"):
app.run()
else:
app.run(debug=True)
assets.yml:
style_css:
filters: less
output: css/style.css
contents:
- css/style.less

Turns out uwsgi does its own thing with app variable to run the webapp and doesn't run the script as __main__ so
assets.register(YAMLLoader(os.path.join(DIR,"assets.yml")).load_bundles())
never got called. I moved it out of the
if __name__ == "__main__":
block. And it worked.

Related

Socket handshake error when using gunicorn

I have a flask app that processes a web socket stream of audio from Twilio.
The app works fine without gunicorn but when I start it with gunicorn I get only the first message of the socket (connect) and an unsuccessful handshake. Here is how the app looks:
from flask import Flask
from flask_sockets import Sockets
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi
...
app = Flask(__name__)
sockets = Sockets(app)
...
#sockets.route('/media')
def media(ws):
...
if __name__ == '__main__':
server = pywsgi.WSGIServer(('', HTTP_SERVER_PORT), app, handler_class=WebSocketHandler)
server.serve_forever()
When I start the app directly using python flaskapp.py it works ok.
When I start it using gunicorn by writing:
gunicorn -k flask_sockets.worker --bind 0.0.0.0:5055 --log-level=bug flaskapp:app
this is where the connection "hangs" and carries no further than the initial connection, apparently due to the handshake failing.
It's important to note that I haven't "gevent monkey patched" the code, but I'm not sure if it has anything to do with the problem.
Any idea will much be appreciated!
Don't have the ability to test this right now, but perhaps try with:
from flask import Flask
from flask_sockets import Sockets
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi
...
app = Flask(__name__)
sockets = Sockets(app)
...
#sockets.route('/media')
def media(ws):
...
server = pywsgi.WSGIServer(('', HTTP_SERVER_PORT), app, handler_class=WebSocketHandler)
if __name__ == '__main__':
server.serve_forever()
Then change the launch command to:
gunicorn -k flask_sockets.worker --bind 0.0.0.0:5055 --log-level=bug flaskapp:server
(Gunicorn should be importing the server object, which can't live within that final if statement, as that code only runs when launched with python directly).

Why do I get 404 when running Flask app on 0.0.0.0

I am testing my Flask app on AWS EC2 instance (Ubuntu).
Main app:
from sonip.api.factory import create_app
app = create_app()
def main():
app.run(debug=True, threaded=True)
if __name__ == "__main__":
main()
The actual set up of the Flask app is done in a factory including registering blueprint, etc.
def create_app():
app = Flask(__name__)
app.config['SERVER_NAME'] = settings.FLASK_SERVER_NAME
app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VALIDATE
app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER
app.config['ERROR_404_HELP'] = settings.RESTPLUS_ERROR_404_HELP
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://{}:{}#{}:{}/{}".format(
settings.DB_USER,
settings.DB_PASS,
settings.DB_HOST,
settings.DB_PORT,
settings.DB_NAME)
db.init_app(app)
blueprint = Blueprint('api', __name__, url_prefix='/api')
app.register_blueprint(blueprint)
return app
When I run python application.py and use curl -X GET http://localhost:5000/api, it returns the correct Swagger page. However, if I tried to run the app by specifying host=0.0.0.0 for external traffic, I got 404 for the same request.
(env) ubuntu#ip-172-31-18-136:~/aae$ python application.py
* Serving Flask app "sonip.api.factory" (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://localhost:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 948-062-124
127.0.0.1 - - [16/May/2018 18:07:24] "GET /api/ HTTP/1.1" 200 -
♥(env) ubuntu#ip-172-31-18-136:~/aae$ vi application.py
(env) ubuntu#ip-172-31-18-136:~/aae$ python application.py
* Serving Flask app "sonip.api.factory" (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://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 948-062-124
165.225.34.185 - - [16/May/2018 18:08:28] "GET /api/ HTTP/1.1" 404 -
Port 5000 is open to allow all inbound traffic in the security group. I tried a vanilla Flask app with just a few line of code, it worked just fine.
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True, port=8080, host='0.0.0.0')
This at least means 5000 is fine. Could it be the Blueprint or Swagger?
Setting SERVER_NAME and changing the host/port to something different in app.run() used to be a recipe for problems. At best, it's under-documented.
Try changing settings.FLASK_SERVER_NAME to 0.0.0.0:5000. Or if your app wants to be using cookies, try the trick of using something.dev:5000 and adding an entry for something.dev to your local /etc/hosts.

Running script with fixed internal commands arguments to include Qwebengine pepflashplayer

I made a PyQt5 QWebengine app i wanna make portable.
I found out that flash weren't working in the app.
After a lot of reading i found out that having pepflashplayer64_*.dll & manifest.json in folder
C:\Windows\System32\Macromed\Flash\ is working.
However i wanna ship the pepflashplayer with app, and
adding custom flash folder to PATH env var, do not have effect , or
sys.path.insert()
the command
myapp.py --ppapi-flash-path=C:\Flash\pepflashplayer64_27_0_0_187.dll
works , but how to pass extra augments internally when script is launched ?
i tried dirty hack to run sys.arg[0] script with extra command but no success.
if __name__ == "__main__":
# print sys.argv
flash = (' --ppapi-flash-path=C:\Flash\pepflashplayer64_27_0_0_187.dll').split()
# print flash
noooo = (sys.argv[0] + flash[0]).split()
import sys
app = QtWidgets.QApplication(noooo)
# ... the rest of your handling: `sys.exit(app.exec_())`, etc.
okay i got it to work so i can make app the app with browser portable , and solution was simpler than i thought.
Parsing second internal argument like this.
if __name__ == "__main__":
programname = os.path.dirname(sys.argv[0]) #get current script full folder path
pepperpflash = ' --ppapi-flash-path=' + programname + '/Flash/pepflashplayer64_27_0_0_187.dll'
try:
app = QtWidgets.QApplication(sys.argv + [pepperpflash])
except:
app = QtWidgets.QApplication(sys.argv)
# ... the rest of your handling: `sys.exit(app.exec_())`, etc.

uwsgi and flask - cannot import name "appl"

I created several servers, without any issue, with the stack nginx - uwsgi - flask using virtualenv.
with the current one uwsgi is throwing the error cannot import name "appl"
here is the myapp directory structure:
/srv/www/myapp
+ run.py
+ venv/ # virtualenv
+ myapp/
+ init.py
+ other modules/
+ logs/
here is the /etc/uwsgi/apps-avaliable/myapp.ini
[uwsgi]
# Variables
base = /srv/www/myapp
app = run
# Generic Config
# plugins = http, python
# plugins = python
home = %(base)/venv
pythonpath = %(base)
socket = /tmp/%n.sock
module = %(app)
callable = appl
logto = %(base)/logs/uwsgi_%n.log
and this is run.py
#!/usr/bin/env python
from myapp import appl
if __name__ == '__main__':
DEBUG = True if appl.config['DEBUG'] else False
appl.run(debug=DEBUG)
appl is defined in myapp/ _ init _ .py as an instance of Flask()
(underscores spaced just to prevent SO to turn them into bold)
I accurately checked the python code and indeed if I activate manually the virtualenvironment and execute run.py manually everything works like a charm, but uwsgi keeps throwing the import error.
Any suggestion what should I search more ?
fixed it, it was just a read permissions issue. The whole python app was readable by my user but not by the group, therefore uwsgi could not find it.
This was a bit tricky because I deployed successfully many time with the same script and never had permissions issues

After installing lpthw.web the does nothing

So, I am going over "Learn Python The Hard Way" and have an issue with Chapter 50 "Building my first website".
jharvard#appliance (~/Dropbox/Python/gothonweb): ls -R
bin docs gothonweb templates tests
./bin:
app.py
./docs:
./gothonweb:
__init__.py
./templates:
./tests:
__init__.py
Trying to run app.py file with command: $python bin/app.py It supposed to start the server but it does not do anything at all. It just return to a prompt again.
#app.py
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello world"
return greeting
if __name__ == "__main__":
app.run
I installed lpthw using pip first.
$pip install lpthw.web
When I run the file it gave me ImportError: no 'web' exists
So I installed webpy myself using with help of http://webpy.org/install
And now I'm getting no result at all.
Python I am using is Python 2.7.8 : Anaconda 2.1.0 . So there must be no conflict. Any suggestions? Thank you.
So, I fixed it successfully but adding parenthesis to the function app.ru()
#app.py
....
greeting = "Hello world"
return greeting
if __name__ == "__main__":
app.run