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. fn project 试用之后的几个问题的解答

    今天试用fnproject  之后自己有些思考,后面继续解决   1. 目前测试是强依赖 dockerhub 的,实际可能不是很方便 2. 如何与k8s .mesos.docker swarm  集成 ...

  2. Pycharm简单使用教程

    转自https://blog.csdn.net/qq_40130759/article/details/79421242 1.下载pycharm pycharm是一种Python IDE,能够帮助我们 ...

  3. QtAV的编译方法

    1--编译准备 QtAV的安装编译总指导说明:https://github.com/wang-bin/QtAV/wiki/Build-QtAV QtAV的源代码:https://github.com/ ...

  4. linux文件系统命令和分区 挂载

    文件系统命令df [选项][挂载点]选项:-a 显示所有的文件系统信息,包括特殊文件,如/proc,/sysfs-h 使用习惯单位显示容量,如KB,MB或GB等-T 显示文件系统类型-m 以MB为单位 ...

  5. Java-Runoob:Java 对象和类

    ylbtech-Java-Runoob:Java 对象和类 1.返回顶部 1. Java 对象和类 Java作为一种面向对象语言.支持以下基本概念: 多态 继承 封装 抽象 类 对象 实例 方法 重载 ...

  6. AngularJS:Service

    ylbtech-AngularJS:Service 1.返回顶部 1. AngularJS 服务(Service) AngularJS 中你可以创建自己的服务,或使用内建服务. 什么是服务? 在 An ...

  7. thinkphp中的dump方法

    感受一下,调试. 1.print_r() 2.var_dump() 3.再看看thinkphp中的dump方法 清晰多了!真实够傻的,今天才发现有这么好的调试方法.

  8. maven学习5 构建MyBatis项目

    2. 修改pom.xml,添加MyBatis依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=& ...

  9. Cocos暂停和重新开始游戏

    创建按钮 cc.MenuItemFont.setFontSize(18); cc.MenuItemFont.setFontName("Arial"); var systemMenu ...

  10. 使用原生js自定义内置标签

    使用原生js自定义内置标签 效果图 代码 <!DOCTYPE html> <html lang="en"> <head> <meta ch ...