In the first step, you need to install the latest version of Python. For this purpose, open the terminal of CentOS and run the following command.
# yum install Python
Setup Virtual Python Environment:
Before starting, install a virtual environment for python using the command
# pip install virtualenv
After installation, create a new environment by using the 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
Now, you need to activate the virtual environment using the command as:
# source envPY/bin/activate
This will show output as:
# (envPY) [root@localhost ~] #
Once you are finished with the virtual environment, you need to install the Flask library by using the following command in the next step.
# pip install flask
Create Restful API using Python-Flask:
Navigate to envPY root, create a file restapi.py and write the following script:
from flask import Flask
app = Flask(__name__)
return 'Connected to Server'
return 'Hello World'
Run Flask Application:
After saving the above-mentioned script, you need to set the environment to develop and tell your terminal to work by exporting the FLASK_APP environment. Use the following commands for setting up a development environment:
# export FLASK_ENV=development
# export FLASK_APP=app.py
To run the application, use the following command:
# flask run
This will show the following output on your terminal:
(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 localhost address “http://127.0.0.1:5000/” address.
If you want to route to another page, as mentioned in our API, use the localhost address “http://127.0.0.1:5000/Hello”.