refactor httpdemo 1
This commit is contained in:
@@ -3,66 +3,32 @@ from fastapi import FastAPI
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from fastapi import Request
|
||||
from elasticsearch import Elasticsearch
|
||||
#from elasticsearch import Elasticsearch
|
||||
import sys
|
||||
import elastic_transport
|
||||
|
||||
ELASTIC_HOST = "http://localhost:9200"
|
||||
client = Elasticsearch(ELASTIC_HOST, verify_certs=False)
|
||||
|
||||
from searching import es_search, es_query
|
||||
import json
|
||||
import yaml
|
||||
app = FastAPI(debug=True)
|
||||
|
||||
templates = Jinja2Templates(directory="./httpdemo")
|
||||
#app.mount("/", StaticFiles(directory="/"))
|
||||
|
||||
|
||||
#@app.get("/")
|
||||
#def read_root():
|
||||
# return {"Hello"}
|
||||
|
||||
|
||||
query ={
|
||||
"multi_match":{
|
||||
"query": ELASTIC_QUERY,
|
||||
"fields": ["title^20","title.ngrams^10","text","text.ngrams"],
|
||||
"type": "most_fields"
|
||||
}
|
||||
}
|
||||
highlight = {
|
||||
"fields": {
|
||||
"title": {},
|
||||
"text": {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def serve_home(request: Request, q: str):
|
||||
query= {
|
||||
"bool":{
|
||||
"should": [{"wildcard": {"body": {"value": "*%s*"% q, "case_insensitive": True }}},
|
||||
{"wildcard": {"title": {"value": "*%s*" % q, "case_insensitive": True }}}],
|
||||
"minimum_should_match": 1
|
||||
}}
|
||||
query = {
|
||||
"match": {
|
||||
"body": q
|
||||
}
|
||||
}
|
||||
|
||||
def serve_home(request: Request, q: str=""):
|
||||
try:
|
||||
resp = client.search(
|
||||
index = "posts2",
|
||||
size=10,
|
||||
#analyze_wildcard=True,
|
||||
#q="sdf*",
|
||||
query= query
|
||||
)
|
||||
resp = es_search(q)
|
||||
query=es_query(q)
|
||||
message = "found ...?"
|
||||
except (elastic_transport.ConnectionError, elastic_transport.ConnectionTimeout) as e:
|
||||
print(e,sys.stderr)
|
||||
results=[]
|
||||
resp={}
|
||||
query={}
|
||||
message = f"cannot reach the search server! : %s" % e
|
||||
else:
|
||||
results=resp["hits"]["hits"]
|
||||
return templates.TemplateResponse("index.html", context= {"request": request,"results": results})
|
||||
|
||||
templates.env.filters["json"]=lambda x: yaml.dump(dict(x))
|
||||
return templates.TemplateResponse("index.html", context= {
|
||||
"request": resp,"results": results,"message": message, "query": query})
|
||||
Reference in New Issue
Block a user