Flask Request within request fails on production WSGI environment - apache

I am making a request within a request, in order to accommodate my service oriented design. Locally, this code works. However on production using ubuntu libapache2-mod-wsgi-py3, my nested request fails.
A key point is both services exist within the same <Virtualhost> on the server, so I suspect this is a threading issue.
The second request called within newitem() fails with ConnectionRefusedError(111, 'Connection refused') on my WSGI Ubuntu box even though the API endpoint functions as expected when I POST to it outside of this context (for example curl POST to the exact url).
Another important point is this request within reqest design works on my local when I have two separate flask apps running on different ports. I had this exact issue on my local until I ran the API server with --threaded flag.
My server is configured as follows:
app2.wsgi:
#!env/bin/python3
import sys, os
sys.path.append('/var/www/api_app')
from app import create_app
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
application = create_app(os.getenv('FLASK_CONFIG') or 'default')
if __name__ == "__main__":
manager.run()
apache2/sites-available/default.conf:
<VirtualHost *:80>
DocumentRoot /var/www/html
# ------ WSGI config ------
WSGIDaemonProcess app1 user=www-data group=www-data threads=5
WSGIDaemonProcess app2 user=www-data group=www-data threads=5
WSGIScriptAlias /front_end /var/www/front_end/app2.wsgi
WSGIScriptAlias /api_app /var/www/api_app/app2.wsgi
WSGIScriptReloading On
<Directory /var/www/api_app>
WSGIProcessGroup app2
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
<Directory /var/www/front_end>
WSGIProcessGroup app1
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
The following code works great on my local environment when I start the API service with the --threaded flag It fails on WSGI Apache2 on the requests.post() line.
#plant_material.route('/plant_material/new', methods=['GET', 'POST'])
def newitem():
form = PlantMaterialForm()
if form.validate_on_submit():
api_uri = current_app.config['API_SERVER_URI']
url = api_uri + "api/plant_material/new"
headers = {'Content-Type': 'application/json'}
print(request.form)
r = requests.post(url, data=json.dumps(request.form), headers=headers)
if r.status_code == 200:
return redirect(url_for('plant_material.index'))
elif r.status_code == 401:
flash('Whiteboard API Unauthorized')
elif r.status_code == 403:
flash('Whiteboard API Forbidden')
elif r.status_code == 500:
flash('Internal Server Error')
return render_template('plant_material/new.html', form=form)
How can I make a request within a request on my production server?

Apache and mod_wsgi take care of concurrency here; there is no reason for a well-formed request from one WSGI app to another on the same server to fail here.
Make sure that there is no firewall blocking requests to the server from localhost. Test the same URL from the command line with curl for example.
Triple-check your assumptions; use the live value of current_app.config['API_SERVER_URI'] when testing if your connections work, not what you assume it to be.
swap out HTTP methods; try running curl from a subprocess call, or use urllib2 to access the API

Related

Error 500 while deploying my Flask app with mo_wsgi on Ubuntu VPS

