Don't lose to Ruby! How to run Python (Django) on Heroku

As the title suggests, Heroku has an image of Ruby or Rails. But you can use Python as well as Ruby! So, I'd like to post a way to get Django, the Python framework, to work.

What is Django?

It's a so-called full-stack web framework made by Python, which has everything you need to build a web app. For example, in Java

It is necessary to make various combinations with (Is it possible to do my best with Java EE alone these days?), But Django can basically be developed only with Django.

Of course, coding is done in Python, so it is recommended for those who can use Python or want to study Python from now on. Tomorrow, kounoike will write an article about another Python framework, Flask. So, you may want to refer to that as well.

Things to consider when deploying Django to Heroku

This is the point I was mainly addicted to. Here, we will talk on the premise that Heroku is a production environment and an environment for actual operation.

Python version

The default Python version on heroku is 2.x. I want to use 3.x system! In that case, you need to tell heroku to that effect.

Debug mode

Django has a debug mode that is turned on by default when you create the environment. By setting this to On, for example, when an error occurs, the detailed contents will be displayed. The following is an example of a 404 error. The URL currently recognized as the URL is displayed, but it is troublesome that it is displayed on the page to be operated. デバッグ時の404エラー例

Database

Django uses SQLite as a DB during development, unless you change the settings. However, Postgres is basically available on Heroku. Therefore, it is necessary to change the DB settings as well.

App server

As a full-stack framework, Django itself has the function of an App server. However, it is positioned for development only, and it is recommended to use a dedicated app server that is tuned crisply for actual operation.

Handling of static files

The App server is basically a server for running applications, so I am not good at handling static files. I think that even App servers of other languages will put Apache or nginx to handle static files. This point also needs to be considered.

solution

I'm moving like this! So, if you have any questions such as "You should do this!", Please do not hesitate to contact us.

Python version

This is easy. Just prepare a file called runtime.txt in the current folder of the project and specify the Python version there as follows.

runtime.txt


python-3.4.1

runtime.txt Please note that the available version is fixed, so please refer to the following page to select the version to use. Specifying a Python Runtime

Debug mode

Debug mode settings are specified in settings.py. However, it is difficult to change it when pushing to heroku and return it when developing locally. So, in my case, as shown below, I am trying to enter debug mode only when local is included in the host name (machine name). This is because my development environment has a name such as "hogehoge.local", so change the local part according to the host name you are using (conversely, specify it with the machine name on the heroku side) Is there any)

settings.py



if 'local' in hostname:
    DEBUG = True
    TEMPLATE_DEBUG = True
else:
    DEBUG = False
    TEMPLATE_DEBUG = False
    ALLOWED_HOSTS = ['*']

Database

This will also be specified in settings.py, but I do not want to rewrite it according to the environment. Therefore, I will make the following description.

settings.py



if 'local' in hostname:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
else:
    import dj_database_url
    DATABASES = {
        'default': dj_database_url.config()
    }

One point here is

python



    import dj_database_url
    DATABASES = {
        'default': dj_database_url.config()
    }

Part of. By using the API called dj_database_url (which can be installed with pip), there is no need to describe the connection destination, user name, password, etc. in the code. This was a shock.

App server

Python's web application framework has a standard called WSGI, and any server that conforms to this standard can be used. In the heroku document, there is an explanation using gunicorn, so I will ride on that.

Deploying Python Applications with Gunicorn

To use this, install gunicorn with pip and add the description of gunicorn to the end of INSTALLED_APPS in settings.py.

settings.py



INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'django.contrib.sitemaps',
    'Project name',
    'gunicorn',   ##← Add this line
)

And at the time of development

$ python manage.py runserver 0.0.0.0:8080

What was started in the form of, will be started with gunicorn instead of manage.py by the method described later (described in Procfile).

Handling of static files

I had a hard time finding information about this. In conclusion, we use something called White noise.

Django and Static Assets

After installing whitenoise with pip, modify settings.py as described in the link above. Then, prepare a file called wisgi.py in the same folder as the location of settings.py, and write the following contents that are also described in the link there.

wsgi.py



from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

