Skip to content

Refactor APIHandler #9

@burrscurr

Description

@burrscurr

Most single actions have a very similar structure, for example set_wifi(..), get_link_local(...) etc. This could be refactored using a generic method like this:

class APIHandler:    
    def _execute_command(self, command, data):
        """
        Send a POST request to the IP camera with given JSON body and
        :param command: name of the command to send
        :param data: object to send to the camera
        :return: response as python object
        """
        try:
            if self.token is None:
                raise ValueError("Login first")
            response = Request.post(self.url, data=data, params={"cmd": command, "token": self.token})
            return json.loads(response.text)
        except Exception as e:
            print(f"Command {command} failed: {e}")
            raise

    def set_wifi(self, ssid, password) -> json or None:
        body = [{"cmd": "SetWifi", "action": 0, "param": {
                "Wifi": {
                    "ssid": ssid,
                    "password": password
        }}}]
        return self._execute_command('SetWifi', body)

    def get_link_local(self):
        """
        Get General network data
        This includes IP address, Device mac, Gateway and DNS
        :return:
        """
        body = [{"cmd": "GetLocalLink", "action": 1, "param": {}}]
        return self._execute_command('GetLocalLink', body)

That's just a simple draft. This or similar refactoring could shorten the APIHandler.py file a lot and make the code much more readable.

If such refactoring is appreciated, I'm happy to create a PR.

Metadata

Metadata

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions