Wednesday, August 21, 2019

Django + uWSGI + Ngnix Web Based API Solution




The API Server is tested on Ubuntu Linux 18.04 LTS
The design of the WebAPI server framework.




Required Package
Description
Python3
Python scripting language version 3
Nginx
Web Server
Django
Web framework supports WSGI protocol
uWSGI
Protocol is the connection between Nginx and Django


Package Installation
apt-get install nginx
apt-get install python3-pip
apt-get install unattended-upgrades

pip3 install django
pip3 install uwsgi


Web Content Directory Configuration

Create web directory on the WebAPI Linux Server
Initialising the web directory
mkdir -p /var/www/webapi/{media,static}
chown -R apiadmin:www-data webapi
chmod g+w -R webapi

cd /var/www/webapi
python3 manage.py migrate



To get the initial Django framework up and running.


Core Files
Description
settings.py
Django configuration file
urls.py
This module is pure Python code and is a mapping between URL path expressions to Python functions (under views).
views/index.py
This module is pure Python code and is a mapping to templates index.html file
template/index.html
html web content



 Django Configuration


Core Files
Description
settings.py
Django configuration file
urls.py
This module is pure Python code and is a mapping between URL path expressions to Python functions (under views).
views/index.py
This module is pure Python code and is a mapping to templates index.html file
template/index.html
html web content


Check modify the key settings in settings.py
DEBUG = True

ALLOWED_HOSTS = ['10.10.10.10', 'FQDN1']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

ROOT_URLCONF = 'webapi.urls'

WSGI_APPLICATION = 'webapi.wsgi.application'

TIME_ZONE = 'Pacific/Auckland'

SESSION_SAVE_EVERY_REQUEST = True


urls.py – basic forwarding for
from django.contrib import admin
from django.urls import path
from views import index

urlpatterns = [
    path('', index),
]


index.py
#!/usr/bin/env python3

from django.shortcuts import render
from django.http import HttpResponseRedirect

def index(request):
    if request.session.get('login_status', True):
        request.session.set_expiry(60)
        return render(request, '../templates/index.html')
    else:
        return HttpResponseRedirect('/accounts/login')


templates/index.html – start with basic html page
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>


Django framework verification
uwsgi --http :8080 --chdir /var/www/webapi --module webapi.wsgi


uWSGI Configuration




Core Files
Description
uwsgi.ini
uWSGI configuration file


/var/www/webapi/uwsgi.ini
# uwsgi.ini file
[uwsgi]

# Django-related settings
# the socket (use the full path to be safe
socket          = 127.0.0.1:8001
# the base directory (full path)
chdir           = /var/www/webapi

# Django's wsgi file
module          = webapi.wsgi

# the virtualenv (full path)
#home            = /path/to/virtualenv

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 2

# ... with appropriate permissions - may be needed
# chmod-socket    = 664
# clear environment on exit
vacuum          = true
enable-threads   = true



Ngnix Configuration 


 Web Server HTTPS Certificate

Create certificate
cd /etc/nginx/conf.d

openssl genrsa -des3 -out server.key 2048

openssl req -new -key server.key -out server.csr

openssl rsa -in server.key.org -out server.key

cp server.key server.key.org

openssl rsa -in server.key.org -out server.key


Define the SSL cert in the file /etc/nginx/sites-available/webapi-django
    ssl_certificate /etc/nginx/conf.d/server.crt;
    ssl_certificate_key /etc/nginx/conf.d/server.key;

Configure Ngnix web server
/etc/nginx/sites-available/webapi-django
# the upstream component nginx needs to connect to
upstream django {
    # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
    server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      443;
    ssl on;
    ssl_certificate /etc/nginx/conf.d/server.crt;
    ssl_certificate_key /etc/nginx/conf.d/server.key;
    # the domain name it will serve for
    server_name servername; # substitute your machine's IP address or FQDN
    root  /var/www/webapi;
    charset     utf-8;

    # max upload size
    client_max_body_size 500M;   # adjust to taste

    # Django media
    location /media  {
        alias /var/www/webapi/media;  # your Django project's media files - amend as required
    }

    location /static {
        alias /var/www/webapi/static; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     uwsgi_params; # the uwsgi_params file you installed
    }
}

server {
    # the port your site will be served on
    listen      80;

    # the domain name it will serve for
    server_name servername; # substitute your machine's IP address or FQDN
    rewrite ^(.*) https://$server_name$1 permanent;

}

Enable the site
cd ../sites-enabled/

rm default

ln -s ../sites-available/webapi-django .

systemctl restart nginx




Web Service Configuration 

webapi service configuration
/etc/systemd/system
[Unit]
Description=The NGINX HTTP WEBAPI
After=network.target

[Service]
User=www-data
Group=www-data
ExecStart=/bin/bash -c 'cd /var/www/webapi; uwsgi --ini uwsgi.ini'

[Install]
WantedBy=multi-user.target


Start / Restart / Stop webapi service
systemctl start webapi