Linux apache postgresql python

Focus on Scientific Research

Deploy A Django Application on Ubuntu Using Apache and PostgreSQL

Posted on 2023-02-08 In Tutorials , Ubuntu , PostgreSQL , Django Views: Valine:
Symbols count in article: 12k Reading time ≈ 11 mins.

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. In this tutorial, I will teach you to install, develop and deploy a web application step by step using Django, Apache and PostgreSQL on Ubuntu 18.04.

Prerequire Installation

Install and Use Python3 and Pip3

The default python on Ubuntu 18.04 is python2, which will be deprecated in future. Django recommend us to use python3 which we have a better compatibility and performance.

Install Python3

sudo apt-get update
sudo apt-get install python3 libexpat1

Set Python3 as Default Python

sudo rm -rf /usr/bin/python
ln -s /usr/bin/python3 /usr/bin/python

Install Pip3

apt-get install python3-pip

Set Pip3 as Default Pip

ln -s /usr/bin/pip3 /usr/bin/pip
pip install —upgrade pip

Install Apache with mod_wsgi Module

Deploying Django with Apache and mod_wsgi is a tried and tested way to get Django into production. mod_wsgi is an Apache module which can host any Python WSGI application, including Django. Django will work with any version of Apache which supports mod_wsgi.

Install

sudo apt-get install apache2 apache2-utils ssl-cert libapache2-mod-wsgi-py3

Restart

sudo systemctl restart apache2

Install PostgreSQL

PostgreSQL is an advanced open source relational database. It has a better performance than django’s default database SQLite, therefore here I use PostgreSQL as Django’s database.

Install

sudo apt-get update
sudo apt-get install postgresql postgresql-contrib
pip install psycopg2

Check Status

service postgresql status

Django Installation

After finish the installation of python3, pip3, apache and postgresql, we can install django now. The latest version of Django is 4.1, however I install 3.2.13 to avoid compatibility problems and other unpredictable bugs.

Install Django

Install

Verify Installation

python -m django —version
python
import django
print(django.get_version())

Install Required Packages (Optional, you can skip this step)

Install REST Framework

pip install djangorestframework

Читайте также:  Управление оперативной памятью linux
Install PhoneNumberField

pip install django-phonenumber-field
pip install phonenumbers

Install Image API

pip install pillow
pip install drf-extra-fields

Install cleanup

pip install django-cleanup
INSTALLED_APPS = (
.
‘django_cleanup.apps.CleanupConfig’, # should be placed after your apps

)

Develop Django Application

Create Project

django-admin startproject mysite
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py

Deploy Project

Run Server

python manage.py runserver 0.0.0.0:8080

Open Port

Create App

api/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

Install App

INSTALLED_APPS = (
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘api’,
)

  • Difference between project and application in Django
    An app is a web application that does something – e.g., a blog system, a database of public records or a small poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

Create Super User and Login

We’ll need to create a user who can login to the admin site. Run the following command:

python manage.py createsuperuser

Input the user name, email address and password, the above command will create a super user for mysite. Then we can login http://127.0.0.1:8080/admin/ as an administrator and manipulate the data defined by Django’s model.

Make Migrations

When we define new models or change the defined models, we need let django known the definitions and changes by the following commands.

python manage.py makemigrations
python manage.py migrate

Deploy Django Application Using Apache2

Although we can serve the django application using the command ‘python manage.py runserver 0.0.0.0:8080’, it is not recommended to use this command to deploy Django’s application. Because this command is designed for developing and debug. It’s performance is poor and it will runout the server’s memory when the application is visited in high concurrency. Apache is a famous open-source HTTP server for modern operating systems Unix and Windows. The official documents of Django recommends us to use Apache to deploy Django’s application.

There are two points we need to know before we take further steps into apache configuration.

├── apache2.conf
├── conf-available
├── conf-enabled
├── envvars
├── magic
├── mods-available
├── mods-enabled
├── ports.conf
├── sites-available
└── sites-enabled
├── access.log
├── error.log
├── other_vhosts_access.log

