首页 > 解决方案 > 如何将 Flask-RESTPlus 与请求相结合:人类的 HTTP?

问题描述

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

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

这是代码片段:

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

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

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

标签: pythonflaskpython-requestsflask-restfulflask-restplus

解决方案


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

这部分代码:

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

args = query_parser.parse_args()

当您要求源来帮助您学习时,这是 requests 在 URL 开头检查适配器的代码,您可以在此处的源代码中找到:

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()来自这里

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

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


推荐阅读