Billjk
Billjk

Reputation: 10686

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.

Upvotes: 1

Views: 878

Answers (2)

Uku Loskit
Uku Loskit

Reputation: 42040

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).

Upvotes: 3

Quentin
Quentin

Reputation: 944021

If you want client side programming, then you need to look at JavaScript or plugins (with JavaScript being the sane option in most cases).

You can use any language under the sun for server side programming. Python is a relatively popular choice for that. The Python wiki has some starting points for web programming.

Upvotes: 1

Related Questions