代码之家  ›  专栏  ›  技术社区  ›  Tri

如何将Flask Resplust与请求结合起来:人类的HTTP?

  •  0
  • Tri  · 技术社区  · 7 年前

    我在用 创建端点并使用 从一个电子商务网站上抓取产品细节。

    请求

    以下是代码片段:

    @api.route('/product')
    class ProductDetails(Resource):
        query_parser = api.parser()
        query_parser.add_argument('marketplace', required=True, location='args')
    
        def post(self, query_parser=query_parser):
            args = query_parser.parse_args()
            url = args['marketplace']
    
            try:
                response = requests.post(
                    url=args,
                    json={
                         'url': url
                    }, timeout=60
               )
                }
            except Exception as e:
               return {
                    'status': 'error',
                    'message': str(e)
                }
    

    当我尝试访问终结点时

    http://localhost:5000/api/v1/product?marketplace=http://xx.xx.xx.xx/v1/markeplace_name/url
    

    我总是遇到这样的错误:

    {
        "status": "error",
        "message": "No connection adapters were found for '{'marketplace': 'http://xx.xx.xx.xx/v1/market_place_name/url'}'"
    }
    

    那么,我的代码有什么问题吗?任何可以学习的示例或源代码都会很好。

    1 回复  |  直到 7 年前
        1
  •  1
  •   SuperShoot npburns224    7 年前

    问题是你正在通过考试 args requests.post 作为url参数。请求验证您提供给的url .post() 是有效的,并且url以 {'marketplace': ...} 显然是无效的url。

    这部分代码:

    response = requests.post(
        url=args,
        json={
             'url': url
        }, timeout=60
    )
    

    以及 args = query_parser.parse_args()

    当您要求源代码来帮助您学习时,这是一段代码,您可以在源代码中找到url开头的请求检查适配器 here :

    def get_adapter(self, url):
        """
        Returns the appropriate connection adapter for the given URL.
        :rtype: requests.adapters.BaseAdapter
        """
        for (prefix, adapter) in self.adapters.items():
    
            if url.lower().startswith(prefix.lower()):
                return adapter
    
        # Nothing matches :-/
        raise InvalidSchema("No connection adapters were found for '%s'" % url)
    

    这个 self.adapters.items() 用于检查url的来源 here

    # Default connection adapters.
    self.adapters = OrderedDict()
    self.mount('https://', HTTPAdapter())
    self.mount('http://', HTTPAdapter())
    

    mount() 方法实际上将预期的url前缀映射到 self.adapters 口述。