Python Flask grpc gateway

PreRequirements

requirements.txt

1
2
3
4
5
6
7
celery==4.2.1
grpcio==1.19.0
grpcio-tools==1.19.0
ontology-python-sdk==1.3.1
protobuf==3.7.0
Flask==1.0.2
gunicorn==19.9.0

Install Dependent Packages

1
2
pyenv activate env_flask_grpc
pip install --no-cache-dir -r requirements.txt -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

proto/demo.proto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
syntax = "proto3";

package demo;

message RequestData {
string data = 1;
}

message ResponseData {
int64 return_code = 1;
string message = 2;
string data = 3;
}

service DemoService {

rpc CreateOne(RequestData) returns (ResponseData) {}
rpc DeleteOne(RequestData) returns (ResponseData) {}
rpc TransferOne(RequestData) returns (ResponseData) {}
rpc GetCreateNotify(RequestData) returns (ResponseData) {}

}

build.sh

1
2
3
4
python -m grpc_tools.protoc -I/usr/local/include -I. \
--grpc_python_out=. \
--python_out=. \
-I./proto/ demo.proto

demo_flask.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from flask import Flask
app = Flask(__name__)

import grpc

import demo_pb2
import demo_pb2_grpc


@app.route('/grpc')
def hello_world_grpc():
with grpc.insecure_channel('127.0.0.1:9090') as channel:
client = demo_pb2_grpc.DemoServiceStub(channel)

response = client.CreateOne(demo_pb2.RequestData(
data="call create one from client",
))
print(response.return_code, response.message, response.data)
return 'Hello, World grpc!'


@app.route('/')
def hello_world():
return 'Hello, World!'



run.sh

1
2
export FLASK_APP=demo_flask.py
gunicorn -w 4 -b 127.0.0.1:4000 demo_flask:app

Run Server

1
./run.sh