Problem scenario
You want a REST API endpoint. How do you create a URL that is a proof-of-concept to trigger a Python program?
Solution
Prerequisites
i. You have installed Python 3. If you are using CentOS/RHEL/Fedora, run this: sudo yum -y install python3
ii. You need a web server installed. If you do not have one, install Apache web server.
iii. You must have PHP installed. To install it, run this command: sudo yum -y install php
Procedures
1. Create a file in /home/ec2-user/ called good.py with the following content:
# This was adapted from https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create a file handler
handler = logging.FileHandler('hello.log')
handler.setLevel(logging.INFO)
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# add the file handler to the logger
logger.addHandler(handler)
logger.info('Hello from contint')
2. Create a file in /var/www/html/ called good.php with the following content:
<html>
<body>
HELLO!
</body>
</html>
<?php
$command = escapeshellcmd('/usr/bin/python3 /home/ec2-user/good.py');
$output = shell_exec($command);
echo $output;
?>