address-service/address_service/grpc/server.py

34 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from concurrent import futures
import grpc
from django.conf import settings
from grpc_reflection.v1alpha import reflection
from address_service.grpc import address_pb2, address_pb2_grpc
from address_service.grpc.servicer import AddressServicer
def listen_address(host: str | None = None, port: int | None = None) -> str:
return f"{host or settings.GRPC_HOST}:{settings.GRPC_PORT if port is None else port}"
def create_server(host: str | None = None, port: int | None = None) -> tuple[grpc.Server, str]:
server = grpc.server(futures.ThreadPoolExecutor(max_workers=settings.GRPC_WORKERS))
address_pb2_grpc.add_AddressServiceServicer_to_server(AddressServicer(), server)
service_names = (
address_pb2.DESCRIPTOR.services_by_name["AddressService"].full_name,
reflection.SERVICE_NAME,
)
reflection.enable_server_reflection(service_names, server)
address = listen_address(host, port)
bound = server.add_insecure_port(address)
if bound == 0:
raise RuntimeError(f"Не удалось открыть порт {address}")
return server, f"{host or settings.GRPC_HOST}:{bound}"
def serve(host: str | None = None, port: int | None = None) -> None:
server, address = create_server(host, port)
server.start()
server.wait_for_termination()