The only way I can run apps on my local machine is by using apache and lib-wsgi. I have installed all the relevent packages including encodings but in my browser I am getting a 403 Forbidden error and in my error logs I am getting this:
AH00051: child pid 28900 exit signal Aborted (6), possible coredump in /etc/apache2
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
I have run
sudo chmod a+x on my files
and
sudo chmod +rw on my folders.
and
sudo chown on my working directories
What do I need to do to get this working?
These are my files:
.conf file:
<VirtualHost *:80>
ServerAdmin webmaster#localhost
DocumentRoot /var/www/html/demo1
ServerName 127.0.0.1
# Give an alias to to start your website url with
WSGIDaemonProcess application python-home=/var/www/html/demo1
WSGIProcessGroup flask-hello-app
WSGIApplicationGroup %{GLOBAL}
WSGIScriptAlias /demo1 /var/www/html/demo1/flask-hello-app.wsgi
<Directory /var/www/html/demo1/>
# set permissions as per apache2.conf file
Options FollowSymLinks
# AllowOverride None
# Require all granted
Order deny,allow
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
flask-hello-app.wsgi
#!/uae/bin/python3
import logging
import sys
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/var/www/html/demo1/')
from application import app as application
application.secret_key = 'super_secret_key'
flask-hello-app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:F00tBall#127.0.0.1:5432/example'
db = SQLAlchemy(app)
class Person(db.Model):
__tablename__ = 'persons'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), nullable=False)
db.create_all()
#app.route('/')
def index():
return 'Hello '
if __name__ == '__main__':
app.run()
I really need to know how to get this working.
Thanks.
Related
I have a flask test website and i want to use os.environ variables from venv or from Apache's SetEnv, but i can't figure it out.
app.py:
from flask import Flask
import os
app = Flask(__name__)
#app.config.from_object('site3.default_settings')
#app.config.from_envvar('SITE3_SETTINGS')
#app.config.from_prefixed_env()
password = "test"
password = os.environ
#app.route('/')
def home():
my_env_var = os.environ.get('MY_ENV_VAR')
return f"3. site!!:{my_env_var} BU BIR FLASK UYGULAMASIII!!<br> Şifre: {password}\n"
The curl output is:
3. site!!:None BU BIR FLASK UYGULAMASIII!! Şifre: environ({'APACHE_RUN_DIR': '/var/run/apache2', 'SYSTEMD_EXEC_PID': '20419', 'APACHE_PID_FILE': '/var/run/apache2/apache2.pid', 'JOURNAL_STREAM': '8:128103', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin', 'INVOCATION_ID': '9afa423a83864973b497217939a094fc', 'APACHE_LOCK_DIR': '/var/lock/apache2', 'LANG': 'C', 'APACHE_RUN_USER': 'www-data', 'APACHE_RUN_GROUP': 'www-data', 'APACHE_LOG_DIR': '/var/log/apache2', 'PWD': '/', 'HOME': '/var/www'})
apache config:
<VirtualHost *:80>
ServerName site3.com
ServerAlias www.site3.com
SetEnv SECRETT "devet"
SetEnv MY_ENV_VAR value
SetEnv ENVTYPE production
WSGIDaemonProcess flaskapp user=www-data group=www-data threads=5 python-home=/var/www/site3/venv
WSGIScriptAlias / /var/www/site3/app.wsgi
SetEnv SECRETT denet
SetEnv MY_ENV_VAR valuee
<Directory /var/www/site3>
WSGIProcessGroup flaskapp
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
Alias /static /var/www/site3/static
<Directory /var/www/site3/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog /var/www/site3/logs/error.log
CustomLog /var/www/site3/logs/access.log combined
</VirtualHost>
app.wsgi:
import sys
sys.path.insert(0, '/var/www/site3')
#activate_this = '/var/www/site3/venv/bin/activate'
#with open(activate_this) as file:
# exec(file.read(), dict(__file__=activate_this))
from app import app as application
if __name__ == "__main__":
application.run()
It is my first question and i am trying to learn. Thank you all.
when i use 'flask run' and curl localhost:5000, everything works as i expected.
add an .env file to your project and load all the variables found as environment variables, example:
# this is your .env file
DATABASE_URL = postgresql... etc
then pip install python-dotenv
pip install python-dotenv
then use load_dotenv() in your app settings
from dotenv import load_dotenv
import os
# then call load_dotenv() when creating your app
def create_app():
app = Flask(__name__)
load_dotenv()
...
# call your variables as follows:
DATABASE_URL = os.getenv("DATABASE_URL") # defined in .env
...
return app
when executing the app, add app:create_app() as parameter, e.g. with gunicorn, on a docker entrypoint your script looks like this:
exec gunicorn --bind 0.0.0.0:80 "app:create_app()"
try to add it where you define the app in app.wsgi
I try to load my app towards my apache2 server but i keep getting error 500.
File Structure:
/var/www/ApproveAndPost:
ApproveAndPost.wsgi
ApprovePost_Web
run.py
/var/www/ApproveAndPost/ApprovePost_Web:
forms.py
init.py
models.py
routes.py
services.py
static
templates
Files content:
/etc/apache2/sites-available/ApproveAndPost.conf
<VirtualHost *:80>
ServerName 192.168.170.67
ServerAdmin email#mywebsite.com
WSGIScriptAlias / /var/www/ApproveAndPost/ApproveAndPost.wsgi
<Directory /var/www/ApproveAndPost/ApprovePost_Web/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/ApproveAndPost/ApprovePost_Web/static
<Directory /var/www/ApproveAndPost/ApprovePost_Web/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
WSGI File:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/ApproveAndPost")
from ApproveAndPost import app as application
application.secret_key = 'DISISSECRETKEY'
Python Code:
run.py
from ApprovePost_Web import app
if __name__ == "__main__":
app.run(debug=True)
init.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = '#$%^&*'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
from ApprovePost_Web import routes
if __name__ == "__main__":
app.run(debug=True)
I think i am mixing up a couple of things ?
The problem is essentially that you are installing Flask, and possibly other required libraries, in a virtual environment but the python (wsgi interface) is running with the system python which does not have these extra libraries installed.
Im trying to host a flask app with an apache2 server. The server works but I'm only seeing a list of files, the wonderful "index of" page. My code is pretty simple. This is my hello.py file in /var/www/flask_dev:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host='0.0.0.0')
I also created an apache config file located in /etc/apache2/sites-available/flask_dev.conf:
ServerName example.com
<VirtualHost *:80>
ServerAdmin webmaster#localhost
WSGIDaemonProcess hello user=www-data group=www-data threads=5 python-path=/var/www/flask_dev
WSGIScriptAlias / /var/www/flask_dev/start.wsgi
<Directory /var/www/flask_dev>
WSGIProcessGroup hello
WSGIApplicationGroup %{GLOBAL}
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
And the needed wsgi file also located in /var/www/flask_dev/start.wsgi:
from hello import app as application
import sys
sys.stdout = sys.stderr
I'm not sure what I did wrong, I just followed a simple tutorial.
Thanks for your help :)
You probably did not install mod_wsgi module for Apache.
http://flask.pocoo.org/docs/0.10/deploying/mod_wsgi/
Apache needs to import the mod_wsgi module for it to work with python. Further instructions for installation can be found at.
https://code.google.com/p/modwsgi/wiki/QuickInstallationGuide
Once installed, edit your httpd.conf with LoadModule wsgi_module modules/mod_wsgi.so
If you are on Windows, you will have to download the appropriate mod_wsgi.so for the python version and architecture. Rename the file to mod_wsgi.so if it has any python specific version naming and set conf to LoadModule.
I have an Apache (ver. 2.2.15) server (running on Linux CentOS), where I have a lot of .cgi scripts located in /var/www/cgi-bin, aliased:
ScriptAlias /cgi-bin "/var/www/cgi-bin"
And it works fine when I enter mydomain/cgi-bin/something.cgi.
Now I want to have also Flask application running within Apache server on 80 port. The app is located in /var/www/cgi-bin/app. So, I created simple Flask app - a.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
and a.wsgi file:
import sys
import site
sys.path.insert(0, '/var/www/cgi-bin/app')
site.addsitedir('/var/www/cgi-bin/app:/<my_python_path>/Lib/site-packages')
from app import app as application
Also in /etc/httpd/conf/httpd.conf I have created required virtualhost:
<VirtualHost *:80>
ServerName app.<mydomain>:80
WSGIDaemonProcess app python-path=/var/www/cgi-bin/app:/<my_python_path>/Lib/site-packages user=user1 group=user1 threads=5
WSGIScriptAlias /cgi-bin/app /var/www/cgi-bin/app/a.wsgi
<Directory /var/www/cgi-bin/app>
WSGIProcessGroup app
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
ErrorLog /var/www/cgi-bin/app/logs/error.log
CustomLog /var/www/cgi-bin/app/logs/custom.log combined
</VirtualHost>
But everytime I try to open mydomain/cgi-bin/app/ in the error.log file I see this error:
(...) attempt to invoke directory as script: /var/www/cgi-bin/app/
Do you have an idea what have I done wrong here?
You should not put your Flask app under cgi-bin, in fact it should not be under the DocumentRoot at all. Move it somewhere else entirely - I like /srv/, but it's up to you - and change the WSGI alias appropriately.
I am trying to setup django project by apache and mod_wsgi file. But I am getting this error client denied by server configuration: /home/ghrix/production . I have google this errro and found lot of solutions but nothing worked for me.
My code are as follows :
production.wsgi
import os
import sys
sys.path = ['/home/ghrix/myproject/'] + sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
production.conf file :
<VirtualHost *:80>
WSGIScriptAlias / /home/ghrix/production.wsgi
ServerName firstweb.com
ServerAlias firstweb.com
Alias /static/ /home/ghrix/myproject/static/
<Directory /home/ghrix/myproject/ >
Options Indexes FollowSymLinks
WSGIProcessGroup production
WSGIApplicationGroup %{GLOBAL}
Require all denied
</Directory>
</VirtualHost>
I solved the problem by making two changes :
1) Require all denied -> change this to -> Require all granted
2) If you look at the project created by you there is already a wsgi.py file in you project directory (same dir where your settings are placed by default) , So you do not have to create seperate wsgi file as I have created initially. Just point to that wsgi.py in your conf file inside apache2 as
WSGIScriptAlias / /<path to my-project wsgi.py file>
That's it you error is resolved. But still if you are getting one more error after this your settings module is not find then you have to edit your wsgi file and add two lines of code :
import sys
sys.path = ['<path to my project>'] + sys.path
That's it your project will run smoothly now.
So complete wsgi and conf files will look like this :
wsgi.py file :
import os
import sys
sys.path = ['<path to my project>'] + sys.path
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
and conf file :
<VirtualHost *:80>
WSGIScriptAlias / /<path to my project>/wsgi.py
ServerName secondweb.com
ServerAlias secondweb.com
Alias /static/ /<path to my project>/static/
<Directory /<path to my project>/ >
Options Indexes FollowSymLinks
Require all granted
</Directory>
</VirtualHost>