STEP 1: Design an ObjectMgr which manages a pool of objects. Objects can be considered to be ints (from 1 to n). It should provide api’s to get_object() and free_object():
get_object(): Returns any object available in the pool. An object cannot be given away again unless it has been freed. free_object(int obj): Returns the object back to the pool so that it can be given out again.
Please document the API’s definitions, data structures and write tests.
STEP 2:
- Write a GraphQL API schema to use the above functions to create, get and free objects.
- Deploy it as a service/container that can be used to deploy on a linux server.
In .app/object/objectmgr.py, created class ObjectMgr.
from collections import deque
from typing import Union
class ObjectMgr:
def __init__(self, n: int):
self.object_pool = deque(range(1, n))
self.allocated_objects = set()
self.freed_objects = deque()
- deque() - efficient element addition and removal.
def get_object(self) -> Union[int, None]:
if self.object_pool:
obj = self.object_pool.popleft()
self.allocated_objects.add(obj)
return obj
elif self.freed_objects:
obj = self.freed_objects.popleft()
self.allocated_objects.add(obj)
return obj
else:
return None
- set() - efficient to check whether an object is currently allocated or not.
def free_object(self, obj) -> Union[int, None]:
if obj in self.allocated_objects:
self.allocated_objects.remove(obj)
self.freed_objects.append(obj)
return obj
else:
raise ValueError("Object is not currently allocated.")
-
Make sure your python is <= "3.10.*"
-
Create virtual env, with:
python -m venv .venv
- move to app folder'
cd ./app
- Install requirements with pip:
pip install -r requirements.txt
- Or install requirements with poetry:
poetry install
- To run app:
flask run
flask --debug run
python app.py
gunicorn --worker-class gevent --workers 8 --bind 127.0.0.1:5000 app:"create_app()" --max-requests 10000 --timeout 5 --keep-alive 5 --log-level info --log-level info
-
create docker-compose.yml from:
- docker-compose.dev.yml
- or
- docker-compose.prod.yml
-
docker-compose up
- create /etc/systemd/system/tromzo-service.service
[Unit]
Description=Gunicorn instance to serve
After=network.target
[Service]
User=mngr-user
Group=www-data
WorkingDirectory=/home/tromzo/app
Environment="PATH=/home/tromzo/app/.venv/bin"
ExecStart=/home/tromzo/app/.venv/bin gunicorn --worker-class gevent --workers 8 --bind 0.0.0.0:3000 app:"create_app()" --max-requests 10000 --timeout 5 --keep-alive 5 --log-level info
[Install]
WantedBy=multi-user.target
sudo systemctl start tromzo-service
sudo systemctl enable tromzo-service
docker run --publish 3000:3000 -it --entrypoint ./start.sh objmngr-server/graphql
- in config.py if
default = "DevelopmentConfig"
- visit {your_host}/graphql to see/test API definitions
query {
getObject
}
mutation {
freeObject(obj: 1) {
success
}
}
- To run tests
pytest
p.s They liked the solution and I was moved to the next step.