How do you set a custom http client in Bravado?

谁都会走 提交于 2020-01-24 19:14:57

问题


I'm using Bravado 3.0.0. I want to make a request that will use my own custom CA Bundle. The underlying Requests client isn't taking advantage of the REQUESTS_CA_BUNDLE env var I've set.

How do I pass in a custom client that uses my CA Bundle?


回答1:


(This answer is based on the current-as-of-this-writing 8.1.0 version of Bravado)

Since it took me a while to even find this answer while learning about Bravado, and mostly because I think others might benefit when starting out, here's an updated look into how to establish a connection:

In order to leverage non-default settings in the HTTP client, (using Requests as an example,) one has to create a new HTTP client instance with it's own settings, then pass this to the SwaggerClient.from_url() call:

""" Required to create a new Requests 'http_client' instance: """
from bravado.requests_client import Requestsclient
""" Required to create a Bravado SwaggerClient instance: """
from bravado.client import SwaggerClient

""" Create a new Requests client instance: """
http_client = RequestsClient()

From here you can do all the fun stuff that Requests allows you to do, like set basic HTTP authentication:

http_client.set_basic_auth(SERVER, USER, PASS)

Or disable SSL certificate verification (Not recommended outside of a test environment):

http_client.session.verify = False

Or as your question and answer point out, supply a local certificate store to verify against:

http_client.session.cert = os.environ.get('REQUESTS_CA_BUNDLE')

From there, it's a simple matter of creating a SwaggerClient instance, pointing it to your swagger.json path, and referencing the Requests 'http_client' instance, (with pre-defined settings,) like so:

URL = 'https://myserver/api/path/to/swagger.json'
client = Swaggerclient.from_url(URL, http_client=http_client)



回答2:


I'm answering my own question here since I was stuck on this for a while and thought it would be nice to share what I've learned.

Since the REQUESTS_CA_BUNDLE env var is set, then we can create a new Requests client that's configured to use the CA Bundle. That can be passed into SwaggerClient to produce something that uses the CA Bundle when making Swagger API calls.

http_client = RequestsClient()
client.session.verify = os.environ.get('REQUESTS_CA_BUNDLE')
client = SwaggerClient.from_url(
    reverse('grafana_generator:swaggerapi', request=request),
    http_client=http_client,
)


来源:https://stackoverflow.com/questions/31887512/how-do-you-set-a-custom-http-client-in-bravado

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!