ch 21 and 22: updated examples
This commit is contained in:
parent
1702717182
commit
66e46a6db6
@ -1,7 +1,3 @@
|
|||||||
"""
|
|
||||||
uvicorn main:app --reload
|
|
||||||
"""
|
|
||||||
|
|
||||||
import pathlib
|
import pathlib
|
||||||
from unicodedata import name
|
from unicodedata import name
|
||||||
|
|
||||||
@ -11,28 +7,30 @@ from pydantic import BaseModel
|
|||||||
|
|
||||||
from charindex import InvertedIndex
|
from charindex import InvertedIndex
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI( # <1>
|
||||||
title='Mojifinder Web',
|
title='Mojifinder Web',
|
||||||
description='Search for Unicode characters by name.',
|
description='Search for Unicode characters by name.',
|
||||||
)
|
)
|
||||||
|
|
||||||
class CharName(BaseModel):
|
class CharName(BaseModel): # <2>
|
||||||
char: str
|
char: str
|
||||||
name: str
|
name: str
|
||||||
|
|
||||||
def init(app):
|
def init(app): # <3>
|
||||||
app.state.index = InvertedIndex()
|
app.state.index = InvertedIndex()
|
||||||
static = pathlib.Path(__file__).parent.absolute() / 'static'
|
static = pathlib.Path(__file__).parent.absolute() / 'static'
|
||||||
with open(static / 'form.html') as fp:
|
with open(static / 'form.html') as fp:
|
||||||
app.state.form = fp.read()
|
app.state.form = fp.read()
|
||||||
|
|
||||||
init(app)
|
init(app) # <4>
|
||||||
|
|
||||||
@app.get('/', response_class=HTMLResponse, include_in_schema=False)
|
@app.get('/search', response_model=list[CharName]) # <5>
|
||||||
|
async def search(q: str): # <6>
|
||||||
|
chars = app.state.index.search(q)
|
||||||
|
return ({'char': c, 'name': name(c)} for c in chars) # <7>
|
||||||
|
|
||||||
|
@app.get('/', # <8>
|
||||||
|
response_class=HTMLResponse,
|
||||||
|
include_in_schema=False)
|
||||||
def form():
|
def form():
|
||||||
return app.state.form
|
return app.state.form
|
||||||
|
|
||||||
@app.get('/search', response_model=list[CharName])
|
|
||||||
async def search(q: str):
|
|
||||||
chars = app.state.index.search(q)
|
|
||||||
return [{'char': c, 'name': name(c)} for c in chars]
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user