mirror of
https://github.com/aiogram/aiogram.git
synced 2025-12-12 18:19:34 +00:00
Fix payload generator for lists and dicts. (Add more comments in this util)
This commit is contained in:
parent
ff2b7f9682
commit
21f35273b7
1 changed files with 34 additions and 5 deletions
|
|
@ -2,10 +2,19 @@ import datetime
|
||||||
|
|
||||||
from . import json
|
from . import json
|
||||||
|
|
||||||
DEFAULT_FILTER = ['self']
|
DEFAULT_FILTER = ['self', 'cls']
|
||||||
|
|
||||||
|
|
||||||
def generate_payload(exclude=None, **kwargs):
|
def generate_payload(exclude=None, **kwargs):
|
||||||
|
"""
|
||||||
|
Generate payload
|
||||||
|
|
||||||
|
Usage: payload = generate_payload(**locals(), exclude=['foo'])
|
||||||
|
|
||||||
|
:param exclude:
|
||||||
|
:param kwargs:
|
||||||
|
:return: dict
|
||||||
|
"""
|
||||||
if exclude is None:
|
if exclude is None:
|
||||||
exclude = []
|
exclude = []
|
||||||
return {key: value for key, value in kwargs.items() if
|
return {key: value for key, value in kwargs.items() if
|
||||||
|
|
@ -14,13 +23,33 @@ def generate_payload(exclude=None, **kwargs):
|
||||||
and not key.startswith('_')}
|
and not key.startswith('_')}
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize(obj):
|
||||||
|
"""
|
||||||
|
Normalize dicts and lists
|
||||||
|
|
||||||
|
:param obj:
|
||||||
|
:return: normalized object
|
||||||
|
"""
|
||||||
|
if isinstance(obj, list):
|
||||||
|
return [_normalize(item) for item in obj]
|
||||||
|
elif isinstance(obj, dict):
|
||||||
|
return {k: _normalize(v) for k, v in obj.items() if v is not None}
|
||||||
|
elif hasattr(obj, 'to_python'):
|
||||||
|
return obj.to_python()
|
||||||
|
return obj
|
||||||
|
|
||||||
|
|
||||||
def prepare_arg(value):
|
def prepare_arg(value):
|
||||||
|
"""
|
||||||
|
Stringify dicts/lists and convert datetime/timedelta to unix-time
|
||||||
|
|
||||||
|
:param value:
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
if value is None:
|
if value is None:
|
||||||
return value
|
return value
|
||||||
elif isinstance(value, (list, dict)):
|
elif isinstance(value, (list, dict)) or hasattr(value, 'to_python'):
|
||||||
return json.dumps(value)
|
return json.dumps(_normalize(value))
|
||||||
elif hasattr(value, 'to_python'):
|
|
||||||
return json.dumps(value.to_python())
|
|
||||||
elif isinstance(value, datetime.timedelta):
|
elif isinstance(value, datetime.timedelta):
|
||||||
now = datetime.datetime.now()
|
now = datetime.datetime.now()
|
||||||
return int((now + value).timestamp())
|
return int((now + value).timestamp())
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue