I need to host a Django website in Ubuntu 18 (Desktop). I searched the web but couldn't find a well-written tutorial which demonstrates how to do this step by step. After doing some research I came across following procedure but I believe its incomplete.
Library installed
sudo apt-get install python3.6
pip3 install Django
sudo apt-get install apache2
sudo apt-get install libapache2-mod-wsgi
The project named mysite with an app polls and virtual environment mysite_env is located in /var/www with following directory structure
Configured wsgi.py at follows
import os
import sys
from django.core.wsgi import get_wsgi_application
sys.path.append('/var/www/mysite')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
Added following lines in apache2.conf located in etc/apache2/apache2.conf
#ServerName mysite.com
WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py
WSGIPythonHome /var/www/mysite/mysite_env
#WSGIPythonPath /path/to/mysite.com
<Directory /var/www/mysite/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
If everything setups perfectly then on opening localhost in the browser will let Apache server to open Django app but on the other hand, by doing it Django app doesn't loads.
I am missing lots of things I know, I need to host it and access it on the web. Can anybody tell me what steps I am missing, Any suggestions would be of great help.
References
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/y
I followed this simple step to step tutorial which I can recommend. It is for Ubuntu 16.04 but I believe you can simply transfer it to 18.04
https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html
Related
I've been trying to sort this out for ages but I just can't seem to get it to work.
Basically I want to use mod_wsgi with apache to serve my Python Flask app, what am I missing?
This is what I've got, a python flask app (flask_restful) with the a main.py as follows:
from app import create_app
application = create_app()
application.run(debug=True)
which calls my app.py
def create_app() -> Flask:
errors = WWAPIErrors()
errors.add_error(GeneralException, 400)
app = Flask("namehere")
api = WWAPI(error_list=errors, app=app)
# APIS
api.add_resource(endpointResouceClass, '/endpoint')
return app
It all runs locally correctly, I have a VPS set up with other sites running perfectly but no python flask apps.
So I've done the following:
sudo apt-get install libapache2-mod-wsgi-py3
sudo apt-get install apache2-dev
sudo apt-get install python3-dev
cd /var/www/appDirectory
python3 -m venv venv
source venv/bin/activate
pip install mod_wsgi
pip install -r requirements.txt
My website.conf file in the /etc/apache2/sites-available directory is:
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
ServerAdmin email#email.com
WSGIScriptAlias / /var/www/appDirectory/app/api/main.py
DocumentRoot /var/www/appDirectory/app/api
<Directory /var/www/appDirectory/app/api/main.py>
Require all granted
</Directory>
WSGIDaemonProcess localhost python-path=/var/www/appDirectory/venv/lib/python3.10/site-packages/ user=www-data
Alias /api /var/www/appDirectory/app/api
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Then I set my mod_wsgi config files:
sudo a2enmod wsgi
mod_wsgi-express module-config
LoadModule wsgi_module "/home/user/appDirectory/venv/lib/python3.10/site-packages/mod_wsgi/server/mod_wsgi-py310.cpython-310-x86_64-linux-gnu.so"
WSGIPythonHome "/home/user/appDirectory/venv"
and put that in my /etc/apache2/mods-enabled/wsgi.load file.
Next I enabled my site:
cd /etc/apache2/sites-available
sudo a2ensite mysitename.conf
The directory of my project loads when I go to the base URL for my app because I have no index.html or anything on site.com/ root directory. But when I go to my implemented site url which is site.com/endpoint I just get a 404, I've even tried to get it locally on my VPS and no luck.
wget localhost:80/endpoint
--2022-12-08 21:07:15-- http://localhost/endpoint
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2022-12-08 21:07:15 ERROR 404: Not Found.
I know/hope I'm just missing something stupid, any help would be GREATLY appreciated.
System details:
neofetch
.-/+oossssoo+/-.
`:+ssssssssssssssssss+:` -------------
-+ssssssssssssssssssyyssss+- OS: Ubuntu 22.04.1 LTS x86_64
.ossssssssssssssssssdMMMNysssso. Host: VMware Virtual Platform None
/ssssssssssshdmmNNmmyNMMMMhssssss/ Kernel: 5.15.0-52-generic
+ssssssssshmydMMMMMMMNddddyssssssss+ Uptime: 47 days, 10 hours, 49 mins
/sssssssshNMMMyhhyyyyhmNMMMNhssssssss/ Packages: 1392 (dpkg), 7 (snap)
.ssssssssdMMMNhsssssssssshNMMMdssssssss. Shell: bash 5.1.16
+sssshhhyNMMNyssssssssssssyNMMMysssssss+ Resolution: 1024x768
ossyNMMMNyMMhsssssssssssssshmmmhssssssso Terminal: /dev/pts/0
ossyNMMMNyMMhsssssssssssssshmmmhssssssso CPU: Intel Xeon E5-2683 v3 (2) # 1.997GHz
+sssshhhyNMMNyssssssssssssyNMMMysssssss+ GPU: 00:0f.0 VMware SVGA II Adapter
.ssssssssdMMMNhsssssssssshNMMMdssssssss. Memory: 987MiB / 1941MiB
/sssssssshNMMMyhhyyyyhdNMMMNhssssssss/
+sssssssssdmydMMMMMMMMddddyssssssss+
/ssssssssssshdmNNNNmyNMMMMhssssss/
.ossssssssssssssssssdMMMNysssso.
-+sssssssssssssssssyyyssss+-
`:+ssssssssssssssssss+:`
.-/+oossssoo+/-.
I managed to find my problem:
Apparently wsgi can't use main.py file directly. I needed to include an app.wsgi file in the root of my project directory, with the following contents:
import sys
sys.path.insert(0, '/var/www/appDirectory/app/api')
from main import application
In addition to this I needed to edit my main.py file to remove the application.run() line as wsgi handles that itself. So my main.py file now looks like this:
from app import create_app
application = create_app()
Now when I run my application I no longer get a 404 but I get the correct response with a 200 code.
Hopefully this helps someone else at some stage, as I do think the information about mod_wsgi and wsgi is really lacking and conflicting online.
I am trying to run a django application with wsgi_mod and apache2. But for some strange reason it cannot import django.
# /etc/apache2/apache2.conf
WSGIDaemonProcess django_apps python-home=/home/swacker/miniconda3/envs/django/
WSGIProcessGroup django_apps
WSGIScriptAlias /koala /var/www/production/Koala/Koala/wsgi.py process-group=django_apps
<Directory /var/www/production/Koala/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
The application sits in /var/www/production/Koala.
My conda enviromnent is installed in /home/user/miniconda3/envs/django.
I installed wsgi inside the conda environment.
I tried different things, but nothing worked. This is what I did to get wsgi running.
sudo apt-get install libapache2-mod-wsgi
pip install mod_wsgi
conda install -c https://conda.binstar.org/travis uwsgi
It looks like wsgi is just not working with conda environments and I have to use virtualenv?? Wsgi works, I can render a test file just fine.
Though, when I go to localhost/koala the /var/log/apache2/error.log shows:
from django.core.wsgi import get_wsgi_application
ImportError: No module named 'django'
I searched a lot, but could not find an answer that addresses this properly.
I have my apache config set up to point to my virtualenv, but when i load the page and look at the error log it gives the following error:
from django.core.wsgi import get_wsgi_application
ImportError: No module named django.core.wsgi
apache2 000-default.conf file:
WSGIDaemonProcess project python-home=/home/django/config/env python-path=/usr/local/bfx/Databases/project
WSGIProcessGroup project
WSGIScriptAlias / /usr/local/bfx/Databases/project/project/wsgi.py
Basically, it will work if I install django, and all my django packages on my server, but what is the point of the virtual env?
Thanks
Virtualenv allows to create isolated environments. So you could create and run multiple projects with different versions of the same library without conflicts, for example.
You have to install all libraries in the server too. Virtualenv do not create a bundle nor deploy it.
I'd like to know how to quickly and simply set up Django on Ubuntu
I have read so much official and user documentation my head is spinning and am not 100% sure where to start.
I'm not an absolute beginner and I have some working knowledge of Django, Python, and Linux Shell Commands (Ubuntu) so the instructions can be quick and to the point.
Note: I answered my own question below...
Setting up Django 1.11 with Python 3.6.1 using Apache 2.4 on Ubuntu 16+
Note: This does not cover everything you 'could do' - it's meant to get your server up and running with Django as quickly as possible. It should work for later versions, just remember to find the right packages and change versioning accordingly
You will likely have to change a lot of the paths included so be watchful.
1. Install Python 3.6 and virtualenv
sudo apt-get update
sudo apt-get install python3.6 python3.6-dev
sudo apt-get install virtualenv
( Ubuntu Packages https://packages.ubuntu.com/ )
2. Install Apache2 webserver
sudo apt-get install apache2 apache2-dev
( all things apache here https://httpd.apache.org/ )
3. Make and enter a folder for your project - then build a Virtual Environment in it
mkdir ~/example.com
cd ~/example.com
virtualenv --python=/usr/bin/python3.6 py361ve
( more about virtual environments here
https://virtualenv.pypa.io/en/stable/ )
4. Enter your new Virtual Environment to install packages to it
source py361ve/bin/activate
( using virtualenv https://virtualenv.pypa.io/en/stable/userguide/ )
5. Install Django, mod_wsgi, and any other needed packages
pip install django
pip install mod_wsgi
pip install ...
( no need for pip3 in virtual environment - pip uses your Virtual Environment python version here )
( more on pip can be found here
https://pip.pypa.io/en/stable/ mod_wsgi
https://modwsgi.readthedocs.io/en/develop/ )
6. Move an existing project or create a new django project within your ~/example.com folder
django-admin startproject django_project
( how to build a Django app
https://docs.djangoproject.com/en/1.11/intro/tutorial01/ )
7. Edit the wsgi.py file in your Django project folder to add sys paths for your project
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Additional: sys.path.append(‘/path/to/your/library’)
( django deployment https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/ )
8. Edit your Django project’s settings.py for your site and set up any additional things you need for your project to work properly.
I put my ‘static’ and ‘media’ folders in a separate location from my
python code ( within /var/www/example.com/ ) and I think you should
too to prevent accidentally making your python code public.
(The VirtualHost example below the instructions should make the setup more
clear)
( Django Settings
https://docs.djangoproject.com/en/1.11/topics/settings/ )
9. Run following command and copy output for placement in apache config file
mod_wsgi-express module-config
( https://pypi.python.org/pypi/mod_wsgi )
10. Exit your virtual environment
deactivate
(You can re-enter your virtual environment any time using the source
method in step 4)
11. Navigate to your apache2 configuration folder ( /etc/apache2/ on Ubuntu ) and place the copied text at the bottom of the Apache2 configuration file.
sudo nano apache2.conf
( more about apache2.conf [ or httpd.conf on some systems ]
https://httpd.apache.org/docs/2.4/configuring.html )
12. Navigate to the /etc/apache2/sites-available/ and create a new conf file for your site. Edit the VirtualHost template (below all instructions) and copy it to this file.
sudo nano example.com.conf
( VirtualHost examples
https://httpd.apache.org/docs/2.4/vhosts/examples.html and mod_wsgi
daemon mode
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode
)
13. After saving the file, enable this site in Apache
sudo a2ensite example.com.conf
sudo service apache2 reload
( https://wiki.apache.org/httpd/DebianLikePlatform )
14. If you want to enable admin access to your site simply copy the files from your python virtual environment to your aliased static/admin folder
example path: /py361ve/lib/python3.6/site-packages/django/contrib/admin/static/admin
( serving admin files
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#serving-the-admin-files
)
15. Any time you update any python or django related script you’ll need to either ‘touch’ the wsgi.py file to reload the daemon process running your site to make it active or restart apache…
touch ~/example.com/my_project/my_project/wsgi.py
or
sudo service apache2 restart
16. Lastly check that all your folders and files have sufficient group ( usually www-data ) read and write privileges and that the folder your database is in (if using sqlite) has group write privileges.
( https://help.ubuntu.com/community/FilePermissions )
VirtualHost Example Template...
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
ServerAdmin info#example.com
DocumentRoot /var/www/example.com
<Directory /var/www/example.com>
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Alias /robots.txt /var/www/example.com/robots.txt
Alias /favicon.ico /var/www/example.com/favicon.ico
Alias /static/ /var/www/example.com/static/
Alias /media/ /var/www/example.com/media/
<Directory /var/www/example.com/static>
Require all granted
</Directory>
<Directory /var/www/example.com/media>
Require all granted
</Directory>
WSGIDaemonProcess example.com python-home=/home/user_name/example.com/py361ve
WSGIProcessGroup example.com
WSGIScriptAlias / /home/user_name/example.com/django_project/django_project/wsgi.py
<Directory /home/user_name/example.com/django_project/django_project>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
</VirtualHost>
Note: Please edit mistakes and make improvements to the instructions as necessary, but don't try to overcomplicate things
I cannot for the life of me figure of why this flask application I'm trying to launch is not working. I am running it on a $5 Digital Ocean droplet. Here's (hopefully) everything you need to know about it:
Directory layout (contained within /var/www/):
FlaskApp
FlaskApp
__init__.py
static
templates
venv
flaskapp.wsgi
__init__.py:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "yay it worked"
if __name__ == "__main__":
app.run()
flaskapp.wsgi:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
from FlaskApp import app as application
application.secret_key = 'Add your secret key'
FlaskApp.conf (contained in /etc/apache2/sites-availble):
<VirtualHost *:80>
ServerName the.ip.blah.blah
ServerAdmin admin#mywebsite.com
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/FlaskApp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/FlaskApp/static
<Directory /var/www/FlaskApp/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
venv was created from calling virtualenv venv within /var/www/FlaskApp/FlaskApp/. I installed flask in venv using pip install flask after entering venv using source venv/bin/activate.
Wsgi has been enabled (a2enmod wsgi). FlaskApp.conf was enabled (a2ensite FlaskApp). And, finally, I restarted apache many times, but to no success (service apache2 restart).
I was following this guide on how to set up a flask application.
Here is a screenshot of what my error looks like:
Any help on getting this to work would be greatly appreciated.
Thanks in advance.
EDIT: I found the problem: ImportError: No module named flask. This is a little strange since I did do pip install flask within the virtualenv. When I just open a python console session in the virtualenv and try import flask I get no error, so not sure what's going on.
Also, how is this application even using venv? I don't see it getting accessed anywhere so how is it even using it? Perhaps this is why i'm getting the ImportError, because I only have flask installed on the virtualenv but it's not being used?
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.
I have very little recent experience running Python on Apache (I come from an era of mod_python and cgi), but apparently one way to handle this is to use the site package to add the site-packages from your venv to the Python that is executed. This would go in your .wsgi file.
import site
site.addsitedir('/path/to/your/venv/lib/pythonX.X/site-packages')
I think the best way to solve your problem is to add tell your wsgi file about your virtual environment and activate it:
put the following code in your your flaskapp.wsgi
activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
and restart apache.
hope it will help!
find more here