From d95fa436eb5e3f3a331762c823f5911261208d67 Mon Sep 17 00:00:00 2001 From: Andi Date: Thu, 13 Apr 2023 09:46:37 +0200 Subject: [PATCH] refactor httpdemo 1 --- httpdemo/__init__.py | 64 +++++++++++--------------------------------- httpdemo/index.html | 27 ++++++++++++++----- 2 files changed, 35 insertions(+), 56 deletions(-) diff --git a/httpdemo/__init__.py b/httpdemo/__init__.py index c43ca44..e956ed0 100644 --- a/httpdemo/__init__.py +++ b/httpdemo/__init__.py @@ -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}) \ No newline at end of file + + templates.env.filters["json"]=lambda x: yaml.dump(dict(x)) + return templates.TemplateResponse("index.html", context= { + "request": resp,"results": results,"message": message, "query": query}) \ No newline at end of file diff --git a/httpdemo/index.html b/httpdemo/index.html index 368b7a2..f54bff1 100644 --- a/httpdemo/index.html +++ b/httpdemo/index.html @@ -1,10 +1,23 @@ + + -

Hello Index httpdemo

-

{{request}}

-