×
Community Blog How to Create a Django Rest Framework-GIS on Ubuntu 16.04 Server (Part 1)

How to Create a Django Rest Framework-GIS on Ubuntu 16.04 Server (Part 1)

In this tutorial, we will create a GIS Django REST framework on an Alibaba Cloud Elastic Compute Service (ECS) instance with Ubuntu 16.04.

By Grace Amondi, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

Django REST Framework is a powerful and flexible toolkit for building Web APIs. Django REST Framework-GIS is a geographic add-on for Django REST Framework. In this tutorial, we are going to go through a step-by-step process of creating a GIS Django REST framework on an Alibaba Cloud Elastic Compute Service (ECS) instance with Ubuntu 16.04.

Part 1 will involve an introduction to Django Rest Framework and initial setup of the Django application environment.

Why You Should Use Django REST Framework

1.  The Web browsable API is a huge usability win for developers.
2.  Authentication policies including packages for OAuth1a and OAuth2.
3.  Serialization that supports both ORM and non-ORM data sources.
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
4.  Customizable all the way down - just use regular function-based views if you don't need the more powerful features.

Prerequisites

For you to successfully complete this tutorial. you will need to have:
1.  A valid Alibaba Cloud account. If you don't have one already, sign up to the Free Trial to enjoy up to $300 worth in Alibaba Cloud products.
2.  An ECS instance running Ubuntu 16.04. You can select your preferred region and configurations; this will not affect the outcome of the server setup.
3.  A root password for your server.
4.  Geodjango Setup on your ECS instance.

Step 1: Install Packages from Ubuntu Repositories

We will be using python package manager pip to install python components.We will be using python 3 so we need to run the commands:

$ sudo apt-get update
$ sudo apt-get install python3-pip python3-setuptools python3-dev libpq-dev postgresql postgresql-contrib nginx

Install Postgis:

$ sudo apt-get install -y postgis postgresql-9.5-postgis-2.2

This will install pip, the Python development files needed to build Gunicorn later, the Postgres database system and the libraries needed to interact with it, and the Nginx web server.

Step 2: Create a PostgreSQL Database and User

We will need to create a potgreSQL database.Switch over to the postgres account on your server by typing

$ sudo -u postgres psql

You will be logged in and able to interact with the database management system right away.

Create a database named geoapi.

potgres=# CREATE DATABASE geoapi;

Next create a database user for your project and use a secure password:

postgres=# CREATE USER yourprojectuser WITH PASSWORD 'yourpassword';

and add PostGIS extension.PostGIS is an open source software program that adds support for geographic objects to the PostgreSQL object-relational database.

$potgres=# CREATE EXTENSION postgis;

We are setting the default encoding to UTF-8, which Django expects. We are also setting the default transaction isolation scheme to "read committed", which blocks reads from uncommitted transactions. Lastly, we are setting the timezone. By default, our Django projects will be set to use UTC. These are all recommendations from the Django project itself:

potgres=# ALTER ROLE yourprojectuser SET client_encoding TO 'utf8';
potgres=# ALTER ROLE yourprojectuser SET default_transaction_isolation TO 'read committed';
potgres=# ALTER ROLE yourprojectuser SET timezone TO 'UTC';
postgres=# ALTER ROLE yourprojectuser SUPERUSER;

Now, we can give our new user access to administer our new database:

postgres=# GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

exit with $ \q

Step 3: Create a Python Virtual Environment

The main purpose of Python virtual environments is to create an isolated environment for Python projects. This means that each project can have its own dependencies, regardless of what dependencies every other project has.

First upgrade pip then install virtualenv package using:

$ sudo -H pip3 install --upgrade pip
$ sudo -H pip3 install virtualenv

Create a directory where the project will be housed:

$ mkdir geoapi
$ cd geoapi

Next create a virtual environment by running the following command:

$ virtualenv geoapienv

This will create a virtual environmnet named geoapi where we will be able to install dependancies for this project.
Finally activate the virtualenv using:

$ source geaopienv/bin/activate

Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this: (geoapienv)user@host:~/geoapit$

With your virtual environment active, install Django, Gunicorn, and the psycopg2 PostgreSQL adaptor with the local instance of pip:

$ pip install django==1.11.5 gunicorn psycopg2

Step 4: Create a Django Project

Creating a django project is very easy. To create a project all you need to do is run the following command within your project directory:

$ django-admin.py startproject geoapi

This will create an folder named geoapi. Let's look at what startproject created

geoapi/
    manage.py
    geoapi/
        __init__.py
        settings.py
        urls.py
        wsgi.py

These files are:

  • The outer geoapi/ root directory is just a container for your project. Its name doesn't matter to Django; you can rename it to anything you like.
  • manage.py : A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py.
  • The inner geoapi/ directory is the actual Python package for your project. Its name is the Python package name you'll need to use to import anything inside it (e.g. geoapi.urls).
  • geoapi/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If you're a Python beginner, read more about packages in the official Python docs.
  • geoapi/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
  • geoapi/urls.py: The URL declarations for this Django project; a "table of contents" of your Django-powered site. You can read more about URLs in URL dispatcher.
  • geoapi/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.

Step 5: Create a Django Application

Your apps can live anywhere on your Python path. In this tutorial, we'll create our REST API app right next to your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.

To create your app, make sure you're in the same directory as manage.py and type this command:

$ geoapi/manage.py startapp mygeoapi

That'll create a directory mygeoapi, which is laid out like this:

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

This directory structure will house the mygeoapi application.

What's the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple 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.

