keijack / python-eureka-client

A eureka client written in python. Support registering your python component to Eureka Server, as well as calling remote services by pulling the the Eureka registry.
MIT License
184 stars 43 forks source link

How to use Requests library with py_eureka_client #29

Closed sid8491 closed 4 years ago

sid8491 commented 4 years ago

Most of my code is written using the requests library, and py_eureka_client is implemented using urllib library. I have a common function to call the services.

I was wondering if it possible to use requests library along with py_eureka_client ?

Currently I am using something like below: resp = eureka_client.do_service(MY_SERVICE, service = "/abc/xyz/movies/list", method="GET", headers=headers, return_type="json")

I have read there is an option walker but I could not understand how to use it. And how to pass additional args to it.

I want to use requests library so that I don't have to change the rest of the code after getting response from the service.

keijack commented 4 years ago

How about using this:

import py_eureka_client.http_client as http_client

# 1. Inherit the `HttpClient` class in `py_eureka_client.http_client`.
class MyHttpClient(http_client.HttpClient):

    # 2. Rewrite the `urlopen` method in your class.
    # If you want to raise an exception, please make sure that the exception is an `urllib.error.HTTPError` or `urllib.error.URLError`
    # (urllib2.HTTPError or urllib2.URLError in python 2), or it may cause some un-handled errors.
    def urlopen(self):
        # The flowing code is the default implementation, you can see what fields you can use. you can change your implementation here
        res = urllib2.urlopen(self.request, data=self.data, timeout=self.timeout,
                            cafile=self.cafile, capath=self.capath,
                            cadefault=self.cadefault, context=self.context)

        if res.info().get("Content-Encoding") == "gzip":
            try:
                # python2
                f = gzip.GzipFile(fileobj=StringIO(res.read()))
            except NameError:
                f = gzip.GzipFile(fileobj=res)
        else:
            f = res

        txt = f.read().decode(_DEFAULT_ENCODING)
        f.close()
        return txt

# 3. Set your class to `py_eureka_client.http_client`. 
http_client.set_http_client_class(MyHttpClient)
keijack commented 4 years ago

no response for long time

sid8491 commented 4 years ago

hi sorry, been busy could not reply. actually i used walk_nodes function to get the url and then simply used that url to call the api using requests library. thanks for the reply and help though.

keijack commented 4 years ago

It's OK if you want just to use the request library to call the SERVICE. py_eureka_client.http_client also make the possibility to change the library to visit eureka server.