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.
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.
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.
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.
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
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
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:
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
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.
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
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.
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
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.
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.
MVP #FridayFive: Fintech, HA PostgreSQL Cluster, Multi-Account Management, and Cybersecurity
How to Create a Django Rest Framework-GIS on Ubuntu 16.04 Server (Part 2)
2,599 posts | 762 followers
FollowAlibaba Clouder - March 18, 2019
Alibaba Clouder - December 17, 2018
Alibaba Clouder - December 26, 2018
Alibaba Clouder - August 2, 2018
Alibaba Clouder - August 9, 2019
Alibaba Clouder - March 22, 2019
2,599 posts | 762 followers
FollowElastic and secure virtual cloud servers to cater all your cloud hosting needs.
Learn MoreAn encrypted and secure cloud storage service which stores, processes and accesses massive amounts of data from anywhere in the world
Learn MoreMarketplace is an online market for users to search and quickly use the software as image for Alibaba Cloud products.
Learn MoreMore Posts by Alibaba Clouder