Skip to content

Commit c8bcdb5

Browse files
authored
Implementation of automatic token renewal with a usage example
Thank you for the improvements!
2 parents f5442b8 + 4ca949b commit c8bcdb5

File tree

3 files changed

+58
-1
lines changed

3 files changed

+58
-1
lines changed

example/example.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from datetime import datetime
33

44
from marzban import MarzbanAPI, AdminCreate, UserCreate, NodeCreate, UserTemplateCreate, AdminModify, UserModify, \
5-
UserTemplateModify, NodeModify, ProxySettings
5+
UserTemplateModify, NodeModify, ProxySettings, MarzbanTokenCache
66

77

88
async def main():
@@ -215,5 +215,25 @@ async def main():
215215
# Closing the API client
216216
await api.close()
217217

218+
219+
async def main_with_token_cache():
220+
# An example of usage with auto-renewal of a token after its expiration
221+
api = MarzbanAPI(base_url="http://marzban-api.com")
222+
223+
marz_token = MarzbanTokenCache(
224+
client=api,
225+
username='login', password='password',
226+
token_expire_minutes=1440 # DEFAULT VALUE (Optional argument)
227+
)
228+
# Get a list of users
229+
users = await api.get_users(token=await marz_token.get_token(), offset=0, limit=10)
230+
print("Users:", users)
231+
232+
# Get list of nodes
233+
nodes = await api.get_nodes(token=await marz_token.get_token())
234+
print("Nodes:", nodes)
235+
236+
237+
218238
# Run the main async function
219239
asyncio.run(main())

marzban/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from .api import MarzbanAPI
2+
from .utils import MarzbanTokenCache
23
from .models import (
34
Admin,
45
AdminCreate,
@@ -34,6 +35,7 @@
3435
__all__ = (
3536
"__version__",
3637
"MarzbanAPI",
38+
"MarzbanTokenCache",
3739
"Admin",
3840
"AdminCreate",
3941
"AdminModify",

marzban/utils.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import logging
2+
from datetime import datetime, timedelta
3+
from typing import Optional
4+
5+
from marzban import MarzbanAPI
6+
7+
8+
class MarzbanTokenCache:
9+
def __init__(self, client: MarzbanAPI,
10+
username: str, password: str,
11+
token_expire_minutes: int = 1440):
12+
self._client = client
13+
self._username = username
14+
self._password = password
15+
self._token_expire_minutes = token_expire_minutes
16+
self._token: Optional[str] = None
17+
self._exp_at: Optional[datetime] = None
18+
19+
async def get_token(self):
20+
if not self._exp_at or self._exp_at < datetime.now():
21+
logging.info(f'Get new token')
22+
self._token = await self.get_new_token()
23+
self._exp_at = datetime.now() + timedelta(minutes=self._token_expire_minutes - 1)
24+
return self._token
25+
26+
async def get_new_token(self):
27+
try:
28+
token = await self._client.get_token(
29+
username=self._username,
30+
password=self._password
31+
)
32+
return token.access_token
33+
except Exception as e:
34+
logging.error(f'{e}', exc_info=True)
35+
raise e

0 commit comments

Comments
 (0)