Skip to content

Instantly share code, notes, and snippets.

@chbndrhnns
Created October 12, 2021 13:07
Show Gist options
  • Save chbndrhnns/bbb70d20d7619d91220255c18d2113bd to your computer and use it in GitHub Desktop.
Save chbndrhnns/bbb70d20d7619d91220255c18d2113bd to your computer and use it in GitHub Desktop.
what's not to like about this code?
import os
import random
from time import sleep
import httpx
class TaskRepository:
def get_all(self):
return []
class TaskService:
def __init__(self):
self._repository = TaskRepository()
def expensive_operation(self):
if random.randint(0, 1):
# Sleep for 5.5 seconds
sleep(5.0)
return 42
return 20000
def all(self):
# Returns tasks
return httpx.get("https://jsonplaceholder.typicode.com/todos/",
allow_redirects=True).json()
def get(self, id):
host = os.getenv("MY_SERVICE_HOST", "jsonplaceholder.typicode.com")
res = httpx.get(f"https://{host}/todos/{id}", allow_redirects=True)
try:
res.raise_for_status()
except Exception:
return "problem"
return res.json()
def delete(self, url):
httpx.delete(url, headers={"Authorization": "Bearer some-token"})
def main():
"""Run the program"""
service = TaskService()
res = service.expensive_operation()
# Load task from server
tasks = service.all()
for task in tasks:
print(task)
my_task = service.get(res)
print(my_task)
print(httpx.post("https://jsonplaceholder.typicode.com/todos",
json={"title": "new_task", "body": "important", "userId": 1},
allow_redirects=True))
tasks = service.all()
for task in tasks:
if task["title"] == "new_task":
url = "https://jsonplaceholder.typicode.com/todos/" + task["id"]
service.delete(url)
print("Task deleted")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment