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和端 ...
随机推荐
- 使用.NET Remoting开发分布式应用——配置文件篇
我们已经知道可以通过编码的方式配置服务器通道和远程客户机,除此之外,还可以使用配置文件对服务器通道和远程客户机进行配置.使用远程客户机和服务器对象的配置文件的优点在于,用户无需修改任何一行代码,也无需 ...
- Python函数- setattr()
作用: setattr 函数对应函数 getatt(),用于设置属性值,该属性必须存在. 语法: setattr(object, name, value) object -- 对象. name -- ...
- 洛谷2943 [USACO09MAR]清理Cleaning Up——转变枚举内容的dp
题目:https://www.luogu.org/problemnew/show/P2943 一下想到n^2.然后不会了. 看过TJ之后似乎有了新的认识. n^2的冗余部分在于当后面那部分的种类数一样 ...
- 加载rocksdb实例报错:java.lang.UnsatisfiedLinkError: C:\Users\Administrator\AppData\Local\Temp\librocksdbjni3696928169151614297.dll
项目的缓存中用到了rocksdb,实例化时报错了: Related cause: org.springframework.beans.factory.BeanCreationException: Er ...
- 监控文件的watchdog
watchdog用来监控指定目录/文件的变化,如添加删除文件或目录.修改文件内容.重命名文件或目录等,每种变化都会产生一个事件,且有一个特定的事件类与之对应,然后再通过事件处理类来处理对应的事件,怎么 ...
- erlang热部署
以下流程参考rebar的wiki,亲测 rebar的版本一定要注意,高版本对于下面两个指令有bug rebar generate-appups rebar generate-upgrade 经过一个个 ...
- Unable to resolve target 'android-21'
本文转载自:http://blog.csdn.net/love_javc_you/article/details/37728355 重新装完Ecplise+ATD+Android SDK 在Ecpli ...
- jetty中war包解压路径
这是个很奇怪的问题,如果下载好了jetty直接放入war包运行,项目会被解压到C盘的临时文件夹中.但是如果你在${JETTY_HOME}文件夹,也就是jetty解压后的根目录中新建,注意是新建一个wo ...
- MySQL error : Deadlock found when trying to get lock; try restarting transaction
在使用 MySQL 时,我们有时会遇到这样的报错:“Deadlock found when trying to get lock; try restarting transaction”. 在 14. ...
- entering power save mode无法开机解决办法
标签(空格分隔): 服务器 问题描述: 服务器型号为IBM system x 3755 m3.服务器在搬动之前运行良好,换完位置之后出现按完电源键后无法进入系统,通过显示器看到entering pow ...