Skip to content
:tech
← Handbook

AI-translated. Read the original in Korean

Python Projects

Implementing an API

Implement the API defined using the API Definition guide.

Adding the Library

The Python library built from the API definition is published to Buzzvil’s private PyPI package management system. Use pip to install the published library.

$ pip install --extra-index-url $BUZZVIL_PYPI_HOST PACKAGE && pip freeze > requirements.txt
Collecting PACKAGE
...

Implementing the Interface

Implement the API defined in the library to provide the service to clients.

# librarysvc/librarysrv/server.py
import logging
import grpc
from library import library_pb2, library_pb2_grpc

class LibraryServer(library_pb2_grpc.LibraryServiceServicer):
    def GetBook(self, request, context):
        # TODO: Find the book from database.
        return library_pb2.Book(
            title="Title here.",
            author="Author here."
        )

Setting Up the Server

Creating and Running the Server

Use gRPC to create and run the server. Keep app.py focused on establishing connections and starting the server, and delegate the actual implementation to internal packages. For details, see Starting the python server.

# app.py
from concurrent import futures
import os
import time
import logging

import grpc

from librarysvc.librarysrv.server import LibraryServer
from library import library_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    library_pb2_grpc.add_LibraryServiceServicer_to_server(LibraryServer(), server)
    server.add_insecure_port('[::]:{}'.format(os.environ['PORT']))
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    logging.basicConfig()
    serve()

Server Logging

TBD

Project Organization

Directory Structure

TBD

All guides