Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some Instructions #17

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ push: build-prod
@echo "\n${BLUE}Pushing image to GitHub Docker Registry...${NC}\n"
@docker push $(IMAGE):$(VERSION)

grpc-gen:
@python -m grpc_tools.protoc \
-I $(MODULE)/proto \
--python_out=./$(MODULE)/generated \
--grpc_python_out=./$(MODULE)/generated \
./$(MODULE)/proto/*.proto
@sed -i -E 's/^import.*_pb2/from . \0/' ./$(MODULE)/generated/*.py

cluster:
@if [ $$(kind get clusters | wc -l) = 0 ]; then \
kind create cluster --config ./k8s/cluster/kind-config.yaml --name kind; \
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ docker.pkg.github.com/martinheinz/python-project-blueprint/blueprint 0.0.5
Hello World...
```

## gRPC

To generate gRPC sources from `.proto` files stored in `./blueprint/generated/` directory:

```console
~ $ make grpc-gen
```

## Testing

Test are ran every time you build _dev_ or _prod_ image. You can also run tests using:
Expand Down
4 changes: 3 additions & 1 deletion blueprint/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from .app import Blueprint # noqa: F401
from .app import Server # noqa: F401
from .grpc import Echoer # noqa: F401
from .generated import echo_pb2 # noqa: F401
4 changes: 2 additions & 2 deletions blueprint/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .app import Blueprint
from .app import Server

if __name__ == '__main__':
Blueprint.run()
Server.run()
15 changes: 13 additions & 2 deletions blueprint/app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
class Blueprint:
from concurrent import futures
import grpc

from .generated import echo_pb2_grpc
from .grpc import Echoer


class Server:

@staticmethod
def run():
print("Hello World...")
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
echo_pb2_grpc.add_EchoServicer_to_server(Echoer(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()
131 changes: 131 additions & 0 deletions blueprint/generated/echo_pb2.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 68 additions & 0 deletions blueprint/generated/echo_pb2_grpc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc

from . import echo_pb2 as echo__pb2


class EchoStub(object):
"""The echo service definition.
"""

def __init__(self, channel):
"""Constructor.

Args:
channel: A grpc.Channel.
"""
self.Reply = channel.unary_unary(
'/echo.Echo/Reply',
request_serializer=echo__pb2.EchoRequest.SerializeToString,
response_deserializer=echo__pb2.EchoReply.FromString,
)


class EchoServicer(object):
"""The echo service definition.
"""

def Reply(self, request, context):
"""Echo back reply.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')


def add_EchoServicer_to_server(servicer, server):
rpc_method_handlers = {
'Reply': grpc.unary_unary_rpc_method_handler(
servicer.Reply,
request_deserializer=echo__pb2.EchoRequest.FromString,
response_serializer=echo__pb2.EchoReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'echo.Echo', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))


# This class is part of an EXPERIMENTAL API.
class Echo(object):
"""The echo service definition.
"""

@staticmethod
def Reply(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/echo.Echo/Reply',
echo__pb2.EchoRequest.SerializeToString,
echo__pb2.EchoReply.FromString,
options, channel_credentials,
call_credentials, compression, wait_for_ready, timeout, metadata)
7 changes: 7 additions & 0 deletions blueprint/grpc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from .generated import echo_pb2_grpc, echo_pb2


class Echoer(echo_pb2_grpc.EchoServicer):

def Reply(self, request, context):
return echo_pb2.EchoReply(message=f'You said: {request.message}')
19 changes: 19 additions & 0 deletions blueprint/proto/echo.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
syntax = "proto3";

package echo;

// The echo service definition.
service Echo {
// Echo back reply.
rpc Reply (EchoRequest) returns (EchoReply) {}
}

// The request message containing the user's message.
message EchoRequest {
string message = 1;
}

// The response message containing the original message.
message EchoReply {
string message = 1;
}
5 changes: 4 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
pytest==5.3.2
pytest-cov==2.8.1
Flask==1.1.1
Flask==1.1.1
grpcio==1.28.1
grpcio-tools==1.28.1
pytest-grpc==0.7.0
25 changes: 18 additions & 7 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import logging
import pytest

LOGGER = logging.getLogger(__name__)

@pytest.fixture(scope='module')
def grpc_add_to_server():
from blueprint.generated.echo_pb2_grpc import add_EchoServicer_to_server

@pytest.fixture(scope='function')
def example_fixture():
LOGGER.info("Setting Up Example Fixture...")
yield
LOGGER.info("Tearing Down Example Fixture...")
return add_EchoServicer_to_server


@pytest.fixture(scope='module')
def grpc_servicer():
from blueprint.grpc import Echoer

return Echoer()


@pytest.fixture(scope='module')
def grpc_stub(grpc_channel):
from blueprint.generated.echo_pb2_grpc import EchoStub

return EchoStub(grpc_channel)
9 changes: 0 additions & 9 deletions tests/test_app.py

This file was deleted.

9 changes: 9 additions & 0 deletions tests/test_grpc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from .context import blueprint


def test_reply(grpc_stub):
value = 'test-data'
request = blueprint.echo_pb2.EchoRequest(message=value)
response = grpc_stub.Reply(request)

assert response.message == f'You said: {value}'