我想在网站上添加一个按钮执行Python脚本
我现在正在用Django做一个网站。现在我想在网站上放一个按钮,点击这个按钮就能运行一个Python脚本。我觉得这应该是可以做到的,但老实说,我不知道怎么做。
如果能给个例子就最好了。
谢谢任何帮助!
4 个回答
创建一个视图函数,并为它添加一个 @dajaxice_register 装饰器:
下面是一个简单的例子:
models.py:
class Funkyness(models.Model):
funktasm = models.CharField(max_length=128)
funfasticness = models.TextField()
urls.py:
url(r'^funk$', 'views.myFunkyView'),
views.py:
def myFunkyView(request)
render_to_request('index.htm', {'where': 'home'}, context_instance=RequestContext(request))
index.htm:
{% if where %}
You are {{ where }}
{% endif %}
当你访问 http://yoursite.com/funk 时,你会看到渲染出的 index.htm 页面,上面写着 "You are home."(你在家)。
现在,进入动态部分...
写一个视图方法,如下所示:
from django.utils import simplejson
def getHowFunky(request, v):
html = """
<div class="my_message">
This is really funky, almost stinky...
<br />
""" + str(v) + """
</div>
"""
return simplejson.dumps({'message': html})
回到 index.htm:
<script type="text/javascript>
/* first argument is return JS function, the second is the dictionary of data to sent to the python method. */
function init(){
Dajaxice.package.getHowFunky(showFunky, {'v': "Your's Truly... Fubar"});
}
function showFunky(data){
/* This is the data returned back from the AJAX (Dajaxice) call. */
document.write(data.message)
}
</script>
所以,你需要写一个 Python 方法,它接收输入并返回一些东西。你把它注册到 Dajaxice,然后调用它,并传入一个回调方法。这个方法会运行,当它成功时,会把 Python 返回的结果(可能是 JSON 对象)作为参数发送给回调方法。然后,这个方法会把从 Dajaxice 调用中得到的内容显示在屏幕上。
想了解更多关于 Dajaxice 的信息,可以访问: http://dajaxproject.com/
感谢 Jorge Bastida,他是 Dajax/Dajaxice 的唯一开发者!
如果你在使用Django,我认为最好的方法就是创建一个视图来处理你的Python代码,然后通过ajax请求在点击事件时访问它。
你的应用程序目录下的views.py文件
def your_python_script(request):
if request.is_ajax:
# do your stuff here
...
else:
return HttpRequest(status=400)
如果你在使用Django,通常也会用到jQuery。在你的模板中添加一些JavaScript代码,像这样:
$("#<your_button_id>").click( function() {
$.post("your_python_script_url", {<dict with any args you need>}, function () {
// What to do when request successfully completed
});
});
还有,如果你在使用CRSF令牌,别忘了处理它。关于如何处理,你可以在Django的官方文档中找到相关信息。
更新
你可以像这样在页面模板中添加csrf令牌:
<script>
var csrf_token = '{% csrf_token %}';
...
</script>
接下来,你需要绑定到全局的jQuery ajaxSend 事件,并将令牌添加到任何POST请求中。
$("body").bind("ajaxSend", function(elm, xhr, s) {
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});
像这样应该就能正常工作。
我现在已经搞定了这个问题,想分享一下我的解决方案:
view.py:
import script as gh
def get_hostname(request):
gh.main()
return HttpResponseRedirect('/')
urls.py:
...
url(r'^get_hostname/$', 'thinco.views.get_hostname'),
...
在模板中的某个地方:
...
<form action="/get_hostname/" method="GET">
<input type="submit" value="Liste der Thin Clients laden">
</form>
...