Next thing we should do is adjust the django settings for the project.Using your text editor head over to geoapi/geoapi/settings.py and edit as follows.

$ nano geoapi/geoapi/settings.py

In the allowed hosts section,list the IP addresses or domain names that are associated with your Django server.

. . .
# The simplest case: just add the domain name(s) and IP addresses of your Django server
# ALLOWED_HOSTS = [ 'example.com', '203.0.113.5']
# To respond to 'example.com' and any subdomains, start the domain with a dot
# ALLOWED_HOSTS = ['.example.com', '203.0.113.5']
ALLOWED_HOSTS = ['your_server_domain_or_IP', 'second_domain_or_IP', . . .]

Next change the database configurations in the same file to something like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'geoapi',
        'USER': 'yourprojectuser',
        'PASSWORD': 'yourprojcetpassword',
        'HOST': 'localhost',
        'PORT': ''
    }
}

Finally let's indicate where the static files should be placed. This is necessary so that Nginx can handle requests for these items.Add the following to the bottom of the settings.py file.

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

Let's collect all the static content into the directory we configured.The static files will be placed in a directory called static within your project directory.:

$ geoapi/manage.py collectstatic

In order to test the development server, we'll have to allow access to the port we'll be using.

Create an exception for port 8000 by typing:

$ sudo ufw allow 8000

Let's make sure that our app is fuctioning well. Run the following command to check our progress then open the development server in your browser and you will see a congratulations message.:

$ geoapi/manage.py runserver 0.0.0.0:8000

In your web browser, visit your server's domain name or IP address followed by :8000:

http://server_domain_or_IP:8000

Step 6: Install Django Rest Framework-GIS

You can do a $ pip freeze to check installed requirements. There is none in the meantime. There are requirements we need so lets install django-rest-framework by

$ pip install djangorestframework

then django-rest-framework-gis by

$ pip install djangorestframework-gis

Next we need to add these requirements to the installed apps in geoapi/settings.py file that we created.

INSTALLED_APPS = [
    # ...
    'rest_framework',
    'rest_framework_gis',
    # ...
]

Now lets run $ geoapi/manage.py migrate

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your geoapi/settings.py file and the database migrations shipped with the app.

Next create an administrative user for the project by typing:

$ geoapi/manage.py createsuperuser

You will have to select a username, provide an email address, and choose and confirm a password.

Step 7: Making Our Project Spatial

So far so good. But it is not yet spatial. To make it geospatial head over to settings.py and add django.contrib.gis to the list of installed apps. We are also going to need to install pyscopg2. Psycopg is a PostgreSQL adapter for the Python programming language. It is a wrapper for the libpq, the official PostgreSQL client library.

$ pip install psycopg2

and leaflet is an open-source JavaScript library for mobile-friendly interactive maps.

$ pip install django-leaflet

add leaflet to the list of installed apps in geoapi/settings.py

INSTALLED_APPS = [
    ...
    'leaflet',
]

Run the following command to add your installed requirements to a requirements.txt file.

$ pip freeze > requirements.txt

Step 8: Testing Gunicorn's Ability to Serve the Project

We can do this by using gunicorn to load the project's WSGI module:

$ gunicorn --bind 0.0.0.0:8000 geoapi.wsgi

This will start Gunicorn on the same interface that django development server was running.

Step 9: Create a Gunicorn systemd Service File

We have successfully tested that Gunicorn can interact with the server but we need a better way of starting and stopping the application server.

Create and open a systemd service file for Gunicorn with sudo privileges in your text editor:

$ sudo nano /etc/systemd/system/gunicorn.service

Add the following to the file:

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=username
Group=www-data
WorkingDirectory=/home/username/geoapi
ExecStart=/home/username/geoapi/geoapienv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/username/geoap/geoapi.sock geoapi.wsgi:application

[Install]
WantedBy=multi-user.target

Unit section, which is used to specify metadata and dependencies.

Service section specifies the user and group that we want to process to run under.

Install section tells systemd what to link this service to if we enable it to start at boot.

With that, our systemd service file is complete. Save and close it now.

We can now start the Gunicorn service we created and enable it so that it starts at boot:

$ sudo systemctl start gunicorn
$ sudo systemctl enable gunicorn

Step 10: Configure Nginx to Proxy Pass to Gunicorn

We now need to configure Gunicorn to pass traffic to the process.Start by creating and opening a new server block in Nginx's sites-available directory:

$ sudo nano /etc/nginx/sites-available/geoapi

Add the following to the file:

server {
    listen 80;
    server_name server_domain_or_IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/username/myproject;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/username/geoapi/myproject.sock;
    }
}

Save and close the file when you are finished. Now, we can enable the file by linking it to the sites-enabled directory:

$ sudo ln -s /etc/nginx/sites-available/geoapi /etc/nginx/sites-enabled

Test your Nginx configuration for syntax errors by typing:

$ sudo nginx -t

If no errors are reported, go ahead and restart Nginx by typing:

$ sudo systemctl restart nginx

Finally, we need to open up our firewall to normal traffic on port 80.

$ sudo ufw allow 'Nginx Full'

You should now be able to go to your server's domain or IP address to view your application.

Conclusion

In Part 2, we will look at the final steps into bringing the Django REST API to an end. We will be looking at working on creating models, views and populating our database as well as adding authentication to the REST API.

0 1 1
Share on

Alibaba Clouder

1,410 posts | 219 followers

You may also like

Comments

Alibaba Clouder

1,410 posts | 219 followers

Related Products