Django JSON-RPC

https://github.com/samuraisam/django-json-rpc

A basic JSON-RPC Implementation for your Django-powered sites.

Features:

  • Simple, pythonic API
  • Support for Django authentication
  • Support for all official Django Python/Version combinations
  • Supports JSON-RPC 1.0, 1.1, 1.2 and 2.0 Spec
  • Proxy to test your JSON Service
  • Run-time type checking
  • Graphical JSON-RPC browser and web console
  • Provides system.describe

The basic API:

myproj/myapp/views.py

from jsonrpc import jsonrpc_method

@jsonrpc_method('myapp.sayHello')
def whats_the_time(request, name='Lester'):
return "Hello %s" % name @jsonrpc_method('myapp.gimmeThat', authenticated=True)
def something_special(request, secret_data):
return {'sauce': ['authenticated', 'sauce']}

myproj/urls.py

from django.conf.urls.defaults import *
from jsonrpc import jsonrpc_site
import myproj.myapp.views # you must import the views that need connected urlpatterns = patterns('',
url(r'^json/browse/', 'jsonrpc.views.browse', name="jsonrpc_browser"), # for the graphical browser/web console only, omissible
url(r'^json/', jsonrpc_site.dispatch, name="jsonrpc_mountpoint"),
url(r'^json/(?P<method>[a-zA-Z0-9.]+)$', jsonrpc_site.dispatch) # for HTTP GET only, also omissible
)

To test your service:

You can test your service using the provided graphical browser and console,

available at http://YOUR_URL/json/browse/ (if using the url patterns from above) or with the included ServiceProxy:

>>> from jsonrpc.proxy import ServiceProxy

>>> s = ServiceProxy('http://localhost:8080/json/')

>>> s.myapp.sayHello('Sam')
{u'error': None, u'id': u'jsonrpc', u'result': u'Hello Sam'} >>> s.myapp.gimmeThat('username', 'password', 'test data')
{u'error': None, u'id': u'jsonrpc', u'result': {u'sauce': [u'authenticated', u'sauce']}}

We add the jsonrpc_version variable to the request object. It be either '1.0', '1.1' or '2.0'. Arg.

Guide

Adding JSON-RPC to your application

1. Install django-json-rpc

git clone git://github.com/samuraisam/django-json-rpc.git
cd django-json-rpc
python setup.py install # Add 'jsonrpc' to your INSTALLED_APPS in your settings.py file

2. Write JSON-RPC methods

from jsonrpc import jsonrpc_method

@jsonrpc_method('app.register')
def register_user(request, username, password):
u = User.objects.create_user(username, 'internal@app.net', password)
u.save()
return u.__dict__ @jsonrpc_method('app.change_password', authenticated=True)
def change_password(request, new_password):
request.user.set_password(new_password)
request.user.save()
return u.__dict__

3. Add the JSON-RPC mountpoint and import your views

from jsonrpc import jsonrpc_site
import app.views urlpatterns = patterns('',
url(r'^json/$', jsonrpc_site.dispatch, name='jsonrpc_mountpoint'),
# ... among your other URLs
)

The jsonrpc_method decorator

Wraps a function turns it into a json-rpc method. Adds several attributes to the function speific to the JSON-RPC machinery and adds it to the default jsonrpc_site if one isn't provided. You must import the module containing these functions in your urls.py.

jsonrpc.jsonrpc_method(name, authenticated=False, safe=False, validate=False)

  • `name`

    The name of your method. IE: namespace.methodName

  • `authenticated=False`

    Adds username and password arguments to the beginning of your method if the user hasn't already been authenticated. These will be used to authenticate the user against django.contrib.authenticate If you use HTTP auth or other authentication middleware, username and password will not be added, and this method will only check against request.user.is_authenticated.

    You may pass a callablle to replace django.contrib.auth.authenticate as the authentication method. It must return either a User or None and take the keyword arguments username and password.

  • `safe=False`

    Designates whether or not your method may be accessed by HTTP GET. By default this is turned off.

  • `validate=False`

    Validates the arguments passed to your method based on type information provided in the signature. Supply type information by including types in your method declaration. Like so:

      @jsonrpc_method('myapp.specialSauce(Array, String)', validate=True)
    def special_sauce(self, ingredients, instructions):
    return SpecialSauce(ingredients, instructions)

    Calls to myapp.specialSauce will now check each arguments type before calling special_sauce, throwing an InvalidParamsError when it encounters a discrepancy. This can significantly reduce the amount of code required to write JSON-RPC services.

    NOTE: Type checking is only available on Python versions 2.6 or greater.

  • `site=default_site`

    Defines which site the jsonrpc method will be added to. Can be any

    object that provides a register(name, func) method.

