示例#1
0
    def Get(self, request, context):
        for booked in bookList:
            if booked.id == request.id:
                return booked

        context.set_code(grpc.StatusCode.NOT_FOUND)
        context.set_details("No book with id {} was found".format(request.id))
        return books_pb2.Book()
示例#2
0
def insert_book(stub):
    # Exception handling.
    try:
        # Insert book
        response = stub.Insert(pb.Book(id=12345, title='My book', author='me'))
        print(response)

    # Catch any raised errors by grpc.
    except grpc.RpcError as e:
        print('InsertBook failed with {0}: {1}'.format(e.code(), e.details()))
示例#3
0
def doInsert(bookId, bookTitle, bookAuthor):
    stub = GetClient()
    # Exception handling.
    try:
        # Insert book
        response = stub.Insert(
            pb.Book(id=int(bookId), title=bookTitle, author=bookAuthor))
        print("Server response:")
        printRespAsJson(response)
    # Catch any raised errors by grpc.
    except grpc.RpcError as e:
        print('InsertBook failed with {0}: {1}'.format(e.code(), e.details()))
示例#4
0
# import the generated classes
import books_pb2_grpc
import books_pb2

log = logging.getLogger()
log.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

bookList = [books_pb2.Book(id=123, title="A Tale of Two Cities", author="Charles Dickens")]

# create a class to define the server functions, derived from
# book_pb2_grpc.BookServiceServicer
class BookService(books_pb2_grpc.BookServiceServicer):
    def List(self, request, context):
        response = books_pb2.BookList()
        response.books.extend(bookList)
        return response

    def Insert(self, request, context):
        bookList.append(request)
        return books_pb2.Empty()

# create a gRPC server
def serve():