Set Port

The default port is 80 for http, but we can use other ports if port 80 is reserved. Open ports.conf and listen the port we want to use for Django application.

And add the following configuration to let apache listen 8080 port.

Enable Rewrite Module

Rewrite Module is a rule-based rewrite engine and it rewrites the requested URLs by the defined rules using regular-expression parser. Usually, it is used to redirect one URL to another URL. Here will use it to redirect http request to https request, which is more secure.

Configure Site

There is a default enabled site defined in 000-default.conf. Here we edit this site configuration to deploy Django application.

cp /etc/apache2/sites-available/000default.conf /etc/apache2/sites-available/000default.conf.cp
vi /etc/apache2/sites-available/000default.conf

Читайте также:  Cracking wifi with linux

And replace the default configuration with the following one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
8080>
# ServerName 172.30.92.118
# ServerAlias zhaoyongsheng.com
# ServerAdmin yongsheng.zhao.csc@gmail.com

WSGIScriptAlias / /django/servo/servo/wsgi.py

ProxyPass /media/ !
Alias /media/ /django/media/
ProxyPass /static/ !
Alias /static/ /django/servo/static/

/django/media>
Require all granted

/django/servo/static>
Require all granted

# WSGIDaemonProcess blog python-home=/home/sammy/myproject/myprojectenv python-path=/home/sammy/myproject
# WSGIProcessGroup %
# WSGIDaemonProcess ziqiangxuetang.com python-path=/home/tu/blog:/home/tu/.virtualenvs/blog/lib/python2.7/site-packages
# WSGIProcessGroup ziqiangxuetang.com
# WSGIApplicationGroup %

/django/servo/servo>

Require all granted
ErrorLog $/error.log
CustomLog $/access.log combined
# RewriteEngine on
# RewriteCond % !=on
# RewriteRule ^(.*) https://%$1 [L,R]

The first bit in the WSGIScriptAlias line is the base URL path you want to serve your application at (/ indicates the root url), and the second is the location of a “WSGI file” . And the piece ensures that Apache can access your wsgi.py file.

  • ** ProxyPass /static/ !** – Do not deal with /static/ urls, otherwise it will add a static/ prefix to the url, such as make “static/admin/base.html” as “static/static/admin/base.html”, for more details please visit the Static and media files
  • Alias /media/ /django/media/ – Let apache know where the media directory is.
  • Alias /static/ /django/servo/static/ – Let apache know where the static directory is.
    The official documents provides more details about how to deploy Django using apache.

Config Apache

The apache’s configuration file is in /etc/apache2/apache2.conf. Similarly, we had better make a copy of the default apache2.conf before modified it.

cp /etc/apache2/apache2.conf /etc/apache2/apache2.conf.cp
vi /etc/apache2/apache2.conf

Find and edit the following lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Directory/>
160 Options FollowSymLinks
161 AllowOverride None
162 Require all granted
163 Directory>
164
165 Directory /usr/share>
166 AllowOverride None
167 Require all granted
168 Directory>
169
170 #
171 # Options Indexes FollowSymLinks
172 # AllowOverride None
173 # Require all granted
174 #
175
176 #
177 # Options Indexes FollowSymLinks
178 # AllowOverride None
179 # Require all granted
180 #

Add the following line at the end of the file.

WSGIPythonPath /django/servo

WSGIPythonPath ensures that your project package is available for import on the Python path; in other words, that import servo works.

Close Debug Mode in Django

Django’s debug mode can print logs which is useful for debug, but its performance is poor. Thus we had better close the debug mode before serving it to web.

vi /django/servo/servo/settings.py

Find the line DEBUG = True, and set it as False.

Change Owner of Django Directory

Generally, the owner of django’s directory is the admin user of the operation system. We must change the owner to apache to let it have full access to Django’s directory.

cd /
chownR www-data:www-data django

