Reez0
Reez0

Reputation: 2689

Grpc requests failing when python client used inside flask

I have a flask app that needs to make a request to a grpc server when a request is made to the flask endpoint.

@main.route("/someroute", methods=["POST"])
def some_function():
    # Do something here
    make_grpc_request(somedata)
    return create_response(data=None, message="Something happened")


def make_grpc_request(somedata):
    channel = grpc.insecure_channel('localhost:30001')
    stub = some_proto_pb2_grpc.SomeServiceStub(channel)
    request = some_proto_pb2.SomeRequest(id=1)
    response = stub.SomeFunction(request)
    logger.info(response)

But I keep getting an error InactiveRpcError of RPC that terminated with: StatusCode.UNAVAILABLE failed to connect to all addresses

Just putting the client code inside a normal .py file works fine, and making the request inside BloomRPC works fine too so it couldn't be a server issue.

Is this something to do with how flask works and I'm just missing something?

I have also tried using https://github.com/public/sonora without any success like this:

with sonora.client.insecure_web_channel("localhost:30001") as channel:
    stub = some_proto_pb2_grpc.SomeServiceStub(channel)
    request = some_proto_pb2.SomeRequest(id=1)
    response = stub.SomeFunction(request)

docker-compose.yml

version: "3.7"

services:
  core-profile: #This is where the grpc requests are sent to
    container_name: core-profile
    build:
      context: ./app/profile/
      target: local
    volumes:
      - ./app/profile/:/usr/src/app/
    env_file:
      - ./app/profile/database.env
      - ./app/profile/jwt.env
      - ./app/profile/oauth2-dev.env
    environment:
      - APP_PORT=50051
      - PYTHONUNBUFFERED=1
      - POSTGRES_HOST=core-profile-db
    ports:
      - 30001:50051
    expose:
      - 50051
    depends_on:
      - core-profile-db

  core-profile-db:
    image: postgres:10-alpine
    expose:
      - 5432
    ports:
      - 54321:5432
    env_file:
      - ./app/profile/database.env

  app-flask-server-db:
    image: postgres:10-alpine
    expose:
      - 5433
    ports:
      - 54333:5433
    env_file:
      - ./app/flask-server/.env

  flask-server:
    build:
      context: ./app/flask-server/
      dockerfile: Dockerfile-dev
    volumes:
      - ./app/flask-server:/usr/src/app/
    env_file:
      - ./app/flask-server/.env
    environment:
      - FLASK_ENV=docker
    ports:
      - 5000:5000
    depends_on:
      - app-flask-server-db

volumes:
  app-flask-server-db:
    name: app-flask-server-db

Upvotes: 1

Views: 1322

Answers (1)

DazWilkin
DazWilkin

Reputation: 40051

Your Python app (service) should reference the gRPC service as core-profile:50051.

The host name is the Compose service core-profile and, because the Python service is also within the Compose network, it must use 50051.

localhost:30001 is how you'd access it from the Compose host

Upvotes: 1

Related Questions