Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGIHTTPRequestHandler run php or python script in python

I'm writing a simple python web-server on windows..

it works but now I want to run dynamic scripts (php or py) and not only html pages..

here is my code:

from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler

class RequestsHandler(CGIHTTPRequestHandler):
    cgi_directories = ["/www"] #to run all scripts in '/www' folder
    def do_GET(self):
        try:
            f = open(curdir + sep + '/www' + self.path)
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        except IOError:
            self.send_error(404, "Page '%s' not found" % self.path)

def main():
    try:
        server = HTTPServer(('', 80), RequestsHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

if __name__ == '__main__':
    main()

if I put php code in www folder I get the page but the code isn't interpreted

what I have to do? thanks

like image 413
frx08 Avatar asked Jan 20 '23 05:01

frx08


1 Answers

Your First Python CGI Website

For someone making their first web server, I put this simple example together with all the needed steps to get it working. There are two files that need to be created. The first, server.py is the script that runs the web server. The second is a Python CGI script that the server will run and send its output to the browser as a "web page".

First create a project folder for the server, something like simple_server in your home directory, or wherever you like to put your projects.

In that folder create a subfolder called cgi-bin. Then copy the first script to a file, server.py and place that in simple_server. Then create the file, my_cgi_script.py and place that in the cgi-bin folder. These files are below in the body of this howto.

Directory structure should look like this:

|
-- [simple_server]
      |
      -- server.py
      |
      -- [cgi-bin]
            |
            -- my_cgi_script.py

You will need to set the permissions on my_cgi_script.py to make it executable - otherwise the web server can't run it to generate the web page output. If you're on Linux or MacOS, in the command shell enter:

$ chmod +x cgi-bin/my_cgi_script.py

On Windows, locate the file with the file explorer and right-click it, and make sure its permissions allow execution.

Open the command shell, and cd in to the simple_server folder and execute the server.py script:

$ cd simple_server
$ python server.py

It should run silently without any output so far. Then in a new tab in your favorite browser, browse to this URL:

http://localhost:8000/cgi-bin/my_cgi_script.py

"hello world!" should appear in the browser with a lot of whitespace as the web page (look for it in the upper left corner if you don't see it right away). There, you've done it! You've made your first website with Python CGI!

server.py

from http.server import HTTPServer, CGIHTTPRequestHandler

if __name__ == '__main__':
    try:
        CGIHTTPRequestHandler.cgi_directories = ['/cgi-bin']

        httpd = HTTPServer(('', 8000),             # localhost:8000
                           CGIHTTPRequestHandler)  # CGI support.

        print(f"Running server. Use [ctrl]-c to terminate.")

        httpd.serve_forever()

    except KeyboardInterrupt:
        print(f"\nReceived keyboard interrupt. Shutting down server.")
        httpd.socket.close()

cgi-bin/my_cgi_script.py

#!/usr/bin/env python
# The line above ^ is important. Don't leave it out. It should be at the
# top of the file.

import cgi, cgitb # Not used, but will be needed later.

print("Content-type: text/html\n\n")
print("hello world!")

If you got it running, you may be wondering 'what just happened?' server.py set up and is running a web server. It is configured to run scripts using the CGIHTTPRequestHandler. This request handler will run files within the cgi-bin folder as scripts. It uses the command shell to do this.

At the top of my_cgi_script.py, the #!/usr/bin/env python line tells the command shell to execute the code in the file using the Python interpreter.

The URL you entered in the browser is understood by the server as a path to a file - in this case the CGI script, my_cgi_script.py, under the cgi-bin folder: http://localhost:8000/cgi-bin/my_cgi_script.py

If you take a look at the command shell that the server is running in, you can see messages detailing the web traffic it's handled. Each time you access this server process, it will output more messages - go ahead and try refresh in the browser and watch it.

You can now modify my_cgi_script.py to output more text, or you could have it output HTML tags and generate a more interesting web page.

To create a web page that incorporates the CGI script, create a file named index.html and place it in the folder with server.py - the content for index.html is below.

index.html

<!DOCTYPE html>
<html>
  <body>

    <h1>My First Heading</h1>
    <p>My first paragraph.</p>

    <!-- Simple example to include text from the CGI script in this web page. -->

    <object type="text/html" data="/cgi-bin/my_cgi_script.py"></object>

  </body>
</html>

The directory structure should now look like this:

|
-- [simple_server]
      |
      -- server.py
      |
      -- index.html
      |
      -- [cgi-bin]
            |
            -- my_cgi_script.py

Once that's done, if you stopped the server process, start it up again and try browsing to http://localhost:8000 and verify you see "hello world!" below "My first paragraph." index.html is a special file name that web servers use as the default page for their URL's. Now you have all the basics in place to create a great website!

Moving forward, there are various opinions on what the best web development framework should be for learning, or serious development. From this example you should get a sense for very basic configuration, setup, and browser/server interaction.

So now, the question is where to go from here? You could continue to pursue the above model, and learn how to put more functionality into the basic site using Python CGI scripts, and bind them to form actions in the HTML page. That would be a perfectly valid path, and you'd likely learn a lot.

Someone recommended to me a good site that uses a production quality web server called Django. From what I gather, it has very good tutorials and other resources to help get started in web development.

That site is Django Girls Tutorial. Don't be put off by the name of the site, anyone can benefit from the tutorial and it provides a very good introduction to the tools and technology you'll need to progress in web development with Django.

Django Girls is an active developer community for women that hosts events around the world, and connects them with others that can help with their progress.

Django Girls Tutorial: https://tutorial.djangogirls.org/en/

More in-depth Python CGI examples: https://www.tutorialspoint.com/python/python_cgi_programming.htm

For learning HTML, this site has good tutorials: https://www.w3schools.com/html/default.asp

Reference on the CGI support module, cgi: https://docs.python.org/3/library/cgi.html

Documentation that includes the classes used in this example can be found within: https://docs.python.org/2/library/internet.html

like image 56
Todd Avatar answered Jan 31 '23 00:01

Todd