Dynamic HTML from Python Script
Ivan Illarionov
ivan.illarionov at gmail.com
Wed Jun 11 10:00:02 EDT 2008
On Wed, 11 Jun 2008 01:05:45 +0000, asdf wrote:
>> Well, there's a few ways you could approach it.
>>
>> You could create a cgi program from your script - this is probably the
>> solution you're looking for.
>>
>>
> Output from the script does come up very often. There is a new output
> every 10 secs and it's possible that the script might be run
> indefinitely. Basically I want all that output displayed in a web
> browser
Here's a simplified Django and AJAX solution:
1. Install Django http://www.djangoproject.com/documentation/install/
and choose the place to strore your Django apps
2. Run 'python django-admin.py startproject YOURPROJECTNAME'
3. Create views.py file inside YOURPROJECTNAME directory
with something like this:
from datetime import datetime
from django.http import HttpResponse
# import your script here
def myscript(request):
output = """\
<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById("hello").innerHTML=xmlHttp.responseText;
setTimeout('ajaxFunction();', 1000);
}
}
xmlHttp.open("GET", "../ajax/", true);
xmlHttp.send(null);
}
window.onload = ajaxFunction;
</script>
<div id="hello"></div>
</body>
</html>"""
return HttpResponse(output)
def ajax(request):
output = """
<p>Hello World from Django and AJAX</p>
<p>Current time is: %s</p>
""" % str(datetime.now())[11:19]
return HttpResponse(output, mimetype="text/plain")
Note, that refresh time is in 'setTimeout('ajaxFunction();', 1000);' in
this example it is 1 second.
3. edit urls.py inside YOURPROJECTNAME directory to something like this:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^myscript/$', 'YOURPROJECTNAME.views.myscript'),
(r'^ajax/$', 'YOURPROJECTNAME.views.ajax'),
)
4. run 'python manage.py runserver' inside YOURPROJECTNAME directory
5. point your browser to 'http://127.0.0.1:8000/myscript/' and you'll see
the result.
6. Deploy your app to Apache web server
http://www.djangoproject.com/documentation/modpython/
http://www.djangoproject.com/documentation/fastcgi/
Hope this Django/AJAX introduction is helpfull
Please note that this code is extremely simplified you probably need to
learn more about Django and AJAX/Javascript by yourself
Ivan
More information about the Python-list
mailing list