python 轻量 web 框架 Bottle 使用

代码!

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')

 

转载于:https://www.cnblogs.com/whm-blog/p/10848933.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值