天天看點

Django gRPC 應用

Django gRPC 應用

官方文檔: ​​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      

現在同步資料庫:

python manage.py migrate      

更新設定

添加​

​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='')      

結果響應