Sunday, May 14, 2017

Hello World with Python

Contents

1.  Virtual box and Vagrant

2.  Install Apache

3.  Install MySQL

4.  Install Python

5.  Hello World with Python

Hello World with Python 3.5

We will create a "index.py" file to display "<H1>This is my first CGI script</H1> Hello, world!" in a browser. Create a file named as "index.py" at C:\MyVM\MyCentOs\. (I mean, inside the share folder of Vagrant). Inside index.py, write as follows:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

print("Content-Type: text/html\n\r")
print ("""
    <TITLE>CGI script ! Python</TITLE>
    <H1>This is my first CGI script</H1>
    Hello, world!
""")


Be careful, the line break type must be LF, not CR. Because we are using Linux that uses LF, if the line break type is CR, python doesn't work because it can't recognize the line breaks. 

Now do the following command on the Teraterm:

$ sudo vi /etc/httpd/conf/httpd.conf

To change the text, hit "a" on your keyboard then insert mode will start.
Detailed explanation (if you need it):
Press a on your keyboard to go into insert mode, then you can edit the file. Press escape key to stop the insert mode. After stopping the insert mode, press shift key + g to go to the lowest row. :wq or Shift + zz to save and close the file. You can go to command mode by pressing : on your keyboard. To save and quit by the command mode, input :wq and enter. To exit the file without saving the file, inout :q! and enter. To search a word, press ? then write a word what you want to search. For example, if you write ?aaa and press enter, "aaa" is searched and highlighted in the file. Press n to jump to next match.)
Add "ExecCGI" in the lines of "/var/www/html" as follows:

<Directory "/var/www/html">
    Options Indexes FollowSymlinks ExecCGI
    AllowOverride None
    Require all granted
</Directory>

And add .py to Access handler:
AddHandler cgi-script .cgi .py

Directory

Access handler

By the way, maybe Access handler is a comment at first:

Un-comment the AddHandler line:


Save and close it by ":wq".

Re-start Apache (httpd):

$ sudo systemctl restart httpd

If SELinux is enabled, we need to change the context too. Change it as follows:

$ sudo chcon -R -t httpd_sys_script_exec_t /var/www/html/index.py

Then, access to your index.py from your browser as follows:
http://192.168.33.10/index.py

Hello World!!

If it doesn't work and it shows 500 or 404 errors, do the following command to check the errors:

$ sudo less /var/log/httpd/error_log

You can see errors. Google the errors to deal with them.