首页 > 技术文章 > python 轻量 web 框架 Bottle 使用

whm-blog 2019-05-11 15:58 原文

代码!

from string import Template

from bottle import route, run, template, request

from create_index.ElSearchFactory import ElSearchFactory

client = ElSearchFactory.get_client()

queryTemp = Template("""
    {
    "from": 0,
    "size": 10,
    "query": {
        "more_like_this": {
            "fields": [
                "title"
            ],
            "like": [
                "${q}"
            ],
            "min_doc_freq": 1,
            "min_term_freq": 1
        }
    }
}
    """)


class ResponseResult:
    @staticmethod
    def error(msg):
        return {
            'msg': msg,
            'status': 'error'
        }


def get_type(type_str: str):
    prefix = 'resources-'
    if type_str == 'hotel' or type_str == 'scenic':
        return prefix + type_str
    else:
        return None


@route('/<index_type>/like')
def like(index_type: str):
    q = request.query.q
    el_type = get_type(index_type)

    if el_type is None:
        return ResponseResult.error("参数错误")
    query = queryTemp.substitute(q=q)

    q = client.search(el_type, body=query)
    q = q['hits']['hits']
    result_list = []
    for it in q:
        result_list.append(
            it['_source']
        )
    # bottle 只能将字典转 json !! 所以只能返回字典
    return {
        'status': 'success',
        'data': result_list
    }


@route('/<index_type>/match')
def match(index_type: str, q: str):
    q = request.query.q
    el_type = get_type(index_type)
    if el_type is None:
        return ResponseResult.error("参数错误")

    return q


if __name__ == '__main__':
    run(host='0.0.0.0', port='7000')

 

推荐阅读