Django gRPC 应用
原创
©著作权归作者所有:来自51CTO博客作者ch3nnn的原创作品,请联系作者获取转载授权,否则将追究法律责任
官方文档: https://djangogrpcframework.readthedocs.io/en/latest/index.html
项目设置
创建一个名为的新Django项目quickstart
,然后启动一个名为的新应用 account
:
# Create a virtual environment
python3 -m venv env
source env/bin/activate
# Install Django and Django gRPC framework
pip install django
pip install djangorestframework
pip install djangogrpcframework
pip install grpcio
pip install grpcio-tools
# Create a new project and a new application
django-admin startproject quickstart
cd quickstart
django-admin startapp account
现在同步数据库:
更新设置
添加django_grpc_framework
到INSTALLED_APPS
,设置模块位于 quickstart/settings.py
:
INSTALLED_APPS = [
...
'django_grpc_framework',
]
定义原型
我们的第一步是定义gRPC服务和消息,在quickstart/account.proto
旁边创建一个文件 quickstart/manage.py
:
syntax = "proto3";
package account;
import "google/protobuf/empty.proto";
service UserController {
rpc List(UserListRequest) returns (stream User) {}
rpc Create(User) returns (User) {}
rpc Retrieve(UserRetrieveRequest) returns (User) {}
rpc Update(User) returns (User) {}
rpc Destroy(User) returns (google.protobuf.Empty) {}
}
message User {
int32 id = 1;
string username = 2;
string email = 3;
repeated int32 groups = 4;
}
message UserListRequest {
}
message UserRetrieveRequest {
int32 id = 1;
}
或者您可以根据User
模型自动生成它:
python manage.py generateproto --model django.contrib.auth.models.User --fields id,username,email,groups --file account.proto
接下来,我们需要从quickstart
目录生成gRPC代码,运行:
python -m grpc_tools.protoc --proto_path=./ --python_out=./ --grpc_python_out=./ ./account.proto
编写串行
然后,我们将定义一个序列化器,让我们创建一个名为的新模块 account/serializers.py
:
from django.contrib.auth.models import User
from django_grpc_framework import proto_serializers
import account_pb2
class UserProtoSerializer(proto_serializers.ModelProtoSerializer):
class Meta:
model = User
proto_class = account_pb2.User
fields = ['id', 'username', 'email', 'groups']
写作服务
现在我们编写一些服务,创建account/services.py
:
from django.contrib.auth.models import User
from django_grpc_framework import generics
from account.serializers import UserProtoSerializer
class UserService(generics.ModelService):
"""
gRPC service that allows users to be retrieved or updated.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserProtoSerializer
注册处理程序
好的,让我们连接gRPC处理程序,编辑quickstart/urls.py
:
import account_pb2_grpc
from account.services import UserService
urlpatterns = []
def grpc_handlers(server):
account_pb2_grpc.add_UserControllerServicer_to_server(UserService.as_servicer(), server)
完成后,项目布局应如下所示:
.
./quickstart
./quickstart/asgi.py
./quickstart/__init__.py
./quickstart/settings.py
./quickstart/urls.py
./quickstart/wsgi.py
./manage.py
./account
./account/migrations
./account/migrations/__init__.py
./account/services.py
./account/models.py
./account/serializers.py
./account/__init__.py
./account/apps.py
./account/admin.py
./account/tests.py
./account.proto
./account_pb2_grpc.py
./account_pb2.py
拨打我们的服务
用开发模式启动服务器:
python manage.py grpcrunserver --dev
现在,我们可以从gRPC客户端访问我们的服务:
import grpc
import account_pb2
import account_pb2_grpc
with grpc.insecure_channel('localhost:50051') as channel:
stub = account_pb2_grpc.UserControllerStub(channel)
for user in stub.List(account_pb2.UserListRequest()):
print(user, end='')
结果响应