Using type checking on methods (Python 2.6 or greater)

When writing web services you often end up manually checking the types of parameters passed. django-json-rpc provides a way to eliminate much of that code by specifying the types in your method signature. As specified in the JSON-RPC spec the available types are Object Array Number Boolean String Nil and Any meaning any type.

  @jsonrpc_method('app.addStrings(arg1=String, arg2=String) -> String', validate=True)
def add_strings(request, arg1, arg2):
return arg1 + arg2

However contrived this example, a lot of extra information about our function is available. The system.describe method will automatically be able to provide more information about the parameters and return type. Provide validate=True to the jsonrpc_method decorator and you can be guaranteed to receive two string objects when add_strings is called.

Note: Return type information is used only for reference, return value types are not checked.

Types can be specified a number of ways, the following are all equivalent:

  # using JSON types:
@jsonrpc_method('app.findSelection(query=Object, limit=Number)') # using Python types:
@jsonrpc_method('app.findSelection(query=dict, limit=int)') # with mixed keyword parameters
@jsonrpc_method('app.findSelection(dict, limit=int)') # with no keyword parameters
@jsonrpc_method('app.findSelection(dict, int)') # with a return value
@jsonrpc_method('app.findSelection(dict, int) -> list')

Using the browser

To access the browser simply add another entry to your urls.py file, before the json dispatch one. Make sure to include the name attribute of each url.

urlpatterns = patterns('',
...
url(r'^json/browse/$', 'jsonrpc.views.browse', name='jsonrpc_browser')
url(r'^json/', jsonrpc_site.dispatch, name="jsonrpc_mountpoint"),
...
)

Enabling HTTP-GET

JSON-RPC 1.1 includes support for methods which are accessible by HTTP GET which it calls idempotent. Add the following to your urls.py file to set up the GET URL.

urlpatterns += patterns('',
(r'^json/(?P<method>[a-zA-Z0-9.-_]+)$', jsonrpc_site.dispatch),
)

Each method that you want to be accessible by HTTP GET must also be marked safe in the method decorator:

@jsonrpc_method('app.trimTails(String)', safe=True)
def trim_tails(request, arg1):
return arg1[:5]

You can then call the method by loading /jsonrpc/app.trimTails?arg1=omgnowai

Using authentication on methods

There is no specific support for authentication in the JSON-RPC spec beyond whatever authentication the transport offers. To restrict access to methods to registered users provide authenticated=True to the method decorator. Doing so will add two arguments to the beginning of your method signature, username and password (and always in that order). By default, the credentials are authenticated against the builtin User database but any method can be used.

@jsonrpc_method('app.thupertheecrit', authenticated=True)
def thupertheecrit(request, value):
p = request.user.get_profile()
p.theecrit = value
p.save()
return p.__dict__

Using your own authentication method:

def mah_authenticate(username, password):
return CustomUserClass.authenticate(username, password) @jsonrpc_method('app.thupertheecrit', authenticated=mah_authenticate)
def thupertheecrit(request, value):
request.user.theecrit = value
request.user.save()
return request.user.__dict__

In case authentication is handled before your method is called, like in some middleware, providing authenticated=True to the method decorator will only check that request.user is authenticated and won't add any parameters to the beginning of your method.