I am currently trying to deploy a very basic Flask app on my ubuntu VPS with mod_wsgi.
I followed this youtube tutorial as precisely as I could : https://www.youtube.com/watch?v=w0QDAg85Oow
But i ended up with a 500 error. Here is a sample from the logs :
mod_wsgi (pid=8283): Failed to exec Python script file '/var/www/flask-app/app.wsgi'.
mod_wsgi (pid=8283): Exception occurred processing WSGI script '/var/www/flask-app/app.wsgi'.
Traceback (most recent call last):
File "/var/www/flask-app/app.wsgi", line 5, in <module>
with open(activate_this) as file_:
PermissionError: [Errno 13] Permission denied: '/root/.local/share/virtualenvs/flask-app-yYmzn1cG/bin/activate_this.py'
The app.wsgi file :
import sys
sys.path.insert(0, '/var/www/flask-app')
activate_this = '/root/.local/share/virtualenvs/flask-app-yYmzn1cG/bin/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))
from app import app as application
The python app.py :
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
The flask-app.conf :
<VirtualHost *:80>
WSGIDaemonProcess flaskapp user=www-data group=www-data threads=5
WSGIScriptAlias / /var/www/flask-app/app.wsgi
<Directory /var/www/flask-app>
WSGIProcessGroup flaskapp
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
ErrorLog /var/www/flask-app/logs/error.log
CustomLog /var/www/flask-app/logs/access.log combined
</VirtualHost>
Screenshot from apache2 both /etc/apache2/sites-available and /etc/apache2/sites-enabled :
screenshot
As we can see in the logs it seems to be a permission error.
What I understood from the video and the flask documentation (https://flask.palletsprojects.com/en/2.0.x/deploying/mod_wsgi/) is that the server runs my app with the "www-data" user as we told him in the flask-app.conf :
WSGIDaemonProcess flaskapp user=www-data group=www-data threads=5
What i've tried for the moment is to run from root :
$ chown -R www-data:www-data /root/.local/share/virtualenvs
Because i created my pipenv virtual env with root, i tried to give the ownership from these to the www-data user.
But the error still remains...
I just begin with VPS, apache and Flask and I can't find a solution for this problem.
Any idea ?
UPDATE
I tried to create a new user called "arnaud", and i copied the "flask-app-yYmzn1cG" folder (containing the virtualenv) in /home/arnaud/flask-app-venv.
I changed the path of the "activate_this.py" in the app.wsgi file to point the new /home/arnaud/flask-app-venv/flask-app-yYmzn1cG/bin/activate_this.py.
I changed "user" and "group" to "arnaud" in the flask-app.conf.
...and this worked. No error this time and my app is running.
So the problem was for the user "www-data" to access the pipenv generated virtual env in the /root/ (owned by root) folder.
Have you confirmed that mod_wsgi actually runs as the www-data user? If you start the application from a non-privileged user (and without sudo), mod_wsgi won't be able to switch to the www-data user.
I can't say for mod_wsgi, but IIRC uwsgi would just silently just run as the invoking user if it didn't have the required permission to run it as the configured user.

Firebase from Flask deployment server

in development mode with Flask, I am successfully able to read and write data to Firestore using the firebase admin module. However, once I deploy the app on Apache 2 using mod_wsgi, everything works fine (firebase app initialization doesn't throw any error) until I start getting a document, where the code gets stuck and the page loads forever.
Flask function where the problem occurs in __init__.py:
#app.route('/users/<user>')
def login(user=None):
if not user:
abort(404)
userRef = db.collection('users').document(user)
print("1") # This runs.
userDoc = userRef.get() # The code gets stuck here. No error message is ever returned or stored in the error log.
print("2") # This never runs.
flaskapp.wsgi
#!/usr/local/bin/python3.8
import sys
import os
import logging
logging.basicConfig(stream=sys.stderr)
os.chdir("/var/www/html/example.com/FlaskApp/")
sys.path.insert(0,"/var/www/html/example.com/FlaskApp/")
from __init__ import app as application
example.com.conf
LoadModule wsgi_module "/home/username/.local/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so"
WSGIPythonHome "/usr/local"
<VirtualHost *:80>
# Admin email, Server Name (domain name), and any aliases
ServerAdmin username#example.com
ServerName example.com
ServerAlias www.example.com
# Index file and Document Root (where the public files are located)
DirectoryIndex index.html index.php
DocumentRoot /var/www/html/example.com/public_html
WSGIScriptAlias / /var/www/html/example.com/FlaskApp/flaskapp.wsgi
<Directory /var/www/html/example.com/FlaskApp/>
Require all granted
</Directory>
Alias /static /var/www/html/example.com/FlaskApp/static
<Directory /var/www/html/example.com/FlaskApp/static/>
Require all granted
</Directory>
# Log file locations
LogLevel warn
ErrorLog /var/www/html/example.com/log/error.log
CustomLog /var/www/html/example.com/log/access.log combined
</VirtualHost>
Do you know how to make Firebase get() works in a deployed Flask app? Thank you for your help!
Seems like WSGI needs to be forced to use the main Python interpreter. Therefore, you'll need to add application-group=%{GLOBAL} to the end of your ``WSGIScriptAlias line on example.com.conf, so that the line now reads:
WSGIScriptAlias / /var/www/html/example.com/FlaskApp/flaskapp.wsgi application-group=%{GLOBAL}
After that, restart Apache with the terminal command systemctl restart apache and your problem should be solved.

run flask on apache on windows

Here's the issue.
I am trying to deploy my flask app in apache2.4 Server using mod_wsgi.After configuration,my apache server start to run on my computer.But when I visit http://127.0.0.1:5000/ the page doesn't display as my wish.
Here's my flask code.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return "Hello World!"
if __name__ == '__main__':
app.run(port=5000)
And here's my virtual host config.
<VirtualHost *:5000>
ServerAdmin example#company.com
DocumentRoot C:\flask
WSGIScriptAlias / C:\flask\test.wsgi
<Directory "C:\flask">
Require all granted
Require host ip
Allow from all
</Directory>
</VirtualHost>
My wsgi code.
import sys
#Expand Python classes path with your app's path
sys.path.insert(0, "C:/flask")
from test import app as application
#Put logging code (and imports) here ...
#Initialize WSGI app object
application = app
The page is like this:
It says 'Internal Server Error'.
Thank everyone!
remove the code
#Initialize WSGI app object
application = app
maybe it works
first remove last line from test.wsgi file.
(i.e application = app)
then check http://127.0.0.1:5000/, if it works then good,
if not then, add the following lines at the bottom of httpd.conf file.
WSGIScriptAlias / C:\flask\test.wsgi
<Directory C:\flask>
Require all granted
</Directory>
then check again http://127.0.0.1:5000/. it will work definitely.

unable to setup wsgi with httpd for running python based web app

I have archlinux.
I installed httpd and mod_wsgi
and added the following in the /etc/httpd/conf/httpd.conf
LoadModule wsgi_module modules/mod_wsgi.so
after this how to put the things in the virtualhost file.
Still i tried:
<VirtualHost *:80>
ServerName localhost
WSGIScriptAlias / /home/simha/.public_html/public_wsgi/wsgi-scripts
<Directory "/home/simha/.public_html/public_wsgi/wsgi-scripts">
Options All Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
I have put a testing script called wsgi_app.py in the /home/simha/.public_html/public_wsgi/wsgi-scripts folder.
the wsgi_app.py script is
#-*- coding: utf-8 -*-
def wsgi_app(environ, start_response):
import sys
output = sys.version.encode('utf8')
status = '200 OK'
headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, headers)
yield output
# mod_wsgi need the *application* variable to serve our small app
application = wsgi_app
(Also i dont understand what is this code doing). i got it from archlinux.
when go to localhost in the browser, i get
Forbidden
You don't have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.
Any help.
This error is generally caused by the fact that your home directory has permissions such that other users cannot access anything in it. This will cause a problem as Apache httpd will run as a distinct user.
Move your application to a directory outside of your home directory, such as under /var/www.

CSRF token mismatch in Apache Flask due to session reset

I have an example of a CSRF protected form that runs perfectly in the development environment (Flask runs the server itself with app.run) but fails when I run the app via mod_wsgi in Apache. The versions I use are:
Server version: Apache/2.4.4 (Unix)
Python 2.7.3
Flask==0.10.1
Flask-WTF==0.9.5
WTForms==2.0
Flask-KVSession==0.4
simplekv==0.8.4
The reason that it fails is a csrf_token mismatch during form validation. I log the contents of the flask.session and flask.request.form at the beginning of the view and the contents of the session again at the end of the view. In development mode the content of the csrf_token in the session stays constant across multiple requests, for example,
<KVSession {'csrf_token': '79918c1e3191e4d4fe89a9499f576404a18be8e4'}>
The contents of the form are transmitted correctly in both cases, e.g.,
ImmutableMultiDict([('csrf_token', u'1403778775.86##34f1447f1b8c78808f4e71f2ff037bcd1df41dcd'),
('time', u'8'), ('submit', u'Go'), ('dose', u'Low')])
When I run my app via Apache the session contents are reset with each request. At the beginning of the view the session contents are empty:
<KVSession {}>
and then a new token is set each time which leads to the mismatch. Currently, my __init__.py module looks as follows:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension
app = Flask(__name__)
app.config.from_object("myapp.config.Config")
db = SQLAlchemy(app)
store = DictStore()
KVSessionExtension(store, app)
from . import views
I removed the KVSession statements and that didn't change the problem. So I think server side sessions are not the culprit.
And yes, I have set the SECRET_KEY to os.urandom(128) in the config.
The relevant (I think) section of my httpd.conf is:
Listen url.com:8090
<VirtualHost url.com:8090>
# --- Configure VirtualHost ---
LogLevel debug
ServerName url.com
DocumentRoot /path/to/flaskapp/htdocs
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /path/to/flaskapp/htdocs/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Require all granted
</Directory>
# --- Configure WSGI Listening App(s) ---
WSGIDaemonProcess mysite user=me group=us processes=2 threads=10
WSGIScriptAlias / /path/to/flaskapp/wsgi/wsgi.py
<Directory /path/to/flaskapp/wsgi/>
WSGIProcessGroup mysite
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
Require all granted
</Directory>
# --- Configure Static Files ---
Alias /static/ /path/to/flaskapp/htdocs/static/
Alias /tmp/ /path/to/flaskapp/htdocs/tmp/
</VirtualHost>
Does anyone know about Apache settings or mod_wsgi with Flask interactions that could cause the session not to persist between requests?
What happens here is that you store your sessions using Flask-KVSession, and provide a memory based DictStore as a storage:
from simplekv.memory import DictStore
store = DictStore()
KVSessionExtension(store, app)
Root cause
In a single-threaded environment, this will work. However, when multiple processes comes into play, they do not share the same memory, and multiple instances of DictStore are created, one per process. As a result, when two subsequent requests are served by two different processes, first request will not be able to pass session changes to a next request.
Or, even shorter: Two processes = two CSRF tokens. Not good.
Solution
Use a persistent storage. This is what I use:
def configure_session(app):
with app.app_context():
if config['other']['local_debug']:
store = simplekv.memory.DictStore()
else:
store = simplekv.db.sql.SQLAlchemyStore(engine, metadata, 'sessions')
# Attach session store
flask_kvsession.KVSessionExtension(store, app)