Nriver / trilium-py

Python client for ETAPI of Trilium Note. Trilium 的 Python版 ETAPI 客户端
GNU Affero General Public License v3.0
118 stars 27 forks source link

How to test for valid login and etapi session? #39

Closed maphew closed 5 months ago

maphew commented 5 months ago

How to test for a valid login and ETAPI session gracefully?

For example this will fail with ugly json decode error if the server is wrong url:

server_url = "http://nas:8080/"
token = os.environ["TRILIUM_TOKEN"]

ea = ETAPI(server_url, token)
print(f'Source Trilium appVersion: {ea.app_info()["appVersion"]}')
...snip...
  File "A:\code\mhw\metril\.pixi\envs\default\Lib\site-packages\trilium_py\client.py", line 86, in app_info
    return res.json()
           ^^^^^^^^^^
  File "A:\code\mhw\metril\.pixi\envs\default\Lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The simpler print(ea.appinfo()) does the same, so I can't do something like if not ea.appinfo(): ...

And dropping the braces, so just print(ea.appinfo) emits <bound method ETAPI.app_info of <trilium_py.client.ETAPI object at 0x00000147F106E840>> which I don't know what to do with.

Nriver commented 5 months ago

There are many reasons to fail, which would be too verbose to handle all of them. I would just use a simple 'try except pass'.

maphew commented 5 months ago

Thanks for quick response! I hoped I was missing something like if ea.appinfo() == {any error at all}. I try to avoid bare 'try except' because it hides other things (and my brain is easily confused).

maphew commented 5 months ago

Here's the solution I chose for now. It feels a bit wierd to import requests for sole purpose of reporting a nice message, but it works.

import requests
try:
    # Trilium server
    server_url = "https://example.com/"
    token = os.environ["TRILIUM_TOKEN"]

    ea = ETAPI(target_url, target_token)
    print(ea.app_info())
except requests.exceptions.JSONDecodeError as e:
    print(f"JSON decode of ETAPI.app_info() failed. Are server and token set? Error: {e}")
    exit(1)

Result:

JSON decode of ETAPI.app_info() failed. Are server and token set? Error: Expecting value: line 1 column 1 (char 0)
maphew commented 5 months ago

update: this is generic, cleaner and doesn't need to import anything:

try:
    print(ea.app_info())
except Exception as e:
    print(f"Error on ETAPI.app_info(): {type(e).__name__}")
    print(f"Message: {e}")
    print("Are server and token set?")
    exit(1)
Error on ETAPI.app_info(): JSONDecodeError
Message: Expecting value: line 1 column 1 (char 0)
Are server and token set?