一、使用所需环境
pip install django-json-rpc
二、在django项目settings配置文件中注册 'jsonrpc'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'jsonrpc',
'app',
]
三、视图中调用
apis.py
from rest_framework import generics
from app.models import Person
from app.serializers import PersonSerializer
from jsonrpc import jsonrpc_method
# http
class PersonAPI(generics.ListCreateAPIView):
queryset = Person.objects.all()
serializer_class = PersonSerializer
# rpc
@jsonrpc_method('person')
def person(request):
queryset = Person.objects.all()
res = PersonSerializer(queryset, many=True).data
return res
四、注册路由
3.Add the JSON-RPC mountpoint and import your views
urls.py
from django.urls import path
from jsonrpc import jsonrpc_site
from app.apis import PersonAPI
urlpatterns = [
path('person/', PersonAPI.as_view()),
path('rpc-person/', jsonrpc_site.dispatch),
]
五、rpc调用对比api调用
### api调用
import requests
url = "http://127.0.0.1:8000/person/"
res = requests.get(url)
print(res.json())
返回值
[
{'id': 1, 'name': 'one', 'age': 22},
{'id': 2, 'name': 'two', 'age': 23},
{'id': 3, 'name': 'three, 'age': 24}
]
### rpc调用
from jsonrpc.proxy import ServiceProxy
url = "http://127.0.0.1:8000/rpc-person/"
s = ServiceProxy(url)
res = s.person.data()
print(res)
返回值
{
'id': '425d9d70-ccbe-11ea-a8ca-7470fd0bd93a',
'error': None,
'result': [
{'id': 1, 'name': 'one', 'age': 22},
{'id': 2, 'name': 'two', 'age': 23},
{'id': 3, 'name': 'three, 'age': 24}
],
'jsonrpc': '1.0'
}