pythonhtmlembed

Python on the Web


I made a script for python that suggested music to someone, and was wondering if there was a way to put that inside a webpage. Is there a way to embed python in HTML somehow, or another way to put Python scripts in a webpage, or am I better off doing the script in Javascript? It's pretty basic, just an input/response thing with a couple of functions, like

input("Blah blah")
if input == 'yes':
print("example")

but obviously a bit more complicated.


Solution

  • The problem with a javascript only solution is that your data must be hard-coded. With a server-script you can do so much more.

    The difficult bit is setting up a proper server. I will evade this step by using python's default CGISERVER.

    Here is probably the easiest way to achieve what you want (very minimal server setup):

    create a directory called cgi-bin/ in that directory create your python script (make sure it has executable rights)

    #!/usr/bin/python
    
    print 'Content-Type: text/html'
    print
    print '<html>'
    print '<head><title>Hello from Python</title></head>'
    print '<body>'
    print '<h2>Hello from Python</h2>'
    print '</body></html>'
    

    run the command python -m CGIHTTPServer in the same directory. Access your server on localhost:8000/cgi-bin/yourscript.py

    Note that handling HTTP requests and responses by hand like this can get very tiresome and error prone, and you would be best off using one of the many Python web frameworks (like web.py or Django etc).