[CHORE] flake8 issues E402, E721 and F821 (#1874)

* F821: undefine name
disabled and logged webhook_listener for opennode and lnpay because they are obviously not working
* E402: module level import not at top of file
* E721 fixes, only popped up for python3.9 not 3.10
This commit is contained in:
dni ⚡
2023-08-16 12:22:14 +02:00
committed by GitHub
parent 355806608b
commit f0a66e41fb
13 changed files with 108 additions and 112 deletions
+1 -1
View File
@@ -468,7 +468,7 @@ async def api_payments_sse(
async def api_payment(payment_hash, X_Api_Key: Optional[str] = Header(None)):
# We use X_Api_Key here because we want this call to work with and without keys
# If a valid key is given, we also return the field "details", otherwise not
wallet = await get_wallet_for_key(X_Api_Key) if type(X_Api_Key) == str else None # type: ignore
wallet = await get_wallet_for_key(X_Api_Key) if isinstance(X_Api_Key, str) else None # type: ignore
# we have to specify the wallet id here, because postgres and sqlite return internal payments in different order
# and get_standalone_payment otherwise just fetches the first one, causing unpredictable results
+1 -1
View File
@@ -462,7 +462,7 @@ class Filters(BaseModel, Generic[TFilterModel]):
if self.search and self.model:
if DB_TYPE == POSTGRES:
where_stmts.append(
f"lower(concat({f', '.join(self.model.__search_fields__)})) LIKE ?"
f"lower(concat({', '.join(self.model.__search_fields__)})) LIKE ?"
)
elif DB_TYPE == SQLITE:
where_stmts.append(
+4 -5
View File
@@ -1,17 +1,16 @@
import uvloop
from uvicorn.supervisors import ChangeReload
uvloop.install()
import multiprocessing as mp
import time
from pathlib import Path
import click
import uvicorn
import uvloop
from uvicorn.supervisors import ChangeReload
from lnbits.settings import set_cli_settings, settings
uvloop.install()
@click.command(
context_settings=dict(
+1 -1
View File
@@ -26,7 +26,7 @@ def list_parse_fallback(v):
class LNbitsSettings(BaseSettings):
@classmethod
def validate(cls, val):
if type(val) == str:
if isinstance(val, str):
val = val.split(",") if val else []
return val
+2 -2
View File
@@ -46,8 +46,8 @@ class SseListenersDict(dict):
self.name = name or f"sse_listener_{str(uuid.uuid4())[:8]}"
def __setitem__(self, key, value):
assert type(key) == str, f"{key} is not a string"
assert type(value) == asyncio.Queue, f"{value} is not an asyncio.Queue"
assert isinstance(key, str), f"{key} is not a string"
assert isinstance(value, asyncio.Queue), f"{value} is not an asyncio.Queue"
logger.trace(f"sse: adding listener {key} to {self.name}. len = {len(self)+1}")
return super().__setitem__(key, value)
+14 -15
View File
@@ -1,10 +1,3 @@
imports_ok = True
try:
import grpc
from grpc import RpcError
except ImportError: # pragma: nocover
imports_ok = False
import asyncio
import base64
import hashlib
@@ -13,14 +6,6 @@ from typing import AsyncGenerator, Dict, Optional
from loguru import logger
from .macaroon import AESCipher, load_macaroon
if imports_ok:
import lnbits.wallets.lnd_grpc_files.lightning_pb2 as ln
import lnbits.wallets.lnd_grpc_files.lightning_pb2_grpc as lnrpc
import lnbits.wallets.lnd_grpc_files.router_pb2 as router
import lnbits.wallets.lnd_grpc_files.router_pb2_grpc as routerrpc
from lnbits.settings import settings
from .base import (
@@ -30,6 +15,20 @@ from .base import (
StatusResponse,
Wallet,
)
from .macaroon import AESCipher, load_macaroon
imports_ok = True
try:
import grpc
from grpc import RpcError
except ImportError: # pragma: nocover
imports_ok = False
if imports_ok:
import lnbits.wallets.lnd_grpc_files.lightning_pb2 as ln
import lnbits.wallets.lnd_grpc_files.lightning_pb2_grpc as lnrpc
import lnbits.wallets.lnd_grpc_files.router_pb2 as router
import lnbits.wallets.lnd_grpc_files.router_pb2_grpc as routerrpc
def get_ssl_context(cert_path: str):
+21 -23
View File
@@ -1,11 +1,8 @@
import asyncio
import hashlib
import json
from http import HTTPStatus
from typing import AsyncGenerator, Dict, Optional
import httpx
from fastapi import HTTPException
from loguru import logger
from lnbits.settings import settings
@@ -65,7 +62,7 @@ class LNPayWallet(Wallet):
memo: Optional[str] = None,
description_hash: Optional[bytes] = None,
unhashed_description: Optional[bytes] = None,
**kwargs,
**_,
) -> InvoiceResponse:
data: Dict = {"num_satoshis": f"{amount}"}
if description_hash:
@@ -139,25 +136,26 @@ class LNPayWallet(Wallet):
yield value
async def webhook_listener(self):
logger.error("LNPay webhook listener disabled.")
return
# TODO: request.get_data is undefined, was it something with Flask or quart?
# probably issue introduced when refactoring?
text: str = await request.get_data() # type: ignore
try:
data = json.loads(text)
except json.decoder.JSONDecodeError:
logger.error(f"got something wrong on lnpay webhook endpoint: {text[:200]}")
data = None
if (
type(data) is not dict
or "event" not in data
or data["event"].get("name") != "wallet_receive"
):
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
# text: str = await request.get_data()
# try:
# data = json.loads(text)
# except json.decoder.JSONDecodeError:
# logger.error(f"error on lnpay webhook endpoint: {text[:200]}")
# data = None
# if (
# type(data) is not dict
# or "event" not in data
# or data["event"].get("name") != "wallet_receive"
# ):
# raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
lntx_id = data["data"]["wtx"]["lnTx"]["id"]
r = await self.client.get(f"/lntx/{lntx_id}?fields=settled")
data = r.json()
if data["settled"]:
await self.queue.put(lntx_id)
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
# lntx_id = data["data"]["wtx"]["lnTx"]["id"]
# r = await self.client.get(f"/lntx/{lntx_id}?fields=settled")
# data = r.json()
# if data["settled"]:
# await self.queue.put(lntx_id)
# raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
+1 -1
View File
@@ -52,7 +52,7 @@ class AESCipher:
return data + (chr(length) * length).encode()
def unpad(self, data):
return data[: -(data[-1] if type(data[-1]) == int else ord(data[-1]))]
return data[: -(data[-1] if isinstance(data[-1], int) else ord(data[-1]))]
@property
def passphrase(self):
+13 -14
View File
@@ -1,10 +1,7 @@
import asyncio
import hmac
from http import HTTPStatus
from typing import AsyncGenerator, Optional
import httpx
from fastapi import HTTPException
from loguru import logger
from lnbits.settings import settings
@@ -136,18 +133,20 @@ class OpenNodeWallet(Wallet):
yield value
async def webhook_listener(self):
logger.error("webhook listener for opennode is disabled.")
return
# TODO: request.form is undefined, was it something with Flask or quart?
# probably issue introduced when refactoring?
data = await request.form # type: ignore
if "status" not in data or data["status"] != "paid":
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
# data = await request.form # type: ignore
# if "status" not in data or data["status"] != "paid":
# raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
charge_id = data["id"]
x = hmac.new(self.auth["Authorization"].encode("ascii"), digestmod="sha256")
x.update(charge_id.encode("ascii"))
if x.hexdigest() != data["hashed_order"]:
logger.error("invalid webhook, not from opennode")
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
# charge_id = data["id"]
# x = hmac.new(self.auth["Authorization"].encode("ascii"), digestmod="sha256")
# x.update(charge_id.encode("ascii"))
# if x.hexdigest() != data["hashed_order"]:
# logger.error("invalid webhook, not from opennode")
# raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
await self.queue.put(charge_id)
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
# await self.queue.put(charge_id)
# raise HTTPException(status_code=HTTPStatus.NO_CONTENT)