How do I run Django as a service? - python

I am having difficulty running Django on my Ubuntu server. I am able to run Django but I don't know how to run it as a service.
Distributor ID: Ubuntu
Description: Ubuntu 10.10
Release: 10.10
Codename: maverick
Here is what I am doing:
I log onto my Ubuntu server
Start my Django process: sudo ./manage.py runserver 0.0.0.0:80 &
Test: Traffic passes and the app displays the right page.
Now I close my terminal window and it all stops. I think I need to run it as a service somehow, but I can't figure out how to do that.
How do I keep my Django process running on port 80 even when I'm not logged in?
Also, I get that I should be linking it through Apache, but I'm not ready for that yet.

Don't use manage.py runserver to run your server on port 80. Not even for development. If you need that for your development environment, it's still better to redirect traffic from 8000 to 80 through iptables than running your django application as root.
In django documentation (or in other answers to this post) you can find out how to run it with a real webserver.
If, for any other reason you need a process to keep running in background after you close your terminal, you can't just run the process with & because it will be run in background but keep your session's session id, and will be closed when the session leader (your terminal) is terminated.
You can circunvent this behaviour by running the process through the setsid utility. See your manpage for setsid for more details.

Anyway, if after reading other comments, you still want to use the process with manage.py, just add "nohup" before your command line:
sudo nohup /home/ubuntu/django_projects/myproject/manage.py runserver 0.0.0.0:80 &

For this kind of job, since you're on Ubuntu, you should use the awesome Ubuntu upstart.
Just specify a file, e.g. django-fcgi, in case you're going to deploy Django with FastCGI:
/etc/init/django-fcgi.conf
and put the required upstart syntax instructions.
Then you can you would be able to start and stop your runserver command simply with:
start runserver
and
stop runserver
Examples of managing the deployment of Django processes with Upstart: here and here. I found those two links helpful when setting up this deployment structure myself.

The problem is that & runs a program in the background but does not separate it from the spawning process. However, an additional issue is that you are running the development server, which is only for testing purposes and should not be used for a production environment.
Use gunicorn or apache with mod_wsgi. Documentation for django and these projects should make it explicit how to serve it properly.
If you just want a really quick-and-dirty way to run your django dev server on port 80 and leave it there -- which is not something I recommend -- you could potentially run it in a screen. screen will create a terminal that will not close even if you close your connection. You can even run it in the foreground of a screen terminal and disconnect, leaving it to run until reboot.

If you are using virtualenv,the sudo command will execute the manage.py runserver command outside of the virtual enviorment context, and you'll get all kind of errors.
To fix that, I did the following:
while working on the virtual env type:
which python
outputs: /home/oleg/.virtualenvs/openmuni/bin/python
then type:
sudo !!
outputs: /usr/bin/python
Then all what's left to do is create a symbolic link between the global python and the python at the virtualenv that you currently use, and would like to run on 0.0.0.0:80
first move the global python folder to a backup location:
mv /usr/bin/python /usr/bin/python.old
/usr/bin/python
that should do it:
ln -s /usr/bin/python /home/oleg/.virtualenvs/openmuni/bin/python
that's it! now you can run sudo python manage.py runserver 0.0.0.0:80 in virtaulenv context!
Keep in mind that if you are using postgres DB on your developement local setup, you'll probably need a root role.
Credit to #ydaniv

Related

Can a Django app be run directly from python?

I have created an app with Django, on my Raspberry Pi, as part of my smart home project. Now that I am coming to the end of the project, I would like to make it so that I can run one script and have all of the features of the smart home working. (This would be especially useful as then I can just make it run on boot without having to connect a screen or ssh).
What I would like to know is if there is a way I can make a python script that will run the whole Django app so that I don't have to go into terminal and set it up. Is this possible? and if not what is the best way to go about my issue?
Yes you can do that you set the autologin in raspi-config then create a shell script run.sh
like this
python /path/to/project.manage.py runserver 0.0.0.0:8000
or you can use gunicorn proxy
You can also start other servers in this file
then put sh run.sh in you .bashrc.
Better way
You can install tmux by apt-get install tmux
You can make detached session using tmux in run.sh using a unique name and tmux so that each time you open the prompt it wont create duplicate sessions.

