Skip to content

Instantly share code, notes, and snippets.

View rockink's full-sized avatar

Nirmal Nepal rockink

View GitHub Profile
from functools import lru_cache
@lru_cache(maxsize=10)
def make_call(page: int):
API_SERVER = f"https://jsonplaceholder.typicode.com/posts/{page}"
return requests.get(API_SERVER).json()
# calculate how long it would take for func to complete.
def calculate_time(func):
start_time = datetime.now().timestamp()
print(func())
end_time = datetime.now().timestamp()
print("TimeTaken", end_time - start_time)
def make_call_1():
def calculate_time(func):
start_time = datetime.now().timestamp()
print(func())
end_time = datetime.now().timestamp()
print("TimeTaken", end_time - start_time)
calculate_time(lambda: make_call(1))
import requests
def make_call(page: int):
API_SERVER = f"https://jsonplaceholder.typicode.com/posts/{page}"
return requests.get(API_SERVER).json()
def get_post_comments(post_id: int) -> List[BlogPost]:
SERVER_ENDPOINT = "https://jsonplaceholder.typicode.com/comments"
response = requests.get(
SERVER_ENDPOINT,
params=dict(postId=post_id) # NEW CONCEPT: notice the post id there?
)
if response.status_code == 200:
# NEW CONCEPT: read the for loop in 1 line. Note how everything wires up.
return response.json()
def update_blog(blog_post: BlogPost) -> BlogPost:
SERVER_ENDPOINT = f"https://jsonplaceholder.typicode.com/posts/{blog_post.id}"
# NEW CONCEPT: This basically converts the dataclass into dictionary
blog_dict = asdict(blog_post)
response = requests.put(
SERVER_ENDPOINT,
json=blog_dict
)
return BlogPost(**response.json())
def post_blog(title: str, body: str, user_id: int):
SERVER_ENDPOINT = "https://jsonplaceholder.typicode.com/posts"
response = requests.post(
SERVER_ENDPOINT,
json=dict(
title=title,
body=body,
userId=user_id
)
)
def get_single_post(post_id: int) -> BlogPost:
# NEW CONCEPT: note the f, this basically means formatting the string. Anything with curly braces will be replaced
# by actual value
SERVER_ENDPOINT = f"https://jsonplaceholder.typicode.com/posts/{post_id}"
response = requests.get(SERVER_ENDPOINT)
if response.status_code == 200:
return BlogPost(**response.json())
from dataclasses import dataclass
from typing import List
import requests
@dataclass
class BlogPost:
userId: int
id: int
from dataclasses import dataclass
from typing import List
import requests
@dataclass
class BlogPost:
userId: int
id: int