Django JSON-RPC的更多相关文章

  1. 測试JSON RPC远程调用(JSONclient)

    #include <string> #include <iostream> #include <curl/curl.h> /* 标题:JSonclient Auth ...

  2. Django JSON,AJAX

    JSON 概念 JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻量级的文本数据交换格式 JSON 独立于语言 * JSON 具 ...

  3. Django JSON 时间

    在views.py中导入: from django.core.serializers.json import DjangoJSONEncoder 在返回JSON数据时调用: return HttpRe ...

  4. Django json处理

    转自:http://www.gowhich.com/blog/423 1, 发往浏览器端 前端:jQuery发送GET请求,并解析json数据. url = "http://example. ...

  5. 【django json.dumps 报错】 datetime.datetime is not JSON serializable

    django 中,json.dumps 无法直接转译 datetime 类型的值. 找了无数方法,找到一个最优.最简洁的解决办法: json.dumps(results, indent=4, sort ...

  6. RPC是什么?科普一下

    RPC概念及分类 RPC全称为Remote Procedure Call,翻译过来为“远程过程调用”.目前,主流的平台中都支持各种远程调用技术,以满足分布式系统架构中不同的系统之间的远程通信和相互调用 ...

  7. Atitit.js javascript的rpc框架选型

    Atitit.js javascript的rpc框架选型 1. Dwr1 2. 使用AJAXRPC1 2.2. 数据类型映射表1 3. json-rpc轻量级远程调用协议介绍及使用2 3.1. 2.3 ...

  8. atitit.基于http json api 接口设计 最佳实践 总结o7

    atitit.基于http  json  api 接口设计 最佳实践 总结o7 1. 需求:::服务器and android 端接口通讯 2 2. 接口开发的要点 2 2.1. 普通参数 meth,p ...

  9. 以太坊RPC机制与API实例

    上一篇文章介绍了以太坊的基础知识,我们了解了web3.js的调用方式是通过以太坊RPC技术,本篇文章旨在研究如何开发.编译.运行与使用以太坊RPC接口. 关键字:以太坊,RPC,JSON-RPC,cl ...

  10. django知识回顾

    一.web框架 1.web框架本质 众所周知,对于所有的web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端 1.浏览器(socket客户端) 2.发送IP和端 ...

随机推荐

  1. HWOJ-字符串的逆序

    将一个字符串str的内容颠倒过来,并输出.str的长度不超过100个字符. 如:输入“I am a student”,输出“tneduts a ma I”. 输入参数: inputString:输入的 ...

  2. [转]你真的了解setTimeout和setInterval吗?

    原文: http://qingbob.com/difference-between-settimeout-setinterval/ setTimeout和setInterval的基本用法我们一带而过: ...

  3. Delphi AES加密(转)

    (**************************************************************) (* Advanced Encryption Standard (AE ...

  4. 验证DataGridView单元格的值

    private void gridPurchaseOrderDetail_CellValidating(object sender, DataGridViewCellValidatingEventAr ...

  5. 1131 Subway Map

    题意:给出起点和终点,计算求出最短路径(最短路径即所经过的站点最少的),若最短路径不唯一,则选择其中换乘次数最少的一条线路. 思路:本题虽然也是求最短路径,但是此路径是不带权值的,路径长度即所经过的边 ...

  6. JCE无限制权限策略文件

    JCE无限制权限策略文件,里面是对应jdk6和jdk7的文件 官网下载地址是 JDK6:http://www.oracle.com/technetwork/java/javase/downloads/ ...

  7. DB2的安装

    jiangxin@db01:~$ su – root #切换到root用户 密码: root@db01:~# uname -a #查看内核和操作系统信息 Linux db01 4.4.0-66-gen ...

  8. python学习笔记(四):函数

    一.函数是什么? 函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的,编程中的函数在英文中也有很多不同的叫法.在BASIC中叫做subroutine(子过程或子程序),在Pasc ...

  9. IntelliJ IDEA 安装 Julia 插件

    打开 IntelliJ IDEA 点击 Configure 选择 Plugins 然后点击 Browse repositories 搜索 Julia,然后点击 Install 进行安装 安装完重启一下 ...

  10. 搭建Easyui环境在Myeclipse或Eclipse中

    转自:https://www.cnblogs.com/henuyuxiang/p/4283018.html 1.下载Easyui.网址:http://www.jeasyui.com/download/ ...