How to start other Servers Automatically after Django Server starts

I am using different Servers alongside Django Server. For Example MongoDB server and Celery[command]
I want to ask that how can I execute other CMD commands automatically whenever I start "**
python manage.py runserver
**"
Depends on what OS you use, on my Ubuntu for local development I do this:
Create .sh script. For example start_project.sh with this code:
cd /path/to/project
source /venv/bin/activate
python manage.py runserver & celery -A project worker --loglevel=debug
And then just run bash start_project.sh
Also you can add more commands to start separated by &
You should write a shell script which contains commands to start each service and then use it to get your projects running. For example here is a sample:
sudo service mongodb start
celery -A worker appname.celery
python manage.py runserver 0.0.0.0:80 > /dev/null 2>&1 &
Due to you use the term CMD I guess you use a Windows based OS. I would then say that you probably have the mongoDB service installation? (otherwise reinstall mongoDB as Service).
By defualt set to autostart (changable to non-autostart). If you changed the service for mongoDB to manual starting method, then you could start it in CMD as
net start mongoDB
I do not use/know what "Celery" is but quick google made it sound as some sort of message que. Which in my opinion should be or at least should have a service installation in which case you should use that and then use autostart/manual as described for mongoDB.

Django: Error: You don't have permission to access that port

I'm very new to this whole setup so please be nice.
On dev the command usually works with no errors but since I have been experimenting with different commands for Django someting has gone wrong.
python manage.py runserver 0.0.0.0:80
I don't have permission to use this port anymore. I can use port 8080 but the website doesn't work when I add the port to the end of the usual host name in the url. When I used port 80 I never had to add :80 to the url anyway.
I had an error where I didn't have permissions to the log file but I changed the permissions on that file. It seems there is now many things I don't have permissions for.
Django 1.8.5.
Using a virtual envirnment and I have 2 apps in the project.
If you're on Linux, you'll receive this error.
First and foremost, Django does not have a production server, just a very basic development server and uses port 8080 by default.
when you execute the command
python manage.py runserver
you tell django to start its development server and it runs so you can test your web app before deployment to a production server.
Django Documentation -> django-admin -> Run Server
The way to access the server is to use your browser and plug in the URL in the address bar as so
localhost:8080
by default, most HTTP applications run on port 80 unless otherwise stated. For example, your MySQL server could run on port 3306 by default.
Basically, you can think of ports as old school telephone lines that connect you to whom ever your looking to communicate with.
There's nothing really special about any of this. You should probably play with bottle to get the basics down first; just a friendly suggestion.
You can dig in to the details on the website. While not secure, you can use sudo to run on port 80, but for security reasons you should avoid it.
#mtt2p mentions a serverfault post that does a great job of the why
I'm sure there's a way to tell the server to allow only local connections, but you should only use 0.0.0.0:80 when you want to show off your work to other people or see what your web app looks like on other devices.
In the long run, sudo is just easier and quicker, but lazy and insecure.
This is a link that explains it in the context of a virtualenv.
Django runserver error when specifying port
The answer states
I guess the sudo command will run the process in the superuser
context, and the superuser context lack virtualenv settings.
Make a shell script to set the virtualenv and call manage.py
runserver, then sudo this script instead.
You should note that the answer explaining a virtualenv based context is also insecure. It should just be run as
sudo python manage.py runserver 80
not
sudo bash script-name
outside of a virtualenv. Doing so defeats the purpose of sand-boxing your application. If you ignore this, you'll be exposing yourself to a race condition.
I am in Xubuntu 20.04 version and I use this command (because I have an python env) :
$ sudo ~/.virtualenvs/myproject/bin/python manage.py runserver 0.0.0.0:80
And to know where is your envs python folder, I did :
$ which python
sudo python manage.py runserver 0.0.0.0:80
you need admin rights for port 80
I set up a virtualenv called "aira" and installed virtualenvwrapper in the root environment (my virtualenvwrapper settings in /root/.bashrc are at the bottom). This reduces the number of sudo commands I need to cascade to -c together to get runserver working:
sudo sh -c "workon aira && python manage.py runserver --insecure 0.0.0.0:80"
If you've set up your django app's virtualenv without virtualenvwrapper you'll need to manually change to the correct directory and activate your virtualenv within the sudo command sequence. My virtualenv is called aira and I keep my virtualenvs in /root/.virtualenvs. My django project is in the ubuntu user's home directory:
sudo sh -c "source $HOME/.virtualenvs/aira/bin/activate && cd /ubuntu/src/aira/ && python manage.py runserver --insecure 0.0.0.0:80"
If you've installed django and your requirements.txt in the system site packages then you can use sudo to runserver.
sudo python manage.py runserver --insecure 0.0.0.0:80"
The --insecure option allows staticfiles to serve your static assets (images, css, javascript).
For completeness, here're my virtualenvwrapper configuration variables in /root/.bashrc on Ubuntu 16.04:
# python3 is used for virtualenv and virtualenvwrapper
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
# *root* reuses the virtualenvs in *ubuntu*'s home directory
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=/home/ubuntu/src
source /usr/local/bin/virtualenvwrapper.sh
sudo ./venv/bin/python manage.py runserver 80

