Python

Aus Meine Wiki
Zur Navigation springen Zur Suche springen

How to run Python scripts in a web page

Install Apache on CentOS 7

1. CentOS 7 Server Minimal Install.

2. Update CentOS

- 1. First update the system software packages to the latest version.

   # yum udpate

- 2. Next, install Apache HTTP server from the default software repositories using the YUM package manager as follows.

   # yum install httpd

- 3. Once Apache web server installed, you can start it first time and enable it to start automatically at system boot.

   # systemctl start httpd
   # systemctl enable httpd
   # systemctl status httpd

- 4. Configure firewalld to Allow. Apache TrafficBy default, CentOS 7 built-in firewall is set to block Apache traffic.

   # firewall-cmd --zone=public --permanent --add-service=http
   # firewall-cmd --zone=public --permanent --add-service=https
   # firewall-cmd --reload


- 2.1 Update system:

   # yum update

- 2.2 Install mod_wsgi with the command:

   # yum install mod_wsgi

- 2.3 Restart Apache:

   # systemctl restart httpd

- 2.4 Verify that the module is loaded:

   # httpd -M | grep wsgimixed
   The server will respond with:
   [root@localhost ~] # sudo httpd -M | grep wsgi
    wsgi_module (shared)

- 2.5 Configure Apache For security reasons, the Python scripts should be stored in a directory which is not available on the web. Create this directory:

   mkdir /var/www/pythonmixed

- 2.6 Set Apache as the owner of this directory, so that it can access the files:

   chown apache:apache /var/www/pythonmixed

- 2.7 We will use WSGIScriptAlias to configure an alias to the script. Access rights will also need to be granted to the directory where the script is located.

- 2.8 Create an Apache configuration file for an example "Hello World" script, and open it for editing:

   vi /etc/httpd/conf.d/helloworld.confmixed

- 2.9 Put the following content into this file:

WSGIScriptAlias /helloworld /var/www/python/helloworld.py


   <Directory /var/www/python>
   Order allow,deny
   Allow from all
   </Directory>

- 2.10 Save and exit the file. Then restart Apache:

   sudo systemctl restart httpdmixed

- 2.11 Create Test Script Use the official recommended mod_wsgi Hello World test script for this example.

- 2.12 Create the file and open it for editing:

   vi /var/www/python/helloworld.pymixed 

Put the following content into this file:

 def application(environ, start_response):
     status = '200 OK'
     output = b'Hello World!'
     response_headers = [('Content-type', 'text/plain'),
                       ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]mixed

- 2.13 Save and exit the file. Then set Apache as the owner of this file, so that it can be accessed:

    chown apache:apache /var/www/python/helloworld.py