Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The use of gRPC Framework in Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Brief introduction

GRPC is a high-performance, open source and general-purpose RPC framework designed for mobile and HTTP/2. C, Java and Go language versions are currently available, which are grpc, grpc-java, grpc-go. C version supports C, Cellular, Node.js, Python, Ruby, Objective-C, PHP and C # support. GRPC is designed based on the HTTP/2 standard and brings features such as bidirectional flow, flow control, header compression, multiplex requests over a single TCP connection, and so on. These features make it perform better on mobile devices, save power and space. GRPC provides a simple way to define services, and clients can make full use of the features of HTTP/2 stream, thus helping to save bandwidth, reduce the number of TCP connections, save the use of CPU, and so on.

GRPC defaults to protocol buffers, a lightweight and efficient structured data storage format open source by Google that can be used for structured data serialization, or serialization. It is very suitable for data storage or RPC data exchange format.

Installation

Official reference document

Installation of gRPC: $pip install grpcio installs ProtoBuf-related python dependent libraries: $pip install protobuf installs python grpc's protobuf compilation tool: $pip install grpcio-tools practice defines a message type

Let's start with a very simple example. Suppose you want to define a message format for a "search request". Each request contains a query string, the number of pages of query results you are interested in, and how many query results per page. You can define the .proto file for the message type in the following way:

Syntax = "proto3"; / / declare to use the proto3 syntax message SearchRequest {string query = 1; / / specify the data type int32 page_number = 2 for each field; / / the number 2 here is the identifier, and the minimum identification number can start with 1, up to 2 ^ 29-1, or 536870911. You can't use [19000 19999] int32 result_per_page = 3; / / here are comments, using / /} the first line of the article specifies that you are using proto3 syntax: if not specified, the compiler will use proto2. This specified syntax must be the first line of the non-empty non-comment of the file. The SearchRequest message format has three fields, and the data carried in the message corresponds to each field. Each of these fields has a name and a type. To add comments to the .proto file, you can use the C/C++/java-style double slash (/ /) syntax format. In the message body, each field has a unique numeric identifier. These identifiers are used to identify fields in the binary format of the message and cannot be changed once they are in use.

The identification number within [1minute 15] takes up one byte when it is encoded. The identification number within [16cm2047] takes up 2 bytes. Therefore, you should keep the identification number within [1mem15] for those message elements that occur frequently. Remember: set aside some identification numbers for frequent identification numbers that may be added in the future.

Specify field rules

The specified message field modifier must be one of the following:

Singular: a well-formed message should have 0 or 1 of these fields (but no more than 1). Repeated: in a well-formed message, this field can be repeated any number of times (including 0 times). The order of duplicate values is preserved.

In proto3, repeated's scalar domain defaults to shrimp using packed. Numerical type

A scalar message field can contain the following types-- this table shows the types defined in the .proto file and the corresponding types defined in the automatically generated access class:

Default value

When a message is parsed, if the encoded information does not contain a specific singular element, the domain corresponding to the parsed object lock is set to a default value, which is specified as follows for different types:

For strings, default is an empty string for bytes, default is an empty bytes for bools, default is false for numeric types, default is 0 for enumerations, default is the first defined enumeration value, must be 0; for message type (message), the domain is not set, and the exact message is determined by language. For more information, please see the default value of generated code guide for repeatable fields is empty (usually an empty list in the corresponding language). Nesting type

You can define and use message types in other message types. In the following example, Result messages are defined within SearchResponse messages, such as:

Message SearchResponse {message Result {string url = 1; string title = 2; repeated string snippets = 3;} repeated Result results = 1;}

In message SearchResponse, the nested message Result is defined and used to define the results domain in the SearchResponse message.

What does the Protobuf file compile generate from the .proto file?

When you run a .proto file with the protocol buffer compiler, the compiler generates code for the selected language that manipulates the message types defined in the .proto file, including getting, setting field values, serializing messages into an output stream, and parsing messages from an input stream.

For C++, the compiler generates an .h file and a .cc file for each .proto file, and each message in the .proto file has a corresponding class. For Java, the compiler generates a .java file for each message type, as well as a special Builder class (which is used to create message class interfaces). For Python, it's a little different-the Python compiler generates a module with static descriptors for each message type in the .proto file, and this module and a metaclass (metaclass) are used at run time (runtime) to create the required Python data access class. For go, the compiler generates a .pd.go file for each message type. For Ruby, the compiler generates an .rb file for each message type. For javaNano, the compiler outputs similar domain java but no Builder classes. For Objective-C, the compiler generates a pbobjc.h file and a pbobjcm file for each message type, and each message in the .proto file has a corresponding class. For C #, the compiler generates a .cs file for each message type, and each message in the .proto file has a corresponding class. Python gRPC example

GRPC_DEMO GitHub source code

Compile

Compile using the following command:

$python-m grpc_tools.protoc-I. /-- python_out=. -- grpc_python_out=. . / hello.proto

Two files are generated:

Hello_pb2.py this file contains the generated request (HelloRequest) and response (HelloReply) classes. Hello_pb2_grpc.py this file contains classes for the generated client (GreeterStub) and server (GreeterServicer). Create server-side code

Creating and running a Greeter service can be divided into two parts:

Implement the generated service interface of our service definition: a function that does the actual "work" of our service.

Run a gRPC server that listens for requests from the client and transmits the response from the service. Create client code

See gRPC_DEMO GitHub source code

Run the code

First run the server code

Python server/main.py

Then run the client code

Python client/main.py output: > Greeter client received: Hello, goodspeed!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report