Fix TypeError: can't concat str to bytes.

Handle invalid use of the library.
This commit is contained in:
Jakub Gocławski 2025-03-07 10:27:27 +01:00
parent d05c0b13ef
commit 4728e5c35c
No known key found for this signature in database
GPG key ID: DB23479BBC13E2A3
2 changed files with 38 additions and 24 deletions

View file

@ -15,15 +15,13 @@ Python API to RouterBoard devices produced by [MikroTik](https://mikrotik.com/)
### Connection ### Connection
```python ```python
#!/usr/bin/python
import routeros_api import routeros_api
connection = routeros_api.RouterOsApiPool('IP', username='admin', password='') connection = routeros_api.RouterOsApiPool('IP', username='admin', password='')
api = connection.get_api() api = connection.get_api()
``` ```
#### Connect Options #### Connection parameters
```python ```python
routeros_api.RouterOsApiPool( routeros_api.RouterOsApiPool(
@ -94,6 +92,13 @@ routeros_api.RouterOsApiPool(host, username='admin', password='', plaintext_logi
Call this with a resource and parameters as name/value pairs. Call this with a resource and parameters as name/value pairs.
```python
api.get_resource('/').call('<resource>', { <dict of params> })
```
You can also use the "binary" version, but in this case, all dict values
should be encoded to bytes and the result will be returned as bytes.
```python ```python
api.get_binary_resource('/').call('<resource>', { <dict of params> }) api.get_binary_resource('/').call('<resource>', { <dict of params> })
``` ```
@ -101,8 +106,8 @@ api.get_binary_resource('/').call('<resource>',{ <dict of params> })
#### Examples #### Examples
```python ```python
api.get_binary_resource('/').call('tool/fetch',{ 'url': "https://dummy.url" }) api.get_resource('/').call('tool/fetch', {'url': 'https://dummy.url'})
api.get_binary_resource('/').call('ping', { 'address': '192.168.56.1', 'count': '4' }) api.get_resource('/').call('ping', {'address': '192.168.56.1', 'count': '4'})
``` ```
### Fetch List/Resource ### Fetch List/Resource
@ -126,15 +131,15 @@ list_queues.get()
### Add rules ### Add rules
```python ```python
list.add(attribute="vale", attribute_n="value") list.add(attribute='vale', attribute_n='value')
``` ```
**NOTE**: Atributes with `-`, like `max-limit` use underscore `_`: `max_limit` **NOTE**: Attributes with `-`, like `max-limit` use underscore `_`: `max_limit`
#### Example: #### Example:
```python ```python
list_queues.add(name="001", max_limit="512k/4M", target="192.168.10.1/32") list_queues.add(name='001', max_limit='512k/4M', target='192.168.10.1/32')
``` ```
### Update Values ### Update Values
@ -146,7 +151,7 @@ list.set(id, attributes)
#### Example: #### Example:
```python ```python
list_queues.set(id="*2", name="jhon") list_queues.set(id='*2', name='john')
``` ```
### Get element: ### Get element:
@ -158,7 +163,7 @@ list.get(attribute=value)
#### Example: #### Example:
```python ```python
list_queues.get(name="jhon") list_queues.get(name='john')
``` ```
### Remove element: ### Remove element:
@ -170,7 +175,7 @@ list.remove(id)
#### Example: #### Example:
```python ```python
list_queues.remove(id="*2") list_queues.remove(id='*2')
``` ```
### Close conection: ### Close conection:
@ -181,25 +186,24 @@ connection.disconnect()
### Run script and get output ### Run script and get output
The example script only prints "hello". Here's a simplifed example of how to run it and get the output: The example script only prints "hello". Here's a simplified example of how
to run it and get the output:
``` ```
>>> api.get_resource("/system/script").get()[0]['source'] >>> api.get_resource('/system/script').get()[0]['source']
'/put "hello"' '/put "hello"'
>>> async_response = api.get_binary_resource('/').call('system/script/run', {"number": '0'.encode('utf-8')}) >>> response = api.get_resource('/system/script').call('run', {'number': '0'})
>>> async_response.__dict__ >>> response.done
{'command': <routeros_api.sentence.CommandSentence object at 0x73a0f2b3eba0>, 'done_message': {'ret': b'hello'}, 'done': True, 'error': None} True
>>> async_response.done_message['ret'] >>> response.done_message['ret']
b'hello' 'hello'
``` ```
### Other Example: ### Other Example:
```python ```python
list_address = api.get_resource('/ip/firewall/address-list') list_address = api.get_resource('/ip/firewall/address-list')
list_address.add(address="192.168.0.1",comment="P1",list="10M") list_address.add(address='192.168.0.1', comment='P1', list='10M')
response = list_address.get(comment='P1')
list_address.get(comment="P1") list_address.remove(id=response[0]['id'])
list_address.remove(id="*7")
``` ```

View file

@ -1,3 +1,8 @@
import logging
logger = logging.getLogger(__name__)
class EncodingApiCommunicator(object): class EncodingApiCommunicator(object):
def __init__(self, inner): def __init__(self, inner):
self.inner = inner self.inner = inner
@ -16,6 +21,11 @@ class EncodingApiCommunicator(object):
def transform_item(self, item): def transform_item(self, item):
key, value = item key, value = item
if not isinstance(value, bytes):
logger.warning(
'Non-bytes value passed as item value ({}). You should probably use api.get_resource() instead of '
'api.get_binary_resource() or encode arguments yourself.'.format(value))
value = value.encode()
return (key.encode(), value) return (key.encode(), value)
def decorate_promise(self, promise): def decorate_promise(self, promise):