•   Lab AI
  • Oct 25, 2019
  • Tags Python

Python Webservice API Server deployment using Ubuntu

Python Flask Restful API implementation in Ubuntu using Nginx and Gunicorn

https://gunicorn.org/Flask is a Python web framework alternative to Django projects with their monolithic structure and dependencies. It is built with a small core and easy-to-extend philosophy. With flask, you can create web services or Restful APIs in no time. 

fromArticle


If we want to implement a Flask API into our servers we need to follow some tasks and installations. 


* For this tutorial, we are assuming that you have knowledge in connecting to your server and Python programming...

Please notice that you can also use Supervisor as a client/server system to monitor and control a number of processes on UNIX.

Also, we will be implementing it in HTTP protocol. The installations of an SSL certificate in the server is out of the scope of this tutorial. 



Here we will use the following architecture because (in my opinion) it is easier to understand for beginners.

fromArticle


The server will execute via a service the commands to call for Nginx using a WSGI with Gunicorn.  Flask will work as the web service Framework which will be implemented in the Python code.  

Step 1 -  Installations 

After connecting to the server via command, we will first update then install the packages for python, and nginx.

$ sudo apt-get update

$ sudo apt-get install python3-pip python3-dev nginx


After installing python and nginx we will proceed with the installation of virtualenv to create Virtual Environments. 

$ sudo pip3 install virtualenv

Step 2 -  Create a Virtual Environment 


Create a new folder and cd the folder. Our folder in this tutorial is going to be called "myflaskproject".  

For example:   mkdir myflaskproject ; cd myflaskproject

To create a new virtual environment called “myfirstflask”  type 

$ virtualenv myfirstflask

Now to use the virtual environment we will need to activate it.  We will do it by using source name-of-virtualenv/bin/activate

$  source myfirstflask/bin/activate


Step 3 - Installing  Flask and Gunicorn

Gunicorn is a Python WSGI HTTP Server for UNIX, it is broadly compatible with many web frameworks, light on server resources and speedy.


So first we will need to Install Gunicorn in the server: 

$ sudo apt install gunicorn


While having the virtual environment activated use pip (even if we are using python3 at the virtual environments we use pip) to install flask and gunicorn 

$ pip install gunicorn flask


Step 4 - Hosting a demo file 


For this tutorial, we will create a hello word API to test the server configurations and hosting. 


Create a new mock file (helloworld.py) in the folder of our project myflaskproject. This file is doing to be very simple, just an json with the hello world message. 

helloworld.py:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/', methods=['GET'])

def helloWorld():

    if request.method == 'GET':        

        return jsonify({"PieceX tutorial": "HELLO WORLD"})    

if __name__ == "__main__":

    app.run(host='0.0.0.0')


The default port is 5000, therefore we need to open that port in our server. If you have a firewall or security group (AWS), you need to add an inbound rule to allow the port 5000 


At the server :

(myfirstflask) $ sudo ufw allow 5000


Now let’s test the configuration

(myfirstflask) $ python helloworld.py


Open your browser and type the domain name of your server or the IP following the port:5000

For example, 

http://domainOrIP:5000


You will have to be able to see your “hello world” application. 


WSGI


In order to tell Gunicorn how to interact with the applications, we need an entry point or wsgi. 


Create a new file called wsgi.py inside your project folder


(myfirstflask) $ sudo nano wsgi.py

Code for the file: 

wsgi.py: 

from helloworld import app


if __name__ == "__main__":

    app.run()



Here we will call our application helloworld.py by importing it and running the application. 


Now let’s bind the wsgi file with Gunicorn 

(myfirstflask) $ gunicorn --bind 0.0.0.0:5000 wsgi:app


Browse your domain/server IP at the port 500:

http://domainOrIP:5000


You should be able to see the same input as before. 


Now we will need to interrupt the hosting. Input CTRL-C to end the hosting. After interrupting the hosting we will also deactivate the virtual environment to proceed with the Nginx configurations and services. 


(myfirstflask) $ deactivate


Step 5 - Creating a service 

In order to run the application we will need a service. Notice that it’s better to use supervisor for this task. For this tutorial we will use a normal service to keep the application alive. 

When the server reboots it will automatically start Gunicorn and our application/website. 

In ubuntu the services are located in the folder:   /etc/systemd/system/ 


First we will test the logic in our service to verify that everything is ok: 

Type: 

$ /home/ubuntu/myflaskproject/myfirstflask/bin/gunicorn --workers 3 --bind unix:flaskproject.sock -m 007 wsgi:app


It should host your application in the port :80, so if you go to your browser and type your IP or domain it should return our Hello World message.



So we will create a new one. 


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


Our file will look like this: 

[Unit]

Description= This is a Gunicorn instance from PieceX tutorial for our hello world application 

After=network.target

[Service]

User=ubuntu

Group=www-data

WorkingDirectory=/home/ubuntu/myflaskproject

Environment="PATH=/home/ubuntu/myflaskproject/myfirstflask/bin"

ExecStart=/home/ubuntu/myflaskproject/myfirstflask/bin/gunicorn --workers 3 --bind unix:flaskproject.sock -m 007 wsgi:app

[Install]

WantedBy=multi-user.target


The [Unit] section is for metadata and dependencies, the description can be added to easily recognize the function of our services. The command After=network.target will tell our service to start it after the network target has been reachead. 

The [Service] section we specify the user who will execute our service (it should have enough privileges to do so).  We will use the default hosting group www-data since it already has the required permissions by default. 

WorkingDirectory is the path were our application is (think of something like apache /var/www/html) 

Environment=“PATH= we will use the path of our virtual enviroment. 


Finally we assign the execution of the service 

The [Install] section will tell when to start the service at boot. 

WantedBy=multi-user.target


After saving the file, we can start and enable the service. 

If you get an error in the file you will need to reload the services: sudo systemctl daemon-reload

$ sudo systemctl start flaskproject

$ sudo systemctl enable flaskproject


Step 6 - Nginx


Nginx is web server, just like apache, it also functions as a reverse proxy to handle requests and responses for Python WSGI. It is advisable that you use Nginx for Python instead of Apache. 


First we need to create the configuration file for the server to use the socket we just made in our service. 


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


Add the following: 


server {

    listen 80;

  server_name localhost;
    location / {

        include proxy_params;

        proxy_pass http://unix:/home/ubuntu/myflaskproject/flaskproject.sock;

    }

}


This will make the server listen to the port 80 by using the proxy_pass of our project’s socket. 


Then we need to add our file to the enable sites list. 


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


Remove the default Nginx site with the welcome page 


$ rm /etc/nginx/sites-enabled/default


Check for errors 

$ sudo nginx -t


You should get a message like the following: 

 

fromArticle


Restart the server 

$ sudo systemctl restart nginx


Since we don’t need the port 5000 to be open we will remove the access to the port 5000

$ sudo ufw delete allow 5000

$ sudo ufw allow 'Nginx Full'


That’s it! You should be able to see your rest API by browsing your domain/server IP:


http://domainOrIP


fromArticle

Here are some links that you might find helpful: 

Additional Images




Comments

Add your comment

user-symbol

Stay in touch

Get Practical Tips For Business and Developers.

Learn about PieceX Community Needs for Source Code Projects.

Be the First to Know PieceX Newest Free Community Code Projects.