我想在我的网站上有一个按钮来执行 python 脚本

发布于 2024-12-06 20:35:30 字数 116 浏览 3 评论 0原文

我目前正在使用 django 制作一个网站。现在我想使用网站上的按钮从我的模板/视图执行 python 脚本。这应该是可能的,但说实话我不知道怎么做。

最好举个例子。

感谢您的任何帮助。

I am currently making a website using django. Now I want to execute a python script from my template/view with a button on the website. It should be possible but to be honest I don't know how.

An example would be best.

Thanks for any help at all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

-残月青衣踏尘吟 2024-12-13 20:35:30

现在好了,我想我会写下我的答案:

view.py:

import script as gh

def get_hostname(request):
        gh.main()
        return HttpResponseRedirect('/')

urls.py:

... 
url(r'^get_hostname/

模板中的某处:

...
     <form action="/get_hostname/" method="GET">
        <input type="submit" value="Liste der Thin Clients laden"> 
    </form>
...
, 'thinco.views.get_hostname'), ...

模板中的某处:

Well got it working now and just thought I would write my answer:

view.py:

import script as gh

def get_hostname(request):
        gh.main()
        return HttpResponseRedirect('/')

urls.py:

... 
url(r'^get_hostname/

somewhere in template:

...
     <form action="/get_hostname/" method="GET">
        <input type="submit" value="Liste der Thin Clients laden"> 
    </form>
...
, 'thinco.views.get_hostname'), ...

somewhere in template:

十年九夏 2024-12-13 20:35:30

如果您使用 Django - 恕我直言,最好的方法就是创建将处理您的 python 代码的视图,然后通过 ajax 请求在 onclick 事件中访问它。

yourapp/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);
   }
});

像这样的东西应该有效。

If you are using Django - best way, IMHO, is just to create the view that will handle your python code, and then access it at onclick event via ajax request.

yourapp/views.py

def your_python_script(request):
    if request.is_ajax:
        # do your stuff here
        ...
    else:
        return HttpRequest(status=400)

If you are using django also you should have jQuery, and in your template add javascript code, something like this:

$("#<your_button_id>").click( function() {
    $.post("your_python_script_url", {<dict with any args you need>}, function () {
        // What to do when request successfully completed
    });
});

And not to forget about CRSF token if your are using it. How to handle it you can find in offical django documentation.

UPDATE

You can add csrf token to page template like:

<script>
var csrf_token = '{% csrf_token %}';
...
</script>

Next, you need to bind to the global jquery ajaxSend event, and add the token to any POST request.

$("body").bind("ajaxSend", function(elm, xhr, s) {
   if (s.type == "POST") {
      xhr.setRequestHeader('X-CSRF-Token', csrf_token);
   }
});

Something like this should work.

野の 2024-12-13 20:35:30

创建一个视图函数并为其创建一个 @dajaxice_register 装饰器:

一个愚蠢的示例如下:

models.py:

class Funkyness(models.Model):
    funktasm = models.CharField(max_length=128)
    funfasticness = models.TextField()

urls.py:views.py:index.htm

url(r'^funk

http://yoursite.com

def myFunkyView(request)
    render_to_request('index.htm', {'where': 'home'}, context_instance=RequestContext(request))

:

{% if where %}
    You are {{ where }}
{% endif %}

当您访问 http://yoursite.com/funk,您将获得 index.htm 呈现,并且您将看到一个页面,显示“您已回家”。

现在,动态部分...
像这样编写一个视图方法:

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 提供道具,他是 Dajaxice 的唯一开发者达贾克斯/达贾克斯!

, 'views.myFunkyView'),

http://yoursite.com

:

当您访问 http://yoursite.com/funk,您将获得 index.htm 呈现,并且您将看到一个页面,显示“您已回家”。

现在,动态部分...
像这样编写一个视图方法:

回到index.htm:

因此,您构建了一个接受输入并返回某些内容的 python 方法。您向 Dajaxice 注册它,调用它,并传递回调方法。它运行,当成功时,它将 python 返回(可能是 JSON 对象)作为参数发送到回调方法。然后,该方法将从 Dajaxice 调用中获取的内容写入屏幕。

有关 Dajaxice 的更多信息,请访问:http://dajaxproject.com/

向 Jorge Bastida 提供道具,他是 Dajaxice 的唯一开发者达贾克斯/达贾克斯!

Create a view function and do an @dajaxice_register decorator for it:

A silly example follows:

models.py:

class Funkyness(models.Model):
    funktasm = models.CharField(max_length=128)
    funfasticness = models.TextField()

urls.py:

url(r'^funk

views.py:

def myFunkyView(request)
    render_to_request('index.htm', {'where': 'home'}, context_instance=RequestContext(request))

index.htm:

{% if where %}
    You are {{ where }}
{% endif %}

When you go to http://yoursite.com/funk, you will get index.htm rendered and you will get a page that says "You are home."

Now, the dynamic part...
Write a view method as such:

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

back in 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>

So, you build a python method that takes inputs and returns something. You register it with Dajaxice, you call it, passing a callback method. It runs and when it succeeds, it send the python return (possibly JSON object) to the callback method as an argument. That method then writes to the screen what it got from the Dajaxice call.

For more info on Dajaxice, go to: http://dajaxproject.com/

Props to Jorge Bastida, the sole developer of Dajax/Dajaxice!

, 'views.myFunkyView'),

views.py:

index.htm:

When you go to http://yoursite.com/funk, you will get index.htm rendered and you will get a page that says "You are home."

Now, the dynamic part...
Write a view method as such:

back in index.htm:

So, you build a python method that takes inputs and returns something. You register it with Dajaxice, you call it, passing a callback method. It runs and when it succeeds, it send the python return (possibly JSON object) to the callback method as an argument. That method then writes to the screen what it got from the Dajaxice call.

For more info on Dajaxice, go to: http://dajaxproject.com/

Props to Jorge Bastida, the sole developer of Dajax/Dajaxice!

我很坚强 2024-12-13 20:35:30

我能想到的答案是使用:

Django + Dajax

Django 链接:
https://docs.djangoproject.com/en/1.4/

Dajax 实际上是 django 的 ajax :
访问他们的网站并参考他们的示例以快速入门
http://www.dajaxproject.com/

您可以在 django 视图中创建按钮并在触发按钮时,您可以使用运行 python 代码片段,而不是脚本。

如果您想运行独立脚本,您可以查看 djcelery。
http://pypi.python.org/pypi/django-celery

What I could think of for an answer is to use:

Django + Dajax

Django link:
https://docs.djangoproject.com/en/1.4/

Dajax is actually ajax for django:
Visit their website and refer to their examples for quick start
http://www.dajaxproject.com/

You can create your button in django view and upon triggering your button, you can use run a python snippet, not script.

If you want to run a standalone script, you could probably check out djcelery.
http://pypi.python.org/pypi/django-celery

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文