Логирование использования токенов и мелкие доработки.
This commit is contained in:
parent
641b179cd0
commit
3aa4f7206d
@ -1,28 +1,19 @@
|
|||||||
from aiohttp import ClientSession
|
# HERE WE GO
|
||||||
from json import dumps, loads
|
# -------- RUS ---------
|
||||||
import asyncio
|
# ⚠️ Для тех, кто не понял ⚠️
|
||||||
|
# Именно здесь вы можете тыкать UserAPI.
|
||||||
from db import read, write
|
# Секция UserAPI - для вас.
|
||||||
|
#
|
||||||
|
# Если вы не находитесь на сервере (а вы не находитесь), вам нужно поменять url_prefix.
|
||||||
|
# Сделать формата 'https://vpc-api.del.pw' (если эта ссылка не устарела)
|
||||||
|
#
|
||||||
|
# Секция SystemAPI и call2api.py вам не нужен, но можете его изучить.
|
||||||
|
# Эта часть кода взаимодействует с SystemAPI, который недоступен.
|
||||||
|
# ----------------------
|
||||||
|
|
||||||
global url_prefix
|
global url_prefix
|
||||||
url_prefix = 'http://127.0.0.1:8010/'
|
url_prefix = 'http://127.0.0.1:8010/'
|
||||||
|
|
||||||
# async def call(api_url, data, pre=True, fix=True):
|
|
||||||
# url = (url_prefix + api_url) if pre else api_url
|
|
||||||
# async with ClientSession() as session:
|
|
||||||
# async with session.post(url, json=data) as response:
|
|
||||||
# text = await response.text()
|
|
||||||
# try:
|
|
||||||
# json = loads(text)
|
|
||||||
# if 'detail' in json:
|
|
||||||
# return json['detail']
|
|
||||||
# else:
|
|
||||||
# return json
|
|
||||||
# except:
|
|
||||||
# if fix:
|
|
||||||
# return text.replace('"', '')
|
|
||||||
# else:
|
|
||||||
# return text
|
|
||||||
from call2api import call
|
from call2api import call
|
||||||
|
|
||||||
#------------------------------------------------------------
|
#------------------------------------------------------------
|
||||||
@ -41,6 +32,24 @@ async def transfer_coins(username, user_token,
|
|||||||
data = {'username': username, 'user_token': user_token,
|
data = {'username': username, 'user_token': user_token,
|
||||||
'dst_username': dst_username, 'amount': amount}
|
'dst_username': dst_username, 'amount': amount}
|
||||||
return await call('api/transfer_coins/', data)
|
return await call('api/transfer_coins/', data)
|
||||||
|
|
||||||
|
async def get_stats(username, user_token):
|
||||||
|
data = {'username': username, 'user_token': user_token}
|
||||||
|
return await call('api/get_stats/', data)
|
||||||
|
|
||||||
|
async def create_invoice(username, user_token, amount=None):
|
||||||
|
data = {'username': username, 'user_token': user_token}
|
||||||
|
if amount:
|
||||||
|
data['amount'] = amount
|
||||||
|
return await call('api/create_invoice/', data)
|
||||||
|
|
||||||
|
async def delete_invoice(username, user_token, id):
|
||||||
|
data = {'username': username, 'user_token': user_token, 'id': id}
|
||||||
|
return await call('api/delete_invoice/', data)
|
||||||
|
|
||||||
|
async def get_invoice(username, user_token, id):
|
||||||
|
data = {'username': username, 'user_token': user_token, 'id': id}
|
||||||
|
return await call('api/get_invoice/', data)
|
||||||
#------------------------- END ------------------------------
|
#------------------------- END ------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
40
user_api/func.py
Normal file
40
user_api/func.py
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
import pytz
|
||||||
|
|
||||||
|
from db import user_token_in_db_func
|
||||||
|
|
||||||
|
moscow_tz = pytz.timezone('Europe/Moscow')
|
||||||
|
|
||||||
|
async def log(session, user_token, message):
|
||||||
|
user_token_db = await user_token_in_db_func(session, user_token)
|
||||||
|
log_message = f"{[datetime.now(moscow_tz).strftime('%Y-%m-%d %H:%M %Z')]} {message}"
|
||||||
|
user_token_db.logs = await append_line_with_limit(user_token_db.logs, log_message)
|
||||||
|
session.add(user_token_db)
|
||||||
|
await session.commit()
|
||||||
|
await session.refresh(user_token_db)
|
||||||
|
|
||||||
|
async def append_line_with_limit(text, new_line, max_lines = 5000) -> str:
|
||||||
|
"""
|
||||||
|
Append a new line to the text and maintain a maximum number of lines.
|
||||||
|
When exceeding the limit, the oldest line is removed.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The existing text
|
||||||
|
new_line: The line to append
|
||||||
|
max_lines: Maximum number of lines to keep
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Updated text with the new line appended
|
||||||
|
"""
|
||||||
|
# Split text into lines
|
||||||
|
lines = text.splitlines() if text else []
|
||||||
|
|
||||||
|
# Append the new line
|
||||||
|
lines.append(new_line)
|
||||||
|
|
||||||
|
# If we exceed the maximum lines, remove the oldest (first) line
|
||||||
|
if len(lines) > max_lines:
|
||||||
|
lines.pop(0)
|
||||||
|
|
||||||
|
# Join lines back together with newlines
|
||||||
|
return '\n'.join(lines)
|
||||||
@ -6,6 +6,7 @@ from statistics import median
|
|||||||
from db import *
|
from db import *
|
||||||
from call2api import check_user_token, user_in_db, transfer_coins, get_stats, create_invoice, delete_invoice, \
|
from call2api import check_user_token, user_in_db, transfer_coins, get_stats, create_invoice, delete_invoice, \
|
||||||
get_invoice
|
get_invoice
|
||||||
|
from func import log
|
||||||
|
|
||||||
|
|
||||||
#------------------------------------------------------------
|
#------------------------------------------------------------
|
||||||
@ -94,6 +95,7 @@ async def user_in_db_api(
|
|||||||
):
|
):
|
||||||
if not token_check(username, user_token):
|
if not token_check(username, user_token):
|
||||||
raise HTTPException(status_code=401, detail='Invalid username or token')
|
raise HTTPException(status_code=401, detail='Invalid username or token')
|
||||||
|
await log(session, user_token, f'/user_in_db')
|
||||||
return await user_in_db(token=SYSTEM_API_TOKEN, username=username)
|
return await user_in_db(token=SYSTEM_API_TOKEN, username=username)
|
||||||
|
|
||||||
@app.post('/api/transfer_coins/')
|
@app.post('/api/transfer_coins/')
|
||||||
@ -106,46 +108,55 @@ async def transfer_coins_api(
|
|||||||
):
|
):
|
||||||
if not token_check(username, user_token):
|
if not token_check(username, user_token):
|
||||||
raise HTTPException(status_code=401, detail='Invalid username or token')
|
raise HTTPException(status_code=401, detail='Invalid username or token')
|
||||||
|
await log(session, user_token, f'/transfer_coins: (dst_username: {dst_username}, amount: {amount})')
|
||||||
return await transfer_coins(token=SYSTEM_API_TOKEN, src_username=username
|
return await transfer_coins(token=SYSTEM_API_TOKEN, src_username=username
|
||||||
, dst_username=dst_username, amount=amount)
|
, dst_username=dst_username, amount=amount)
|
||||||
|
|
||||||
@app.post('/api/get_stats/')
|
@app.post('/api/get_stats/')
|
||||||
async def get_stats_api(
|
async def get_stats_api(
|
||||||
username: str = Body(),
|
username: str = Body(),
|
||||||
user_token: str = Body()
|
user_token: str = Body(),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
):
|
):
|
||||||
if not token_check(username, user_token):
|
if not token_check(username, user_token):
|
||||||
raise HTTPException(status_code=401, detail='Invalid username or token')
|
raise HTTPException(status_code=401, detail='Invalid username or token')
|
||||||
|
await log(session, user_token, f'/get_stats')
|
||||||
return await get_stats(token=SYSTEM_API_TOKEN)
|
return await get_stats(token=SYSTEM_API_TOKEN)
|
||||||
|
|
||||||
@app.post('/api/create_invoice/')
|
@app.post('/api/create_invoice/')
|
||||||
async def create_invoice_api(
|
async def create_invoice_api(
|
||||||
username: str = Body(),
|
username: str = Body(),
|
||||||
user_token: str = Body(),
|
user_token: str = Body(),
|
||||||
amount: float | None = Body(None)
|
amount: float | None = Body(None),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
):
|
):
|
||||||
if not token_check(username, user_token):
|
if not token_check(username, user_token):
|
||||||
raise HTTPException(status_code=401, detail='Invalid username or token')
|
raise HTTPException(status_code=401, detail='Invalid username or token')
|
||||||
|
await log(session, user_token, f'/create_invoice: (amount: {amount})')
|
||||||
return await create_invoice(token=SYSTEM_API_TOKEN, dst_username=username, amount=amount)
|
return await create_invoice(token=SYSTEM_API_TOKEN, dst_username=username, amount=amount)
|
||||||
|
|
||||||
@app.post('/api/delete_invoice/')
|
@app.post('/api/delete_invoice/')
|
||||||
async def delete_invoice_api(
|
async def delete_invoice_api(
|
||||||
username: str = Body(),
|
username: str = Body(),
|
||||||
user_token: str = Body(),
|
user_token: str = Body(),
|
||||||
id: str = Body()
|
id: str = Body(),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
):
|
):
|
||||||
if not token_check(username, user_token):
|
if not token_check(username, user_token):
|
||||||
raise HTTPException(status_code=401, detail='Invalid username or token')
|
raise HTTPException(status_code=401, detail='Invalid username or token')
|
||||||
|
await log(session, user_token, f'/delete_invoice: (id: {id})')
|
||||||
return await delete_invoice(token=SYSTEM_API_TOKEN, id=id)
|
return await delete_invoice(token=SYSTEM_API_TOKEN, id=id)
|
||||||
|
|
||||||
@app.post('/api/get_invoice/')
|
@app.post('/api/get_invoice/')
|
||||||
async def get_invoice_api(
|
async def get_invoice_api(
|
||||||
username: str = Body(),
|
username: str = Body(),
|
||||||
user_token: str = Body(),
|
user_token: str = Body(),
|
||||||
id: str = Body()
|
id: str = Body(),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
):
|
):
|
||||||
if not token_check(username, user_token):
|
if not token_check(username, user_token):
|
||||||
raise HTTPException(status_code=401, detail='Invalid username or token')
|
raise HTTPException(status_code=401, detail='Invalid username or token')
|
||||||
|
await log(session, user_token, f'/get_invoice: (id: {id})')
|
||||||
return await get_invoice(token=SYSTEM_API_TOKEN, id=id)
|
return await get_invoice(token=SYSTEM_API_TOKEN, id=id)
|
||||||
|
|
||||||
#------------------------- END ------------------------------
|
#------------------------- END ------------------------------
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user