python - 如何将 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'}'"
}
让我困惑的是为什么我之前可以得到产品细节。
那么,我的代码有什么问题?,任何学习的示例或资源都会很棒。
解决方案
问题是您将args
dictrequests.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.adapters
dict 中请求的连接适配器类型之一。
推荐阅读
- android - M1 MacBook Pro 上的 Android Studio 无法使用 ABI armeabi-v7a 模拟系统映像
- snowflake-cloud-data-platform - Kafka ConnectStandalone - java.lang.IllegalArgumentException:格式错误的 \uxxxx 编码
- javascript - 使用three.js将透明背景PNG包裹在圆柱体周围时保留原始颜色
- python - 在 Pandas 中添加 DataFrame 中存在的列
- android - com.google.android.gms.common.api.ApiException: 10: 调用者未列入白名单以调用此 API
- android - version_defaults.mk 中的“REL”是什么意思?
- javascript - 使用 php 在 html 中生成条形码,给出相同的值
- c# - EF Core 中的查询超时,但在 SSMS 中运行速度很快
- android - 徽标和可序列化/保存功能在我的手机上可用,但在其他手机上不可用
- python - 在 Anaconda Spyder 环境中调试