【问题标题】:I want a button on my website that will execute a python script我想在我的网站上有一个按钮来执行 python 脚本
【发布时间】:2011-11-27 12:06:23
【问题描述】:

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

最好举个例子。

非常感谢您的帮助。

【问题讨论】:

    标签: python django templates view


    【解决方案1】:

    如果您使用的是 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);
       }
    });
    

    这样的事情应该可以工作。

    【讨论】:

    • 嗯,我真的不想使用 ajax,但我知道你会怎么做。不使用ajax还有其他方法吗?
    • 是的,您可以找到有关嵌入式 python 的信息——但这只有在访问者安装了一些特定的插件/软件时才有效——根据我的经验——我还没有看到任何人安装了这样的东西他们的机器。还有更多 - 一些人想要安装它只是为了访问您的网站。
    • 避免 AJAX 的唯一方法是使用静态页面。如果没有 AJAX,您将无法直接从模板实时访问任何视图。 AJAX 在这种范式(MVC 中的视图和控制器)中弥合了视图和模板之间的差距。出于这个原因,您需要通过 HTML 发送请求(表单提交或 URL 更改)以从服务器的 python 视图代码中获取响应,或者发送 AJAX 调用并将其返回到页面以进行显示。
    • @Mihail 我在使用这种方法时遇到 csrf 问题,知道为什么吗?
    • @astrocybernaute 我已经添加了一些 CSRF 令牌示例,该令牌自动添加到任何 jQuery ajax 发布请求中。
    【解决方案2】:

    创建一个视图函数并为其做一个@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 渲染,你会得到一个页面,上面写着“你到家了。”

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

    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/

    Dajax/Dajaxice 的唯一开发者 Jorge Bastida 的道具!

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        我能想到的答案是使用:

        Django + Dajax

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

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

        您可以在 django 视图中创建您的按钮,并在触发您的按钮时,您可以使用运行 python sn-p,而不是脚本。

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

        【讨论】:

          猜你喜欢
          • 2019-08-29
          • 1970-01-01
          • 2018-08-26
          • 2022-01-26
          • 1970-01-01
          • 1970-01-01
          • 2018-04-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多