Restart Apache

Finishing the above steps, restart apache to deploy Django’s application.

Now we can visit the Django’s application via http:xxx.xxx.xxx.xxx:8080/admin/. Congratulations!
If there are any problems, feel free to contact me.

Читайте также:  Astra linux удаленный доступ anydesk

Warnings, Errors And Solutions

AH00558: apache2: Could not reliably determine the server’s fully qualified domain name, using 172.30.92.119. Set the ‘ServerName’ directive globally to suppress this message

Apache uses the ServerName directive to map incoming HTTP requests to an IP address or DNS hostname using VirtualHost directives in order to handle requests for multiple sites using a single server. The error message notes that a global ServerName directive should also be set. Doing so will ensure that Apache can gracefully handle incoming requests that do not map to a VirtualHost without generating additional errors.

For maximum compatibility with various Apache configurations, use the value of 127.0.0.1 for your global ServerName directive. You can use a different IP address or DNS name that corresponds to your server’s configuration if you need to, but it is safest to use 127.0.0.1.

Open the /etc/apache2/apache2.conf file using vim.

And add the following line to the end of the file.

. . .
# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
ServerName 127.0.0.1

Then restart apache and the AH00558 error will disappear.

Authentication credentials were not provided.

The token authentication works well when I run django project using python manage.py runserver 0.0.0.0:8080. I met this error when running django project using apache2. Obviously, this error is a privilege problem. Since I deploy django using wsgi module, I can enable WSGIPassAuthorization to solve this problem.
Open the site configuration file using vim.

vi /etc/apache2/sites-enabled/000default.conf

And put the following line to the file.

Источник

Запуск веб-сервера Apache в связке с Python 3 и СУБД на CentOS Stream 8

Краткая инструкция по быстрому запуску веб-сервера Apache HTTP Server с Python 3 и системами управления базами данных MariaDB (MySQL) и PostgreSQL на ОС CentOS Stream 8.

Для начала необходимо установить СУБД MariaDB и/или PostgreSQL. Инструкции по установкам находятся по следующим ссылкам:

Затем устанавливаем Apache и Python 3.9 с модулями для работы с СУБД

# yum install httpd python39 python39-pip python39-psycopg2 python39-mod_wsgi

и запускаем и включаем в автозагрузку службу httpd

# systemctl start httpd # systemctl enable httpd

Если в дальнейшем будет использоваться СУБД MariaDB (MySQL), тогда установим для него модуль через pip

# pip3 install mysql-connector-python39

Теперь отключаем SELINUX. Открываем файл

и изменяем значение SELINUX на disabled:

а также выполняем команду

Вместе с этим создадим необходимые правила для файрволла

# firewall-cmd --add-service=http --zone=public --permanent # firewall-cmd --add-service=https --zone=public --permanent # firewall-cmd --reload

После этого создаём каталог /var/www/scripts/, в котором будут храниться скрипты Python

Далее открываем файл конфигурации Apache

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
ScriptAlias /scripts/ "/var/www/scripts/"
 AllowOverride None Options None Require all granted 
 Options ExecCGI Indexes AddHandler cgi-script .cgi .py AddHandler wsgi-script .wsgi Require all granted 

Затем перезапускаем Apache

и проверяем что у нас получилось.

Создаём простой скрипт /var/www/scripts/welcome.py, зададим ему необходимые права, а также открываем его

# touch /var/www/scripts/welcome.py # chmod 755 /var/www/scripts/welcome.py # vi /var/www/scripts/welcome.py

впишем в него страницу приветствия:

#!/usr/bin/python3 print('Content-Type: text/html; charset=utf-8') print('') print('

Добро пожаловать на страницу Python

')

На другой машине в сети в адресной строке браузера вводим: http://IP_или_хост_сервера/scripts/welcome.py и увидим страницу с текстом «Добро пожаловать на страницу Python».

Похожие посты:

Источник

Оцените статью
Adblock
detector