mirror of
https://github.com/NovaOSS/nova-api.git
synced 2024-11-25 23:13:57 +01:00
Refactor file operations
This commit is contained in:
parent
21331874db
commit
c5ad22c45b
|
@ -1,6 +1,8 @@
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import aiofiles
|
||||||
|
import aiofiles.os
|
||||||
|
|
||||||
from sys import argv
|
from sys import argv
|
||||||
from bson import json_util
|
from bson import json_util
|
||||||
|
@ -18,8 +20,7 @@ async def main(output_dir: str):
|
||||||
async def make_backup(output_dir: str):
|
async def make_backup(output_dir: str):
|
||||||
output_dir = os.path.join(FILE_DIR, '..', 'backups', output_dir)
|
output_dir = os.path.join(FILE_DIR, '..', 'backups', output_dir)
|
||||||
|
|
||||||
if not os.path.exists(output_dir):
|
await aiofiles.os.makedirs(output_dir, exist_ok=True)
|
||||||
os.makedirs(output_dir)
|
|
||||||
|
|
||||||
client = AsyncIOMotorClient(MONGO_URI)
|
client = AsyncIOMotorClient(MONGO_URI)
|
||||||
databases = await client.list_database_names()
|
databases = await client.list_database_names()
|
||||||
|
@ -29,22 +30,22 @@ async def make_backup(output_dir: str):
|
||||||
if database == 'local':
|
if database == 'local':
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if not os.path.exists(f'{output_dir}/{database}'):
|
await aiofiles.os.makedirs(os.path.join(output_dir, database), exist_ok=True)
|
||||||
os.mkdir(f'{output_dir}/{database}')
|
|
||||||
|
|
||||||
for collection in databases[database]:
|
for collection in databases[database]:
|
||||||
print(f'Initiated database backup for {database}/{collection}')
|
print(f'Initiated database backup for {database}/{collection}')
|
||||||
await make_backup_for_collection(database, collection, output_dir)
|
await make_backup_for_collection(database, collection, output_dir)
|
||||||
|
|
||||||
async def make_backup_for_collection(database, collection, output_dir):
|
async def make_backup_for_collection(database, collection, output_dir):
|
||||||
path = f'{output_dir}/{database}/{collection}.json'
|
path = os.path.join(output_dir, database, f'{collection}.json')
|
||||||
|
|
||||||
client = AsyncIOMotorClient(MONGO_URI)
|
client = AsyncIOMotorClient(MONGO_URI)
|
||||||
collection = client[database][collection]
|
collection = client[database][collection]
|
||||||
documents = await collection.find({}).to_list(length=None)
|
documents = await collection.find({}).to_list(length=None)
|
||||||
|
|
||||||
with open(path, 'w') as f:
|
async with aiofiles.open(path, 'w') as f:
|
||||||
json.dump(documents, f, default=json_util.default)
|
for chunk in json.JSONEncoder(default=json_util.default).iterencode(documents):
|
||||||
|
await f.write(chunk)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
if len(argv) < 2 or len(argv) > 2:
|
if len(argv) < 2 or len(argv) > 2:
|
||||||
|
|
16
api/core.py
16
api/core.py
|
@ -13,6 +13,7 @@ import json
|
||||||
import hmac
|
import hmac
|
||||||
import httpx
|
import httpx
|
||||||
import fastapi
|
import fastapi
|
||||||
|
import aiofiles
|
||||||
import functools
|
import functools
|
||||||
|
|
||||||
from dhooks import Webhook, Embed
|
from dhooks import Webhook, Embed
|
||||||
|
@ -148,11 +149,13 @@ async def run_checks(incoming_request: fastapi.Request):
|
||||||
async def get_crypto_price(cryptocurrency: str) -> float:
|
async def get_crypto_price(cryptocurrency: str) -> float:
|
||||||
"""Gets the price of a cryptocurrency using coinbase's API."""
|
"""Gets the price of a cryptocurrency using coinbase's API."""
|
||||||
|
|
||||||
if os.path.exists('cache/crypto_prices.json'):
|
try:
|
||||||
with open('cache/crypto_prices.json', 'r') as f:
|
async with aiofiles.open(os.path.join('cache', 'crypto_prices')) as f:
|
||||||
cache = json.load(f)
|
content = await f.read()
|
||||||
else:
|
except FileNotFoundError:
|
||||||
cache = {}
|
cache = {}
|
||||||
|
else:
|
||||||
|
cache = json.loads(content)
|
||||||
|
|
||||||
is_old = time.time() - cache.get('_last_updated', 0) > 60 * 60
|
is_old = time.time() - cache.get('_last_updated', 0) > 60 * 60
|
||||||
|
|
||||||
|
@ -164,8 +167,9 @@ async def get_crypto_price(cryptocurrency: str) -> float:
|
||||||
cache[cryptocurrency] = usd_price
|
cache[cryptocurrency] = usd_price
|
||||||
cache['_last_updated'] = time.time()
|
cache['_last_updated'] = time.time()
|
||||||
|
|
||||||
with open('cache/crypto_prices.json', 'w') as f:
|
async with aiofiles.open(os.path.join('cache', 'crypto_prices.json'), 'w') as f:
|
||||||
json.dump(cache, f)
|
for chunk in json.JSONEncoder().iterencode(cache):
|
||||||
|
await f.write(chunk)
|
||||||
|
|
||||||
return cache[cryptocurrency]
|
return cache[cryptocurrency]
|
||||||
|
|
||||||
|
|
|
@ -2,6 +2,8 @@ import os
|
||||||
import time
|
import time
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
|
import aiofiles
|
||||||
|
import aiofiles.os
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from motor.motor_asyncio import AsyncIOMotorClient
|
from motor.motor_asyncio import AsyncIOMotorClient
|
||||||
|
|
||||||
|
@ -60,10 +62,10 @@ class KeyManager:
|
||||||
db = await self._get_collection('providerkeys')
|
db = await self._get_collection('providerkeys')
|
||||||
num = 0
|
num = 0
|
||||||
|
|
||||||
for filename in os.listdir('api/secret'):
|
for filename in await aiofiles.os.listdir(os.path.join('api', 'secret')):
|
||||||
if filename.endswith('.txt'):
|
if filename.endswith('.txt'):
|
||||||
with open(f'api/secret/{filename}') as f:
|
async with aiofiles.open(os.path.join('api', 'secret', 'filename')) as f:
|
||||||
for line in f.readlines():
|
for line in await f.readlines():
|
||||||
if not line.strip():
|
if not line.strip():
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
|
@ -14,7 +14,7 @@ except ImportError:
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
with open(helpers.root + '/api/config/config.yml', encoding='utf8') as f:
|
with open(os.path.join(helpers.root, 'api', 'config', 'config.yml', encoding='utf8')) as f:
|
||||||
credits_config = yaml.safe_load(f)
|
credits_config = yaml.safe_load(f)
|
||||||
|
|
||||||
## MONGODB Setup
|
## MONGODB Setup
|
||||||
|
|
|
@ -19,10 +19,11 @@ from helpers import tokens, errors, network
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
users = UserManager()
|
users = UserManager()
|
||||||
models_list = json.load(open('cache/models.json', encoding='utf8'))
|
with open(os.path.join('cache', 'models.json'), encoding='utf8') as f:
|
||||||
|
models_list = json.load(f)
|
||||||
models = [model['id'] for model in models_list['data']]
|
models = [model['id'] for model in models_list['data']]
|
||||||
|
|
||||||
with open('config/config.yml', encoding='utf8') as f:
|
with open(os.path.join('config', 'config.yml'), encoding='utf8') as f:
|
||||||
config = yaml.safe_load(f)
|
config = yaml.safe_load(f)
|
||||||
|
|
||||||
moderation_debug_key_key = os.getenv('MODERATION_DEBUG_KEY')
|
moderation_debug_key_key = os.getenv('MODERATION_DEBUG_KEY')
|
||||||
|
|
|
@ -16,9 +16,9 @@ try:
|
||||||
provider_name = sys.argv[1]
|
provider_name = sys.argv[1]
|
||||||
|
|
||||||
if provider_name == '--clear':
|
if provider_name == '--clear':
|
||||||
for file in os.listdir('secret/'):
|
for file in os.listdir('secret'):
|
||||||
if file.endswith('.txt'):
|
if file.endswith('.txt'):
|
||||||
remove_duplicate_keys(f'secret/{file}')
|
remove_duplicate_keys(os.path.join('secret', file))
|
||||||
|
|
||||||
exit()
|
exit()
|
||||||
|
|
||||||
|
|
|
@ -96,7 +96,7 @@ proxies_in_files = []
|
||||||
|
|
||||||
for proxy_type in ['http', 'socks4', 'socks5']:
|
for proxy_type in ['http', 'socks4', 'socks5']:
|
||||||
try:
|
try:
|
||||||
with open(f'secret/proxies/{proxy_type}.txt') as f:
|
with open(os.path.join('secret', 'proxies', f'{proxy_type}.txt')) as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
clean_line = line.split('#', 1)[0].strip()
|
clean_line = line.split('#', 1)[0].strip()
|
||||||
if clean_line:
|
if clean_line:
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
aiofiles==23.2.1
|
||||||
aiohttp==3.8.5
|
aiohttp==3.8.5
|
||||||
aiohttp_socks==0.8.0
|
aiohttp_socks==0.8.0
|
||||||
dhooks==1.1.4
|
dhooks==1.1.4
|
||||||
|
|
|
@ -51,7 +51,7 @@ async def update_roles():
|
||||||
def launch():
|
def launch():
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
||||||
with open('rewards/last_update.txt', 'w', encoding='utf8') as f:
|
with open(os.path.join('rewards', 'last_update.txt'), 'w', encoding='utf8') as f:
|
||||||
f.write(str(time.time()))
|
f.write(str(time.time()))
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
Loading…
Reference in a new issue