2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
This article will show you how to create a simple example application using Flask and gRPC in Python and use requests
Library for testing.
First, make sure you have Python installed. Then, create a virtual environment to manage your dependencies.
python -m venv myenv
source myenv/bin/activate # Windows 使用 `myenvScriptsactivate`
Install necessary packages:
pip install Flask grpcio grpcio-tools requests
Create .proto
File to define the gRPC service. Save the file asservice.proto
:
syntax = "proto3";
package demo;
service DemoService {
rpc SayHello (HelloRequest) returns (HelloResponse) {}
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
use grpc_tools
Generate Python code:
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. service.proto
This will generate two files:service_pb2.py
andservice_pb2_grpc.py
。
Create a file called grpc_server.py
document:
from concurrent import futures
import grpc
import service_pb2
import service_pb2_grpc
class DemoService(service_pb2_grpc.DemoServiceServicer):
def SayHello(self, request, context):
return service_pb2.HelloResponse(message=f'Hello, {request.name}!')
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
service_pb2_grpc.add_DemoServiceServicer_to_server(DemoService(), server)
server.add_insecure_port('[::]:50051')
server.start()
print("gRPC server started on port 50051")
server.wait_for_termination()
if __name__ == '__main__':
serve()
Create a file called flask_server.py
document:
from flask import Flask, request, jsonify
import grpc
import service_pb2
import service_pb2_grpc
app = Flask(__name__)
def get_grpc_client():
channel = grpc.insecure_channel('localhost:50051')
stub = service_pb2_grpc.DemoServiceStub(channel)
return stub
@app.route('/hello', methods=['POST'])
def say_hello():
data = request.json
name = data.get('name')
stub = get_grpc_client()
response = stub.SayHello(service_pb2.HelloRequest(name=name))
return jsonify({'message': response.message})
if __name__ == '__main__':
app.run(port=5000, debug=True)
Open two terminal windows or tabs.
In the first terminal, start the gRPC server:
python grpc_server.py
In the second terminal start the Flask server:
python flask_server.py
requests
carry out testingCreate a file called test_flask_server.py
and add the following code:
import requests
def test_say_hello():
url = 'http://localhost:5000/hello'
data = {'name': 'World'}
response = requests.post(url, json=data)
if response.status_code == 200:
print('Success!')
print('Response JSON:', response.json())
else:
print('Failed!')
print('Status Code:', response.status_code)
print('Response Text:', response.text)
if __name__ == '__main__':
test_say_hello()
make sure grpc_server.py
andflask_server.py
running.
In another terminal run test_flask_server.py
:
python test_flask_server.py
You should see output like this:
Success!
Response JSON: {'message': 'Hello, World!'}
This test script sends a name
for"World"
POST request to the JSON objecthttp://localhost:5000/hello
, and then print out the response from the server. If the server is working properly, you will see a success message and the returned JSON data.