2021-04-25 01:49:53 +02:00
|
|
|
from pathlib import Path
|
2021-02-24 22:55:55 +01:00
|
|
|
from unicodedata import name
|
|
|
|
|
|
|
|
from fastapi import FastAPI
|
|
|
|
from fastapi.responses import HTMLResponse
|
|
|
|
from pydantic import BaseModel
|
|
|
|
|
|
|
|
from charindex import InvertedIndex
|
|
|
|
|
2021-02-28 21:16:44 +01:00
|
|
|
app = FastAPI( # <1>
|
2021-02-24 22:55:55 +01:00
|
|
|
title='Mojifinder Web',
|
|
|
|
description='Search for Unicode characters by name.',
|
|
|
|
)
|
|
|
|
|
2021-02-28 21:16:44 +01:00
|
|
|
class CharName(BaseModel): # <2>
|
2021-02-24 22:55:55 +01:00
|
|
|
char: str
|
|
|
|
name: str
|
|
|
|
|
2021-02-28 21:16:44 +01:00
|
|
|
def init(app): # <3>
|
2021-02-24 22:55:55 +01:00
|
|
|
app.state.index = InvertedIndex()
|
2021-04-25 01:49:53 +02:00
|
|
|
static = Path(__file__).parent.absolute() / 'static' # <4>
|
|
|
|
app.state.form = (static / 'form.html').read_text()
|
2021-02-24 22:55:55 +01:00
|
|
|
|
2021-03-22 16:24:21 +01:00
|
|
|
init(app) # <5>
|
2021-02-28 21:16:44 +01:00
|
|
|
|
2021-03-22 16:24:21 +01:00
|
|
|
@app.get('/search', response_model=list[CharName]) # <6>
|
|
|
|
async def search(q: str): # <7>
|
2021-02-28 21:16:44 +01:00
|
|
|
chars = app.state.index.search(q)
|
2021-03-22 16:24:21 +01:00
|
|
|
return ({'char': c, 'name': name(c)} for c in chars) # <8>
|
2021-02-24 22:55:55 +01:00
|
|
|
|
2021-03-22 16:24:21 +01:00
|
|
|
@app.get('/', response_class=HTMLResponse, include_in_schema=False)
|
|
|
|
def form(): # <9>
|
2021-02-24 22:55:55 +01:00
|
|
|
return app.state.form
|
2021-03-22 16:24:21 +01:00
|
|
|
|
2021-04-25 01:49:53 +02:00
|
|
|
# no main funcion # <10>
|