Django JSON-RPC
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
andpassword
arguments to the beginning of your method if the user hasn't already been authenticated. These will be used to authenticate the user againstdjango.contrib.authenticate
If you use HTTP auth or other authentication middleware,username
andpassword
will not be added, and this method will only check againstrequest.user.is_authenticated
.You may pass a callablle to replace
django.contrib.auth.authenticate
as the authentication method. It must return either a User orNone
and take the keyword argumentsusername
andpassword
. - `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 callingspecial_sauce
, throwing anInvalidParamsError
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 aregister(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的更多相关文章
- 測试JSON RPC远程调用(JSONclient)
#include <string> #include <iostream> #include <curl/curl.h> /* 标题:JSonclient Auth ...
- Django JSON,AJAX
JSON 概念 JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻量级的文本数据交换格式 JSON 独立于语言 * JSON 具 ...
- Django JSON 时间
在views.py中导入: from django.core.serializers.json import DjangoJSONEncoder 在返回JSON数据时调用: return HttpRe ...
- Django json处理
转自:http://www.gowhich.com/blog/423 1, 发往浏览器端 前端:jQuery发送GET请求,并解析json数据. url = "http://example. ...
- 【django json.dumps 报错】 datetime.datetime is not JSON serializable
django 中,json.dumps 无法直接转译 datetime 类型的值. 找了无数方法,找到一个最优.最简洁的解决办法: json.dumps(results, indent=4, sort ...
- RPC是什么?科普一下
RPC概念及分类 RPC全称为Remote Procedure Call,翻译过来为“远程过程调用”.目前,主流的平台中都支持各种远程调用技术,以满足分布式系统架构中不同的系统之间的远程通信和相互调用 ...
- Atitit.js javascript的rpc框架选型
Atitit.js javascript的rpc框架选型 1. Dwr1 2. 使用AJAXRPC1 2.2. 数据类型映射表1 3. json-rpc轻量级远程调用协议介绍及使用2 3.1. 2.3 ...
- atitit.基于http json api 接口设计 最佳实践 总结o7
atitit.基于http json api 接口设计 最佳实践 总结o7 1. 需求:::服务器and android 端接口通讯 2 2. 接口开发的要点 2 2.1. 普通参数 meth,p ...
- 以太坊RPC机制与API实例
上一篇文章介绍了以太坊的基础知识,我们了解了web3.js的调用方式是通过以太坊RPC技术,本篇文章旨在研究如何开发.编译.运行与使用以太坊RPC接口. 关键字:以太坊,RPC,JSON-RPC,cl ...
- django知识回顾
一.web框架 1.web框架本质 众所周知,对于所有的web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端 1.浏览器(socket客户端) 2.发送IP和端 ...
随机推荐
- vue指令总结
new Vue({ el: "#box", // element(元素) 当前作用域 data:{ msg:" ...
- C#枚举Enum[轉]
枚举是一个指定的常数,其基础类型可以是除 Char 外的任何整型.如果没有显式声明基础类型,则使用 Int32.编程语言通常提供语法来声明由一组已命名的常数和它们的值组成的枚举.定义默认基数从O开始, ...
- poj 3590 The shuffle Problem——DP+置换
题目:http://poj.org/problem?id=3590 bzoj 1025 的弱化版.大概一样的 dp . 输出方案的时候小的环靠前.不用担心 dp 时用 > 还是 >= 来转 ...
- flask之redis
redis 连接需要host port passwod Hash:key-fields-value(做缓存)相当于一个key对于一个map,map中还有key-valueList:有顺序可重复(处理不 ...
- 源码安装ceph后使用测试集群的方法
标签(空格分隔): ceph,ceph实验,ceph源码 通过博客 源码编译安装ceph(aarch64架构) 成功安装ceph之后,之后可以运行一个测试集群进行实验 1,进入安装构建目录: [roo ...
- WP10通过StreamSocket连接C++服务器
注:当服务端和手机模拟器运行在一台机器时,会有奇怪错误.将服务端放在其它机器上更改客户端连接地址,运行正常.或者直接用本机modern调试也可以. 实例化一个对象 StreamSocket _clie ...
- a标签的四个伪类是什么?如何排序?为什么?
爱恨分明原则: l v h a 注释:为了产生预期的效果,在 CSS 定义中,a:hover 必须位于 a:link 和 a:visited 之后 ! 注释:为了产生预期的效果,在 CSS 定义中,a ...
- Proxmark3笔记(一)
Kali下使用Proxmark3 apt-get update apt-get install build-essential libreadline5 libreadline-dev libusb- ...
- 请求时控制器的返回结果view()怎么会默认调到某个页面的?
请求时控制器的返回结果view()怎么会默认调到某个页面的? (1)请求时会拿方法行为的名字去和视图的名字对应,会默认去views视图下的与控制器名称一样的文件夹下名字与方法对应的视图文件匹配对应,然 ...
- 深度剖析collections模块
namedtuple OrderedDict deque tuple defaultdict Counter ChainMap