Skip to content

Commit

Permalink
Update api
Browse files Browse the repository at this point in the history
  • Loading branch information
hdakhli committed Nov 21, 2023
1 parent 96fa6e9 commit 4daf4a8
Show file tree
Hide file tree
Showing 8 changed files with 82 additions and 62 deletions.
9 changes: 0 additions & 9 deletions 6_architecture/api/quiz_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,5 @@ def say_hello(username: str) -> dict:
}


@app.post("/send-answer")
def answer(username: str, question_id: int, answer_id: int) -> dict:
return {
"username": username,
"question_id": question_id,
"answer_id": answer_id
}


if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=5000)
42 changes: 31 additions & 11 deletions 6_architecture/api/quiz_dao.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import logging
import sqlite3
from sqlite3 import OperationalError


class QuizDAO:
def __init__(self):
self.database = 'quiz.db'
sql = '''CREATE TABLE QUIZ (id INTEGER PRIMARY KEY,
question_id INT NOT NULL,
user_name text NOT NULL,
answer_id INT NOT NULL);'''
with self.create_connection() as conn:
cur = conn.cursor()
cur.execute(sql)
conn.commit()
sql = '''CREATE TABLE QUIZ (question_id INT NOT NULL,
user_name text NOT NULL,
answer_id INT NOT NULL,
PRIMARY KEY (question_id, user_name));'''
try:
with self._create_connection() as conn:
cur = conn.cursor()
cur.execute(sql)
conn.commit()
except OperationalError as error:
logging.error("Database error", error.args)

def create_connection(self):
def _create_connection(self):
conn = None
try:
conn = sqlite3.connect(self.database)
Expand All @@ -24,16 +29,31 @@ def create_connection(self):
def create_answer(self, question_id, user_name, answer_id):
sql = ''' INSERT INTO QUIZ (question_id, user_name, answer_id)
VALUES(?,?,?) '''
with self.create_connection() as conn:
with self._create_connection() as conn:
cur = conn.cursor()
cur.execute(sql, (question_id, user_name, answer_id))
conn.commit()

def count_answers_by_id(self, question_id: int):
sql = ''' SELECT * FROM QUIZ WHERE question_id=?'''
with self.create_connection() as conn:
with self._create_connection() as conn:
cur = conn.cursor()
cur.execute(sql, (question_id,))
rows = cur.fetchall()
print(f"rows: {rows}")
return len(rows)

def update_answer(self, question_id: int, user_name, answer_id):
sql = ''' UPDATE QUIZ SET answer_id=? WHERE question_id=? AND user_name=?'''
with self._create_connection() as conn:
cur = conn.cursor()
cur.execute(sql, (answer_id, question_id, user_name))
conn.commit()

def get_all_answers(self):
sql = ''' SELECT * FROM QUIZ '''
with self._create_connection() as conn:
cur = conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
return rows
36 changes: 36 additions & 0 deletions 6_architecture/async_call/async_call.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import random
from datetime import datetime

import requests
import uvicorn
from fastapi import FastAPI

app = FastAPI()


@app.get("/get-a-random")
def get_a_random_data() -> list:
start = datetime.now()

dog_response = call_api('https://dog.ceo/api/breeds/image/random')
cat_response = call_api('https://catfact.ninja/fact')
pokemon_response = call_api(f'https://pokeapi.co/api/v2/pokemon/{random.randint(0, 100)}')
user_response = call_api('https://randomuser.me/api/')
joke_response = call_api('https://official-joke-api.appspot.com/random_joke')
products_response = call_api('https://hub.dummyapis.com/products?noofRecords=10&idStarts=1001&currency=usd')

responses = [dog_response, cat_response, pokemon_response, joke_response, user_response, products_response]

end = datetime.now()
print(f"duration = {end - start}")

return responses


def call_api(url):
response = requests.get(url)
return response.json()


if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=5000)
29 changes: 0 additions & 29 deletions 6_architecture/async_call/no_async_call.py

This file was deleted.

3 changes: 2 additions & 1 deletion 6_architecture/async_call/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
requests==2.28.1
requests==2.28.1
aiohttp==3.9.0
Empty file.
15 changes: 8 additions & 7 deletions 6_architecture/concurrency/multiprocessing_calls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import time
from multiprocessing import Pool

import multiprocessing

def call_function(user_name):
time.sleep(0.2)
Expand All @@ -11,14 +10,16 @@ def call_function(user_name):
start_time = time.time()

users = []
for user_id in range(1, 15):
for user_id in range(1, 16):
users.append(user_id)

for user in users:
call_function(user)
cpu_count = multiprocessing.cpu_count()
print(f"cpu count = {cpu_count}")

pool = multiprocessing.Pool(cpu_count)

pool.map(call_function, users)

# pool = Pool(15)
# pool.map(call_function, users)

end_time = time.time()
duration = end_time - start_time
Expand Down
10 changes: 5 additions & 5 deletions 6_architecture/concurrency/multithreading_calls.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from threading import Thread
import time
from threading import Thread


def call_function(user_name):
Expand All @@ -10,19 +10,19 @@ def call_function(user_name):
if __name__ == '__main__':
start_time = time.time()
users = []
for user_id in range(1, 15):
for user_id in range(1, 16):
users.append(user_id)

# creating threads
threads = []
for user in users:
th = Thread(target=call_function, args=(user,))
th.start()
threads.append(th)
th.start()

# check the end of all threads
for th in threads:
th.join()


end_time = time.time()
duration = end_time - start_time
print(f"Duration: {duration}")

0 comments on commit 4daf4a8

Please sign in to comment.