zoukankan      html  css  js  c++  java
  • 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')
  • 相关阅读:
    复利计算器2.01
    复利计算器2.0
    0429团队3.0
    0428 团队项目合作2.0作业
    "数学口袋精灵"bug
    操作系统-实验2
    博客评论
    复利计算升级
    0408 结对合作
    0406复利计算5.0
  • 原文地址:https://www.cnblogs.com/whm-blog/p/10848933.html
Copyright © 2011-2022 走看看