permission denied error while creating a file in python flask on apache and mod_wsgi - mod-wsgi

I am trying to create a csv file through python flask. The code works fine in localhost but gives a permission denied error when deployed on apache + mod_wsgi on aws ec2 instance.
#app.route('/downloadChats/<db_token>/<requestrange>/', methods = ['GET'])
def downloadChats(db_token, requestrange):
<fetch data from table>
try:
filename = str(time.time()).strip().split('.')[0] + '.csv'
df = pd.DataFrame(columns = ['sessionid', 'city', 'ipAddress', 'startTime', 'timestamp', 'name', 'mob_no'])
for sessid in sessionids:
df = df.append({'sessionid' : disp_json[sessid]['sessionid'], 'city' : disp_json[sessid]['city'], 'ipAddress' : disp_j$
df.to_csv(filename, index = False)
except Exception as msg:
print("Exception while writing csv file in downloadChats : " + str(msg))
return "<h1> THis service is unavailable currently, Please try later. </h1> "
return send_from_directory('/var/www/FlaskApps/chatbotApp/', filename, as_attachment=True)
The app configuration file is :
<VirtualHost *:80>
ServerName example1.example.com
ServerAdmin admin#mywebsite.com
WSGIScriptAlias / /var/www/FlaskApps/FlaskApps.wsgi
WSGIPassAuthorization On
<Directory /var/www/FlaskApps/chatbotApp/>
Order allow,deny
Allow from all
</Directory>
<Directory /var/www/FlaskApps/chatbotApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
RewriteEngine on
RewriteCond %{SERVER_NAME} = example1.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI}
[END,NE,R=permanent]
</VirtualHost>
The wsgi config file is :
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApps/chatbotApp/")
# home points to the home.py file
from home import app as application
application.secret_key = "somesecretsessionkey"
Error :
[Errno 13] Permission denied: '1518497209.csv'

You can't use a relative path name as the working directory of the process will not be where your code is. This, along with what you need to do is explained in the mod_wsgi documentation at:
http://modwsgi.readthedocs.io/en/develop/user-guides/application-issues.html#application-working-directory

Related

Apache2 error, redirects to defaultsite. Domain hosted by 1&1 Ionos

I am setting up an apache2/flask hello world test site to make sure everything works, but I can't stop it from being redirected to /defaultsite.
I know I've done the setup correctly as I don't get any error messages in my logs, just a 404 url not found for mycocoop.com/defaultsite.
Domain registered with 1&1 Ionos, mycocoop.com. Could this be an issue?
I have given control of the mycocoop directory to www-data.
I've removed all the standard files created by apache2. My sites-available only contains mycocoop.conf. I have disensite'd 000-default, so my sites-enabled only contains mycocoop.conf.
mycocoop.conf contents:
<VirtualHost *:80>
ServerAdmin CensoredFor#StackOverflow
ServerName www.mycocoop.com
ServerAlias mycocoop.com
WSGIDaemonProcess mycocoop user=www-data group=www-data threads=5
WSGIProcessGroup mycocoop
WSGIScriptAlias / /var/www/mycocoop/mycocoop.wsgi
Alias /static/ /var/www/mycocoop/build
<Directory /var/www/mycocoop/build>
Order allow,deny
Allow from all
</Directory>
ErrorLog /var/www/mycocoop/logs/error.log
CustomLog /var/www/mycocoop/logs/access.log combined
</VirtualHost>
file structure:
/var/www/mycocoop:
/api:
__init__.py
app.py
/build:
index.html #basic hello world html, currently not in use
/logs: #not relevant
/venv: #not relevant
mycocoop.wsgi
mycocoop.wsgi contents:
#!/usr/bin/python3.9
import sys
sys.path.insert(0, "/var/www/mycocoop/")
from api import app as application
api/__ init __.py contents:
from .app import app
api/app.py contents:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run

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.

404 error when trying and unable access the sub urls but the server name is running

I am deploying Flask app with httpd 2.4 by using mod_wsgi 4.5 version.
My servername sample.server.com is running fine but when i try with sub url like sample.server.com/app1, am encountering 404 error.
I also tried with localshost/app1 its is working, that means my flask app is tottaly fine but there is some configuration issue which i couldnt figure out.
I am providing with wsgi file and virtualhost config, i tried reading many articles and blogs but i couldnt find the solution.I would appreciate any help, Thanks
app.wsgi-->
activate_this = '/home/nmapi/venv/bin/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))
from werkzeug.wsgi import DispatcherMiddleware
import sys
import logging
print(sys.path)
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"home/nmapi/project/dir")
from run import *
my vurtual host config is
#ServerName sample.server.com
WSGIApplicationGroup %{GLOBAL}
WSGIScriptAlias /test_wsgi
/home/nmapi/project/dir/datascience.wsgi
<Directory /home/nmapi/project/dir/>
#WSGIProcessGroup score
#AllowOverride All
Require all granted
#Allow from all
</Directory>
Alias /static /home/nmapi/project/dir/static
<Directory /home/nmapi/project/dir/static/>
WSGIProcessGroup score
#WSGIApplicationGroup %{GLOBAL}
#AllowOverride All
Require all granted
#Allow from all
</Directory>
ErrorLog logs/error.log
#ErrorLog /tmp/error.log
LogLevel debug
#CustomLog /tmp/access.log combined
CustomLog logs/access.log combined

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.

symfony 1.4 and Apache access/error logs

Symfony 1.4 is set up as the only virtual host in my Apache config. Should I make use of the Apache access logs and error logs or does symfony take care of both of these for me?
Apache logs are not the same as the logging provided by symfony. Apache logs are useful for other reasons than symfony's. I usually use the following virtual host config for my local development.
<VirtualHost *:80>
ServerName dev.yoursite.com.br
DocumentRoot "/home/you/dev/sfprojects/yoursite/web"
DirectoryIndex index.php
<Directory "/home/you/dev/sfprojects/yoursite/web">
AllowOverride All
Allow from All
</Directory>
Alias /sf /home/you/dev/sfprojects/yoursite/lib/vendor/symfony/data/web/sf
<Directory "/home/you/dev/sfprojects/yoursite/lib/vendor/symfony/data/web/sf">
AllowOverride All
Allow from All
</Directory>
ErrorLog "/home/you/dev/sfprojects/yoursite/log/error.log"
CustomLog "/home/you/dev/sfprojects/yoursite/log/web.log" combined
</VirtualHost>
For symfony, I configure the factories.yml like the following
dev:
logger:
class: sfAggregateLogger
param:
level: notice
loggers:
sf_file_err:
class: sfFileLogger
param:
level: err
file: %SF_LOG_DIR%/%SF_APP%_%SF_ENVIRONMENT%_error.log
sf_file_notice:
class: sfFileLogger
param:
level: notice
file: %SF_LOG_DIR%/%SF_APP%_%SF_ENVIRONMENT%_notice.log