Then, write the following in the Procfile so that it can be started using the settings including gunicorn.

Procfile



web: gunicorn --env DJANGO_SETTINGS_MODULE=Project name.settings Project name.wsgi --log-file -

With this setting, push to heroku's repository and it should start!

What about performance? ??

I released the application deployed with the above settings the other day, and there was about 20,000 PV on the first day of release, but it worked fine within the range of the free frame. No, heroku is really amazing.

Below is a link to the blog that describes the process of actually creating the application, so I hope you can refer to it as well.

I tried to create a web service to solve sexual problems

>> Services that are actually running Love Points

Postscript

The source code of the service actually operated (different from ↑) made with heroku & Django has been uploaded to github.

I hope it will be helpful for the composition etc. (It is a dirty source ...)

https://github.com/nakazye/ProgrammerProfile/

Next is ...

Tomorrow, December 8th, Heroku Advent Calendar 2014 is about kounoike's Flask! I'm excited that the Python material will continue.

And I hope that the article will inspire more and more people to write applications in Python.

kounoike, I'm looking forward to tomorrow's article! !!

Recommended Posts

Don't lose to Ruby! How to run Python (Django) on Heroku
How to run matplotlib on heroku
How to run MeCab on Ubuntu 18.04 LTS Python
How to run Notepad ++ Python
How to build a Django (python) environment on docker
How to use Django on Google App Engine / Python
How to run Django on IIS on a Windows server
How to deploy the easiest python textbook pybot on Heroku
python + django + scikit-learn + mecab (1) on heroku
python + django + scikit-learn + mecab (2) on heroku
Periodically run Python on Heroku Scheduler
How to install OpenCV on Cloud9 and run it in Python
How to deploy a Django app on heroku in just 5 minutes
Migrate Django applications running on Python 2.7 to Python 3.5
How to read pydoc on python interpreter
How to erase Python 2.x on Mac.
Memorandum on how to use gremlin python
How to run Cython on OSX Memo
How to write Ruby to_s in Python
How to run a Maya Python script
How to upload with Heroku, Flask, Python, Git (4)
How to enjoy programming with Minecraft (Ruby, Python)
Put MicroPython on Windows to run ESP32 on Python
[2020 version] How to install Python3 on AWS EC2
Strategy on how to monetize with Python Java
How to install OpenCV on Jetson Nano Python
How to use Python Kivy ④ ~ Execution on Android ~
How to run some script regularly in Django
How to run Leap Motion in non-Apple Python
[Python] How to install OpenCV on Anaconda [Windows]
Run Python on Apache to view InfluxDB data
How to run GUI programs such as tkinter in Python environment on WSL2
How to run a Django application on a Docker container (development and production environment)
How to install Python
Run Django on PythonAnywhere
How to install python
[Python] How to run Jupyter-notebook + pandas + multiprocessing (Pool) [pandas] Memo
Think about how to program Python on the iPad
[Python] [Django] How to use ChoiceField and how to add options
How to embed mod_wsgi into Apache on Python Windows
How to run python in virtual space (for MacOS)
How to deploy a Django application on Alibaba Cloud
How to upload with Heroku, Flask, Python, Git (Part 3)
How to run tests in bulk with Python unittest
Memo of deploying Django × Postgresql on Docker to Heroku
How to run Self bot on Discord.py [Easy vandalism! ]
How to upload with Heroku, Flask, Python, Git (Part 1)
How to run setUp only once in python unittest
How to upload with Heroku, Flask, Python, Git (Part 2)
python, php, ruby How to convert decimal numbers to n-ary numbers
How to enjoy Python on Android !! Programming on the go !!
How to build a Python environment on amazon linux 2
How to handle JSON in Ruby, Python, JavaScript, PHP
[2020.8 latest] How to install Python
Run Openpose on Python (Windows)
How to install Python [Windows]
How to install Python2.7 python3.5 with pyenv (on RHEL5 CentOS5) (2016 Nov)
How to run a trained transformer model locally on CloudTPU
Python on Ruby and angry Ruby on Python
python3: How to use bottle (2)
How to build a new python virtual environment on Ubuntu