Search persons by name
This commit is contained in:
parent
3113bacc11
commit
37ae73ef1f
2 changed files with 13 additions and 2 deletions
5
main.py
5
main.py
|
|
@ -195,9 +195,10 @@ async def delete_meal(meal_id: int, conn: sqlite3.Connection = Depends(get_db))
|
||||||
return meal
|
return meal
|
||||||
|
|
||||||
@app.get("/persons/")
|
@app.get("/persons/")
|
||||||
async def get_persons(conn: sqlite3.Connection = Depends(get_db)) -> List[meals.Person]:
|
async def get_persons(q: str = None, conn: sqlite3.Connection = Depends(get_db)) -> List[meals.Person]:
|
||||||
|
query = persons.search_by_name(conn, q) if q else persons.get_all(conn)
|
||||||
result = []
|
result = []
|
||||||
async for person in persons.get_all(conn):
|
async for person in query:
|
||||||
result.append(person)
|
result.append(person)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,16 @@ async def create(conn):
|
||||||
name TEXT UNIQUE
|
name TEXT UNIQUE
|
||||||
);''')
|
);''')
|
||||||
|
|
||||||
|
async def search_by_name(conn, name: str) -> List[Person]:
|
||||||
|
async with conn.execute('''
|
||||||
|
SELECT id, name
|
||||||
|
FROM Person
|
||||||
|
WHERE name LIKE ?
|
||||||
|
''', (f'%{name}%',)) as cursor:
|
||||||
|
async for row in cursor:
|
||||||
|
yield Person(id=row[0], name=row[1])
|
||||||
|
|
||||||
|
|
||||||
async def get_by_name(conn, name: str) -> Person:
|
async def get_by_name(conn, name: str) -> Person:
|
||||||
cursor = await conn.execute('''
|
cursor = await conn.execute('''
|
||||||
SELECT id, name
|
SELECT id, name
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue