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

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:

Install Postgis:

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

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

Create a database named geoapi.

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

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

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:

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

exit with

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:

Create a directory where the project will be housed:

Next create a virtual environment by running the following command:

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

Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this:

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

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:

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

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:

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

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.

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

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

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.

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.:

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:

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.:

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

Step 6: Install Django Rest Framework-GIS

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

then django-rest-framework-gis by

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

Now lets run

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:

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.

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

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

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

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

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

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:

Add the following to the file:

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:

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:

Add the following to the file:

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

Test your Nginx configuration for syntax errors by typing:

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

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

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.

Reference:https://www.alibabacloud.com/blog/how-to-create-a-django-rest-framework-gis-on-ubuntu-16-04-server-part-1_594585?spm=a2c41.12692263.0.0

Follow me to keep abreast with the latest technology news, industry insights, and developer trends.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store