Difference between Daemon and Upscript for Gunicorn in Django Production

I am deploying a Django site in production and now from a week I couldn't get Gunicorn script in /etc/init/project.conf to bind Nginx no matter what I do inside a Django virtual environment and under newly created user djagno at location /home/Django/project/bin/gunicorn. I need to know that can I run a site in production with daemon. I understand that daemon is simply a background process and not attached to any tty. But with creating a pid with running a command from inside a virtualenv like "gunicorn --bind 127.0.0.1:9500 project.wsgi:application --config=/etc/gunicorn.d/gunicorn.py --name=project -p /tmp/project.pid" wouldn't it act as a service? My project without virtual environment is working just fine but not with virtual environment. I am learning Linux so need an expert advise. Can I launch a project like this?
My upstart script I couldn't attach within virtualenv is given below.
description "Gunicorn daemon for Django project"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]
# If the process quits unexpectadly trigger a respawn
respawn
setuid django
setgid django
chdir /home/django
exec gunicorn \
--name=project\
--pythonpath=project\
--bind=127.0.0.1:9500 \
--config /etc/gunicorn.d/gunicorn.py \
project.wsgi:application
If someone can help me to make change in it according to virtualenv I would be thankful. Again...same settings for my project without virtualenv are working just fine but not for my second website where the only difference is that I am running first project without virtualenv and second one is from virtualenv.
The point is that if you just run it like that, you don't have anything responsible for ensuring it remains up: if the process dies, or if you have to restart your server, you will have to re-run that command manually. That's what upstart, or supervisor, will do for you: monitor that it is indeed running, and bring it back if it isn't.
If you want help with debugging your upstart script, you will need to actually post it, plus any errors from the log.

Heroku bash on windows

I am trying to connect to Heroku bash on windows and use python manage.py shell iPython shell to help me type commands faster.
While this works fine if I am on Mac, on my Windows machine - the colour coding of heroku bash iPython shell and the tab-autocomplete feature does not work.
Is there some other tool I can use or can configure somewhere? I tried installing bash on Windows, and it gives me the same result
You should NOT, NOT, NOT!!#!!!!! be using Heroku's bash shell for casual python coding. This is an awful idea for many reasons:
Heroku dynos don't have a persistent filesystem. Any files on your dyno can be deleted randomly.
The amount of time it will take you to build an ipython setup / configuration from scratch, and get it running on your dyno is not worth the effort.
Heroku dynos are meant to run web processes as they restart randomly -- your terminal session may blow up at any point.
If you really want an authentic 'shell' experience, I recommend using a real shell for development -- either get yourself a virtual machine and install ubuntu, or spin up a ubuntu server machine through a host like DigitalOcean or Amazon.

Categories

Resources