I have some Python code that accesses data locally or remotely. To demonstrate this, the example below fetches a todo item from a remote JSON API or from a local JSON file. The _remote_todo
method fetches the todo item from the JSON API. The _local_todo
fetches the item from a local JSON file. The get_todo
method provides a single interface to locally or remotely get the todo item. Instead of defining three methods is there a way to consolidate this into one method? Maybe there is a way to define the local function and decorate it with the API call? Is there a design pattern that would lend itself well to this type of problem? I’m eager to know if there is a better way to write local and remote code in Python.
import json
import requests
class Todo:
def __init__(self, item_id: int):
self.item_id = item_id
def _remote_todo(self):
api = f"https://jsonplaceholder.typicode.com/todos/{self.item_id}"
resp = requests.get(api)
print(resp.json())
def _local_todo(self):
with open("todos.json") as f:
data = json.load(f)
for d in data:
if d["id"] == self.item_id:
print(d)
def get_todo(self, api: bool = False):
if api:
self._remote_todo()
else:
self._local_todo()
def main():
"""Run example."""
todo = Todo(item_id=2)
todo.get_todo(api=True)
todo.get_todo()
if __name__ == "__main__":
main()