How to get the name of the uri_path that Coap's client is writing to in Resource class?

150 Views Asked by At

I have defined my resource class as following;

class Humidity(resource.Resource):
    async def render_post(self, request):
        payload = request.payload.decode("ascii")
        print("Received message: ", payload, "from")
        return #aiocoap.Message(code=CHANGED, payload=b"ACK")

And this is the object instantiation;

root.add_resource(('humidity_sensor1_indus',), Humidity())

I would like to print the name of the uri_path ('humidity_sensor1_indus' in this case) where I am printing the received message.

So far I have tried the following but it does not work;

`class Humidity(resource.Resource):
    async def render_post(self, request):
        payload = request.payload.decode("ascii")
        print("Received message: ", payload, "from", request.uri_path)
        return #aiocoap.Message(code=CHANGED, payload=b"ACK")`

Let me know what you would do.

1

There are 1 best solutions below

0
chrysn On

The way you should be able to obtain the request's original URI is through request.get_request_uri(). (The information about the path alone would be in request.opt.uri_path, but in the course of path routing these items are removed).

However, due to a bug in aiocoap, the output of .get_request_uri() is wrong; it should be fixed in the next version (0.4.6).


By the way, you should rarely need that information (which is why that error was only discovered when answering your question): A handler should work the same no matter where it is instantiated. The only reason I've found so far for using the request path inside a handler is when working with data formats that do not have functioning relative URI references (eg. RFC6690 Link Format).