Executing a Python Script when Web Page is loaded
Question: I'm trying to have it so that when my web page is loaded, a python script is
executed. The website is run on an apache server and the script is in the same
directory as the index.html (it's a very small project).

Is there anyway I can do this? I'm not trying to output the data from the
python file to the webpage, nor am I trying to affect anything client-side, I
simply want the python script to execute and do it's thing whenever the web
page is loaded.

Is there some sort of javascript function that I can use? I've searched around
but really haven't found anything similar. Thanks!


Answer: Hopefully, your web server is already set up to run Python scripts. Presumably
it will recognize an `index.py` file as any other `index.(html|cgi|pl|etc.)`
document. Create the following as `index.py` in your DocumentRoot:

    
    
    my_webpage = """
    Content Type: text/html\n\n
    
    <html>
    <head>
    <title>Python-generated text!</title>
    </head>
    <body>
    <h1>I just made an HTML page with Python!</h1>
    </body>
    </html>
    """
    print(my_webpage)
    # now that that's out of the way, let's run our script
    import stuff
    
    def myfunc():
        # awesomeness goes here...
    

and make sure it's executable. Now, whenever a user requests
`http://www.yourserver.com/` the server will run `index.py`, which prints out
the HTML content, including the headers, then goes on to run the rest of your
script.

