【问题标题】:How to combine Flask-RESTPlus with Requests: HTTP for Humans?如何将 Flask-RESTPlus 与请求相结合:人类的 HTTP?
【发布时间】:2019-08-14 15:29:57
【问题描述】:

我正在使用 Flask-RESTPlus 来创建端点,并使用 Requests: HTTP for Humans 从电子商务网站之一抓取产品详细信息。

我已经使用 Requests 完美地获得了产品详细信息,但是当我将它与 FLASK-RESTPlus 结合使用时,我遇到了一些问题。

这里是sn-p的代码:

@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'}'"
}

让我困惑的是为什么我之前可以得到产品详细信息。

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

【问题讨论】:

    标签: python flask python-requests flask-restful flask-restplus


    【解决方案1】:

    问题是您将args dict 传递给requests.post 作为url 参数。 Requests 会验证您提供给 .post() 的 url 是否有效,并且以 {'marketplace': ...} 开头的 url 显然是无效的 url。

    这部分代码:

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

    还有args = query_parser.parse_args()

    当您要求源来帮助您学习时,这是 requests 在 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)
    

    用于检查url的self.adapters.items()来自here

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

    mount() 方法本质上将预期的 url 前缀映射到 self.adapters 字典中的请求的连接适配器类型之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 2020-01-26
      • 2020-04-05
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多