CRC-Blogs

Making Python server using Restful Api and Flask on CentOS 7

1. Installing Python

First, you need to install Python using following command on CentOS terminal

# Yum install Python

 

2. Installing Flask

Once you have installed Python, install Flask using following command:

# Pip install Flask

 

3. Setting up virtual environment for development

Before starting, install virtual environment for python using command

 # Pip install virtualenv

After installation, create a new environment by using following command:

# Virtualenv envPY

 It will show the output as:

[root@localhost ~]# virtualenv envPY

No LICENSE.txt / LICENSE found in source

New python executable in /root/envPY/bin/python2

Also creating executable in /root/envPY/bin/python

Installing setuptools, pip, wheel...

done.

Now you need to activate the virtual environment using command as:

# Source envPY/bin/activate

 This will show an output as:

# (envPY) [root@localhost ~] #

4. Creating Flask Application:

Navigate to envPY root, create a file test.py and write the following script:

from flask import Flask

app = Flask(__name__)

@app.route('/')

def index():

return 'Connected to Server'

@app.route('/Hello')

def say_hello():

return 'Hello World'

 

5. Running Flask Test Application:

Before running the python script, you need to set the environment to development and tell your terminal to work by exporting FLASK_APP environment. Use following commands for setting up development environment.

# Export FLASK_ENV=development

# Export FLASK_APP=app.py

To run you sample test, use command

# Flask run

This will show the following output on terminal of CentOS:

(envPY) [root@localhost ~]# flask run

* Serving Flask app "test.py" (lazy loading)

* Environment: development

* Debug mode: on

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

* Restarting with stat

* Debugger is active!

* Debugger PIN: 162-483-712

Now, try to access the results on your browser using the mentioned address, it should return the following outputs:

 a. Initial Connection to Server:

 b. Printing ‘Hello World’ on a separate page:

You have now successfully created a python server using Flask, having the default port as 5000.

You can now mix up more into this for returning string or json responses.