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和端 ...
随机推荐
- 【策略】一致性Hash算法
转载请说明出处:http://blog.csdn.net/cywosp/article/details/23397179 一致性哈希算法在1997年由麻省理工学院提出的一种分布式哈希(DHT) ...
- 洛谷 P3144 [USACO16OPEN]关闭农场Closing the Farm_Silver
传送门 题目大意: n个谷仓 ,每次关闭一个谷仓,问剩下没被关闭的谷仓是 否联通. 题解:并查集+倒序处理 代码: #include<iostream> #include<cstdi ...
- 学习动态性能表(5)--v$session
学习动态性能表 第五篇--V$SESSION 2007.5.29 在本视图中,每一个连接到数据库实例中的session都拥有一条记录.包括用户session及后台进程如DBWR,LGWR,arcch ...
- 【转】简单明了区分escape、encodeURI和encodeURIComponent
一.前言 讲这3个方法区别的文章太多了,但是大部分写的都很绕.本文试图从实践角度去讲这3个方法. 二.escape和它们不是同一类 简单来说,escape是对字符串(string)进行编码(而另外两种 ...
- 致Oracle DBA 的一封信 (网上流传)
1. 数据库的可用度,DBA 说了“不算” --物化视图,加快查询速度 某些时候数据库的可用性,并不由DBA所设定.因为即使DBA对数据库有绝对掌控权,但用户可能从自己的工作和应用角度,与DBA的 ...
- (转)Download interrupted: Connection to https://dl-ssl.google.com refused
(转)Download interrupted: Connection to https://dl-ssl.google.com refused 这个可能是网络问题,国内连google服务器经常连 ...
- quartz框架实现定时任务举例
简单的定时任务功能可以通过原生的java.util.Timer定义执行时间规则.继承java.util.TimeTask来定义执行逻辑来实现,更方便的是利用开源的quartz框架,只需定义几个spri ...
- PUTTY学习
参考地址:http://blog.csdn.net/eastmount/article/details/52753135 putty介绍: PuTTY是一个Telnet.SSH.rlogin.纯TCP ...
- split的用法回顾,快忘记了@ →@
split:用for循环时不要忘记是数组名.length package com.aaa; //split的用法把指定的字符串按指定的分割符进行分割,然后返回字符串 数组 public class f ...
- mybatis~动态SQL(1)
动态SQL MyBatis还有一个方便的功能就是动态SQL,可以根据条件智能生成SQL语句.这里的例子全部来自MyBatis文档. if标签 下面这个例子使用了MyBatis的if元素,在标题不为空的 ...