中华人民共和国
django-rpc的Python项目详细描述
jquery的django rpc。允许在浏览器中使用javascript执行一些服务器端类方法。
也可以使用jquery表单插件提交表单。
它还支持调用批处理。django rpc将在可配置的时间范围内接收到的调用批处理在一起,并在单个请求中发送它们。
您可以轻松地将当前视图移动到rpc方法,并使用django rpc而不是混乱的ajax请求。
灵感来自extjs 3的ext.direct。
安装
使用pip安装:
pip install django-rpc
…或从github克隆项目:
https://github.com/Alerion/django-rpct
将djangorpc应用程序添加到INSTALLED_APPS设置:
INSTALLED_APPS = ( ... 'djangorpc', )
现在所有必需的js文件都可以通过djangostaticfiles应用程序访问。
将jquery添加到页面中。您可以使用应用程序中的一个来快速启动:
<script src="{% static 'djangorpc/js/jquery-1.9.1.min.js' %}"></script>
在基本模板中添加所需的js脚本:
<script src="{% static 'djangorpc/js/jquery.util.js' %}"></script> <script src="{% static 'djangorpc/js/jquery.rpc.js' %}"></script> <script src="{% static 'djangorpc/js/jquery.form.js' %}"></script>
您可以在一个位置处理所有错误,并向用户显示一些消息:
//Show error message for RPC exceptions jQuery.Rpc.on('exception', function(event){ alert('Error during RPC request: '+event.message); });
不要忘记ajax请求的csrf。
示例
让我们看一个如何使用django rpc应用程序的快速示例。
我们将创建一个页面,该页面使用django rpc调用服务器端方法,并用接收到的消息向我们显示警报。
使用以下代码在项目文件夹中创建rpc.py:
from djangorpc import RpcRouter, Msg class MainApiClass(object): def hello(self, username, user): return Msg(u'Hello, %s!' % username) rpc_router = RpcRouter({ 'MainApi': MainApiClass(), })
将此添加到urls.py:
from django.conf.urls import patterns, include, url from rpc import rpc_router urlpatterns = patterns('someproject.someapp.views', url(r'^rpc/', include(rpc_router.urls)) )
在页面模板中添加以下代码:
<script src="{% url 'jsapi' %}"></script> <script> MainApi.hello('username', function(resp, sb){ alert(resp.msg); }); </script>
重新加载页面后,您将看到一条提示消息“你好,用户名!“。
如果你得到一个错误403,你可能忘记了csrf。
下面是csrf cookie注入的示例:
<script> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }, dataType: 'json', error:function(jqXHR, textStatus, errorThrown){ alert(textStatus +'\n'+ errorThrown) } }); </script>
您可以在我们的回购协议中找到工作项目示例。
贡献
这个软件的开发在github上进行,主fork当前位于https://github.com/Alerion/Django-RPC
任何形式的贡献都是受欢迎的,但是使用github的pull-request系统是非常受欢迎的,因为它使审查和集成更加容易。