Technology Sharing

[Python] Python Flask and gRPC simple project

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Python Flask and gRPC Example Project

This article will show you how to create a simple example application using Flask and gRPC in Python and use requests Library for testing.

Environment Setup

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`
  • 1
  • 2

Install necessary packages:

pip install Flask grpcio grpcio-tools requests
  • 1

Defining a gRPC Service

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Generate Python code from Proto files

use grpc_tools Generate Python code:

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. service.proto
  • 1

This will generate two files:service_pb2.py andservice_pb2_grpc.py

Implementing a gRPC server

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

Implementing the Flask server

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

Running the Server

Open two terminal windows or tabs.

  1. In the first terminal, start the gRPC server:

    python grpc_server.py
    
    • 1
  2. In the second terminal start the Flask server:

    python flask_server.py
    
    • 1

use requests carry out testing

Create 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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Running Tests

  1. make sure grpc_server.py andflask_server.py running.

  2. In another terminal run test_flask_server.py

    python test_flask_server.py
    
    • 1

You should see output like this:

Success!
Response JSON: {'message': 'Hello, World!'}
  • 1
  • 2

Run screenshot

insert image description here

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.