Running a Python application on your hosting package
With every package at mijn.host, you have the option to run a Python application. Before you can deploy an application, you will have to go through a few steps. We explain which steps those are in this knowledge base article.
What is important to know?
- Only perform these steps if there are no important websites running on your hosting. By following this knowledge base article, you will immediately deploy a Python application into production, which means there is a chance you could damage the current website.
- It is recommended to first create a staging or dev environment and not go directly into production.
- Wait before entering sensitive data into the test application until you know how the security of Django works.
Creating the application
Go to DirectAdmin, how to get there can be read in this article: https://mijn.host/kb/hoe-log-ik-in-op-directadmin/
Once you are logged into DirectAdmin, look in the left menu for Extra Features and then Setup Python App.
Next, click on Create Application to create your application.
You will now arrive at the following screen:
Here are a few important fields you need to fill in:
Python version: The version of Python you are working with. It is recommended to use version 3.9 or 3.10.
Application root: This is the directory in which you create the application, you can see it as the public_html directory in web development terms. Please note that you should not install a subdirectory to avoid problems with the pip installer.
Application URL: The default URL of your application, for example, you can enter je-domein.nl/applicatie or leave it empty for just je-domein.nl.
Application startup file: This is the directory where your application is fetched by the server. You can leave it empty when booting up for the first time.
Application entry point: This is the place where you link to your wsgi.py file, you can also leave this empty so that the default value is filled in.
Getting started with your new Python application.
Once you have created the python application, you will see the following screen:
Unlike web development, the content of your project does not go into the public_html directory, but in the kennisbank-demo directory as we just specified.
What is virtualenv?
At mijn.host you work with a virtualenv (virtual environment). A virtual "root" environment on your own hosting package. This allows you to keep all your pip packages and python versions separated should you want to run multiple applications. In short, it ensures that the software and modules do not conflict with each other but stay neatly with the application where they belong.
You can activate Virtualenv by entering the following commands via SSH:
See the image for where you can find your source link in your app:
We currently use:
source /home/jegebruikersnaam/virtualenv/kennisbankdemo/3.7/bin/activate && cd /home/jegebruikersnaam/kennisbankdemo
Don't know how to log in via SSH? Then you can use the following knowledge base article: https://mijn.host/kb/verbinden-met-ssh/
What is Django and how do you install it?
To stay somewhat in the web development sphere, this knowledge base article is focused on creating a web application. One of the popular choices you can make is the Django library. You can install Django on your application via SSH:
pip install --upgrade pip
pip install django "mysqlclient<2.0.2"
Afterwards, you can create the Django project with the following command, make sure you also include the . at the end:
django-admin startproject begin .
Adjusting the config file as desired
In your configuration file, you can specify things like your database credentials. You can adjust this in the settings.py file, this file only becomes active once you restart the Python application. You can restart the application in the admin panel of your Python application:
After you have restarted the Python application, you can add your own domain to the ALLOWED_HOSTS so that django also recognizes it. Next, you add the STATIC_ROOT, this is how you let django know where the static files from your application should be stored. You need to make these changes in the settings.py:
ALLOWED_HOSTS = ['jouw-domein.nl']
DEBUG = False
STATIC_ROOT = '/home/jegebruikersnaam/domains/jouw-domein.nl/public_html/static'
In the same file you also indicate where Django can log to:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': '/home/jouw-gebruikersnaam/project-naam/django.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
},
}Note that you must create the django.log file first, you can do this in the command line with the following command:
touch django.log
Then you indicate which database is being used:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database_naam ',
'USER': 'database_gebruiker ',
'PASSWORD': 'database_wachtwoord',
'HOST': 'localhost',
'PORT': '3306',
}
}Starting with the first test page
Now that the settings have been discussed, it is time to test if the application works. We do this using a hello-world page. Start the app as follows:
python manage.py startapp start
This will create the 'start' directory. In this directory you can modify the view for your test page. Replace the content in start/views.py with the following code snippet:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hallo mijn.host kennisbank, de testpagina werkt!")
With the following code snippet you can ensure that 'start' can be loaded in the main application (demo/urls.py):
from django.contrib import admin
from django.urls import path
from start.views import index
urlpatterns = [
path('', index),
path('admin/', admin.site.urls),
]
As a final step, add the changes to the list of INSTALLED_APPS in settings.py; here you insert the string* 'start'.
*A string is a data type that only contains letters.
The final steps to go live
The code for the test page is now complete and you can almost go live with your test application. There are a few more things that are good to execute. One of those things is the virtualenv that was discussed earlier in this knowledge base article. Use the command to activate your virtualenv (also see the heading what is virtualenv?).
After that, you can use the manage.py file to prepare your application for use:
python manage.py collectstatic
python manage.py migrate
python manage.py createsuperuser
Just like with WordPress, for example, Django also has an admin section:
- Collectstatic: This places the CSS and JavaScript files in the public_html folder.
- Migrate: Is the initial database structure that the Django admin needs.
- Createsuperuser: This is the account with the most permissions, also known as the administrator account.
Activating the application
Then it is finally time to activate the application; you only need to let python know where it can load the application. Go to the admin panel in python and change passenger_wsgi.py to demo.py. Save the changes and click on restart to apply the changes.
As you can see, we successfully displayed our test page:
A working admin section:
Known error codes
403 Forbidden: Check if the application is active and if the correct wsgi.py is configured.
404 Not found: This means that a file or files cannot be found, which prevents the application from loading. Check the settings you entered in the python admin section again.
500 Internal Server Error: Look in the Django log for more information.
Can’t acquire lock for app:
No styling: It can happen that the Django admin section does not look the way it should. Check if the static folder in the public_html folder is populated with files. If this is not the case, check the STATIC_ROOT setting and whether the STATIC_URL points to the correct static folder and use the following command:
python manage.py collectstatic
Still have questions? Get in touch.