ref: Add ruff rules for TRY2 and TRY002 (#4077)
Add ruff rules for TRY2 and TRY002
This commit is contained in:
parent
66be632086
commit
8ddab95ac4
34 changed files with 80 additions and 67 deletions
|
|
@ -365,9 +365,9 @@ async def build_flow(
|
|||
except Exception as e:
|
||||
if isinstance(e, HTTPException):
|
||||
event_manager.on_error(data={"error": str(e.detail), "statusCode": e.status_code})
|
||||
raise e
|
||||
raise
|
||||
event_manager.on_error(data={"error": str(e)})
|
||||
raise e
|
||||
raise
|
||||
|
||||
ids, vertices_to_run, graph = vertices_task.result()
|
||||
else:
|
||||
|
|
@ -376,9 +376,9 @@ async def build_flow(
|
|||
except Exception as e:
|
||||
if isinstance(e, HTTPException):
|
||||
event_manager.on_error(data={"error": str(e.detail), "statusCode": e.status_code})
|
||||
raise e
|
||||
raise
|
||||
event_manager.on_error(data={"error": str(e)})
|
||||
raise e
|
||||
raise
|
||||
event_manager.on_vertices_sorted(data={"ids": ids, "to_run": vertices_to_run})
|
||||
await client_consumed_queue.get()
|
||||
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ def create_flow(
|
|||
status_code=400, detail=f"{column.capitalize().replace('_', ' ')} must be unique"
|
||||
) from e
|
||||
if isinstance(e, HTTPException):
|
||||
raise e
|
||||
raise
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
|
|
@ -255,7 +255,7 @@ def update_flow(
|
|||
status_code=400, detail=f"{column.capitalize().replace('_', ' ')} must be unique"
|
||||
) from e
|
||||
if isinstance(e, HTTPException):
|
||||
raise e
|
||||
raise
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ async def login_to_get_access_token(
|
|||
user = authenticate_user(form_data.username, form_data.password, db)
|
||||
except Exception as exc:
|
||||
if isinstance(exc, HTTPException):
|
||||
raise exc
|
||||
raise
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(exc),
|
||||
|
|
|
|||
|
|
@ -102,8 +102,8 @@ async def update_message(
|
|||
session.commit()
|
||||
session.refresh(db_message)
|
||||
return db_message
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
|
@ -135,8 +135,8 @@ async def update_session_id(
|
|||
session.refresh(message)
|
||||
message_responses.append(MessageResponse.model_validate(message, from_attributes=True))
|
||||
return message_responses
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ def create_variable(
|
|||
)
|
||||
except Exception as e:
|
||||
if isinstance(e, HTTPException):
|
||||
raise e
|
||||
raise
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -86,7 +86,7 @@ class LCModelComponent(Component):
|
|||
except Exception as e:
|
||||
if message := self._get_exception_message(e):
|
||||
raise ValueError(message) from e
|
||||
raise e
|
||||
raise
|
||||
|
||||
def build_status_message(self, message: AIMessage):
|
||||
"""
|
||||
|
|
@ -198,7 +198,7 @@ class LCModelComponent(Component):
|
|||
except Exception as e:
|
||||
if message := self._get_exception_message(e):
|
||||
raise ValueError(message) from e
|
||||
raise e
|
||||
raise
|
||||
|
||||
@abstractmethod
|
||||
def build_model(self) -> LanguageModel: # type: ignore[type-var]
|
||||
|
|
|
|||
|
|
@ -26,5 +26,5 @@ class GetEnvVar(Component):
|
|||
def process_inputs(self) -> Message:
|
||||
if self.env_var_name not in os.environ:
|
||||
msg = f"Environment variable {self.env_var_name} not set"
|
||||
raise Exception(msg)
|
||||
raise ValueError(msg)
|
||||
return Message(text=os.environ[self.env_var_name])
|
||||
|
|
|
|||
|
|
@ -12,6 +12,10 @@ from langflow.schema.message import Message
|
|||
from langflow.template import Output
|
||||
|
||||
|
||||
class AssistantsRunError(Exception):
|
||||
"""Error running assistant"""
|
||||
|
||||
|
||||
class AssistantsRun(ComponentWithCache):
|
||||
display_name = "Run Assistant"
|
||||
description = "Executes an Assistant Run against a thread"
|
||||
|
|
@ -96,4 +100,4 @@ class AssistantsRun(ComponentWithCache):
|
|||
except Exception as e:
|
||||
print(e)
|
||||
msg = f"Error running assistant: {e}"
|
||||
raise Exception(msg) from e
|
||||
raise AssistantsRunError(msg) from e
|
||||
|
|
|
|||
|
|
@ -156,7 +156,7 @@ class GmailLoaderComponent(Component):
|
|||
yield self._get_message_data(service, message)
|
||||
except Exception as e:
|
||||
if self.raise_error:
|
||||
raise e
|
||||
raise
|
||||
else:
|
||||
print(f"Error processing message {message['id']}: {e}")
|
||||
|
||||
|
|
|
|||
|
|
@ -136,10 +136,10 @@ class ChatLiteLLMModelComponent(LCModelComponent):
|
|||
if self.provider == "Azure":
|
||||
if "api_base" not in self.kwargs:
|
||||
msg = "Missing api_base on kwargs"
|
||||
raise Exception(msg)
|
||||
raise ValueError(msg)
|
||||
if "api_version" not in self.model_kwargs:
|
||||
msg = "Missing api_version on model_kwargs"
|
||||
raise Exception(msg)
|
||||
raise ValueError(msg)
|
||||
output = ChatLiteLLM(
|
||||
model=f"{self.provider.lower()}/{self.model}",
|
||||
client=None,
|
||||
|
|
|
|||
|
|
@ -89,6 +89,6 @@ class MergeDataComponent(Component):
|
|||
logger.info("Data merging process completed successfully.")
|
||||
return merged_data_list
|
||||
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
logger.exception("An error occurred during the data merging process.")
|
||||
raise e
|
||||
raise
|
||||
|
|
|
|||
|
|
@ -89,6 +89,6 @@ class MergeDataComponent(Component):
|
|||
logger.info("Data merging process completed successfully.")
|
||||
return merged_data_list
|
||||
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
logger.exception("An error occurred during the data merging process.")
|
||||
raise e
|
||||
raise
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ from langflow.io import BoolInput, DictInput, DropdownInput, IntInput, Output, S
|
|||
from langflow.schema import Data
|
||||
|
||||
|
||||
class SpiderToolError(Exception):
|
||||
"""SpiderTool error"""
|
||||
|
||||
|
||||
class SpiderTool(Component):
|
||||
display_name: str = "Spider Web Crawler & Scraper"
|
||||
description: str = "Spider API for web crawling and scraping."
|
||||
|
|
@ -114,7 +118,7 @@ class SpiderTool(Component):
|
|||
raise ValueError(msg)
|
||||
except Exception as e:
|
||||
msg = f"Error: {e}"
|
||||
raise Exception(msg) from e
|
||||
raise SpiderToolError(msg) from e
|
||||
|
||||
records = []
|
||||
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@ class SQLExecutorComponent(CustomComponent):
|
|||
result = str(e)
|
||||
self.status = result
|
||||
if not passthrough:
|
||||
raise e
|
||||
raise
|
||||
error = repr(e)
|
||||
|
||||
if add_error and error is not None:
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ class VectaraSelfQueryRetriverComponent(CustomComponent):
|
|||
meta_obj = json.loads(meta)
|
||||
if "name" not in meta_obj or "description" not in meta_obj or "type" not in meta_obj:
|
||||
msg = "Incorrect metadata field info format."
|
||||
raise Exception(msg)
|
||||
raise ValueError(msg)
|
||||
attribute_info = AttributeInfo(
|
||||
name=meta_obj["name"],
|
||||
description=meta_obj["description"],
|
||||
|
|
|
|||
|
|
@ -178,7 +178,7 @@ class PythonCodeStructuredTool(LCToolComponent):
|
|||
func_arg = self._find_arg(named_functions, func_name, field_name)
|
||||
if func_arg is None:
|
||||
msg = f"Failed to find arg: {field_name}"
|
||||
raise Exception(msg)
|
||||
raise ValueError(msg)
|
||||
|
||||
field_annotation = func_arg["annotation"]
|
||||
field_description = self._get_value(self._attributes[attr], str)
|
||||
|
|
@ -251,7 +251,7 @@ class PythonCodeStructuredTool(LCToolComponent):
|
|||
for arg in node.args.args:
|
||||
if arg.lineno != arg.end_lineno:
|
||||
msg = "Multiline arguments are not supported"
|
||||
raise Exception(msg)
|
||||
raise ValueError(msg)
|
||||
|
||||
func_arg = {
|
||||
"name": arg.arg,
|
||||
|
|
|
|||
|
|
@ -235,7 +235,7 @@ class CassandraVectorStoreComponent(LCVectorStoreComponent):
|
|||
"Your collection does not contain a field name 'content'."
|
||||
)
|
||||
raise ValueError(msg) from e
|
||||
raise e
|
||||
raise
|
||||
|
||||
logger.debug(f"Retrieved documents: {len(docs)}")
|
||||
|
||||
|
|
|
|||
|
|
@ -214,7 +214,7 @@ class CassandraGraphVectorStoreComponent(LCVectorStoreComponent):
|
|||
"Your collection does not contain a field name 'content'."
|
||||
)
|
||||
raise ValueError(msg) from e
|
||||
raise e
|
||||
raise
|
||||
|
||||
logger.debug(f"Retrieved documents: {len(docs)}")
|
||||
|
||||
|
|
|
|||
|
|
@ -320,10 +320,10 @@ class CodeParser:
|
|||
"""
|
||||
try:
|
||||
bases = self.execute_and_inspect_classes(self.code)
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
# If the code cannot be executed, return an empty list
|
||||
bases = []
|
||||
raise e
|
||||
raise
|
||||
return bases
|
||||
|
||||
def parse_classes(self, node: ast.ClassDef) -> None:
|
||||
|
|
|
|||
|
|
@ -286,7 +286,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI
|
|||
if hasattr(exc, "detail") and "traceback" in exc.detail:
|
||||
logger.error(exc.detail["traceback"])
|
||||
|
||||
raise exc
|
||||
raise
|
||||
|
||||
|
||||
def run_build_config(
|
||||
|
|
@ -334,7 +334,7 @@ def run_build_config(
|
|||
if hasattr(exc, "detail") and "traceback" in exc.detail:
|
||||
logger.error(exc.detail["traceback"])
|
||||
|
||||
raise exc
|
||||
raise
|
||||
|
||||
|
||||
def add_code_field(frontend_node: CustomComponentFrontendNode, raw_code):
|
||||
|
|
@ -416,7 +416,7 @@ def build_custom_component_template(
|
|||
return frontend_node.to_dict(keep_name=False), custom_instance
|
||||
except Exception as exc:
|
||||
if isinstance(exc, HTTPException):
|
||||
raise exc
|
||||
raise
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ class Edge:
|
|||
"might not be a valid input."
|
||||
)
|
||||
raise ValueError(msg) from e
|
||||
raise e
|
||||
raise
|
||||
|
||||
else:
|
||||
msg = "Target handle is not a dictionary"
|
||||
|
|
|
|||
|
|
@ -216,7 +216,7 @@ def create_state_model(model_name: str = "State", validate: bool = True, **kwarg
|
|||
except ValueError as e:
|
||||
# If the method is not valid,assume it is already a getter
|
||||
if ("get_output_by_method" not in str(e) and "__self__" not in str(e)) or validate:
|
||||
raise e
|
||||
raise
|
||||
property_method = value
|
||||
fields[name] = computed_field(property_method)
|
||||
elif isinstance(value, FieldInfo):
|
||||
|
|
|
|||
|
|
@ -352,7 +352,7 @@ class Vertex:
|
|||
if "too many values to unpack" in str(e):
|
||||
full_path = file_path
|
||||
else:
|
||||
raise e
|
||||
raise
|
||||
params[field_name] = full_path
|
||||
elif field.get("required"):
|
||||
field_display_name = field.get("display_name")
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ def update_params_with_load_from_db_fields(
|
|||
except ValueError as e:
|
||||
# check if "User id is not set" is in the error message, this is an internal bug
|
||||
if "User id is not set" in str(e):
|
||||
raise e
|
||||
raise
|
||||
logger.debug(str(e))
|
||||
if fallback_to_env_vars and key is None:
|
||||
var = os.getenv(params[field])
|
||||
|
|
@ -134,8 +134,8 @@ def update_params_with_load_from_db_fields(
|
|||
|
||||
params[field] = key
|
||||
|
||||
except TypeError as exc:
|
||||
raise exc
|
||||
except TypeError:
|
||||
raise
|
||||
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception(f"Failed to get value for {field} from custom component. Setting it to None.")
|
||||
|
|
|
|||
|
|
@ -5,6 +5,10 @@ import httpx
|
|||
from langflow.services.database.models.flow.model import FlowBase
|
||||
|
||||
|
||||
class UploadError(Exception):
|
||||
"""Raised when an error occurs during the upload process."""
|
||||
|
||||
|
||||
def upload(file_path: str, host: str, flow_id: str):
|
||||
"""
|
||||
Upload a file to Langflow and return the file path.
|
||||
|
|
@ -26,11 +30,12 @@ def upload(file_path: str, host: str, flow_id: str):
|
|||
response = httpx.post(url, files={"file": file})
|
||||
if response.status_code in (httpx.codes.OK, httpx.codes.CREATED):
|
||||
return response.json()
|
||||
msg = f"Error uploading file: {response.status_code}"
|
||||
raise Exception(msg)
|
||||
except Exception as e:
|
||||
msg = f"Error uploading file: {e}"
|
||||
raise Exception(msg) from e
|
||||
raise UploadError(msg) from e
|
||||
else:
|
||||
msg = f"Error uploading file: {response.status_code}"
|
||||
raise UploadError(msg)
|
||||
|
||||
|
||||
def upload_file(file_path: str, host: str, flow_id: str, components: list[str], tweaks: dict | None = None):
|
||||
|
|
@ -63,11 +68,12 @@ def upload_file(file_path: str, host: str, flow_id: str, components: list[str],
|
|||
msg = f"Component ID or name must be a string. Got {type(component)}"
|
||||
raise TypeError(msg)
|
||||
return tweaks
|
||||
msg = "Error uploading file"
|
||||
raise ValueError(msg)
|
||||
except Exception as e:
|
||||
msg = f"Error uploading file: {e}"
|
||||
raise ValueError(msg) from e
|
||||
raise UploadError(msg) from e
|
||||
else:
|
||||
msg = "Error uploading file"
|
||||
raise UploadError(msg)
|
||||
|
||||
|
||||
def get_flow(url: str, flow_id: str):
|
||||
|
|
@ -90,8 +96,9 @@ def get_flow(url: str, flow_id: str):
|
|||
if response.status_code == httpx.codes.OK:
|
||||
json_response = response.json()
|
||||
return FlowBase(**json_response).model_dump()
|
||||
msg = f"Error retrieving flow: {response.status_code}"
|
||||
raise Exception(msg)
|
||||
except Exception as e:
|
||||
msg = f"Error retrieving flow: {e}"
|
||||
raise Exception(msg) from e
|
||||
raise UploadError(msg) from e
|
||||
else:
|
||||
msg = f"Error retrieving flow: {response.status_code}"
|
||||
raise UploadError(msg)
|
||||
|
|
|
|||
|
|
@ -77,7 +77,7 @@ class JavaScriptMIMETypeMiddleware(BaseHTTPMiddleware):
|
|||
)
|
||||
error_messages = json.dumps([message, str(exc)])
|
||||
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=error_messages) from exc
|
||||
raise exc
|
||||
raise
|
||||
if (
|
||||
"files/" not in request.url.path
|
||||
and request.url.path.endswith(".js")
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ def add_messages(messages: Message | list[Message], flow_id: str | None = None):
|
|||
return [Message(**message.model_dump()) for message in messages_models]
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
raise e
|
||||
raise
|
||||
|
||||
|
||||
def add_messagetables(messages: list[MessageTable], session: Session):
|
||||
|
|
@ -83,7 +83,7 @@ def add_messagetables(messages: list[MessageTable], session: Session):
|
|||
session.refresh(message)
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
raise e
|
||||
raise
|
||||
return [MessageRead.model_validate(message, from_attributes=True) for message in messages]
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -24,6 +24,6 @@ def log_transaction(db: Session, transaction: TransactionBase) -> TransactionTab
|
|||
try:
|
||||
db.commit()
|
||||
return table
|
||||
except IntegrityError as e:
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise e
|
||||
raise
|
||||
|
|
|
|||
|
|
@ -24,9 +24,9 @@ def log_vertex_build(db: Session, vertex_build: VertexBuildBase) -> VertexBuildT
|
|||
try:
|
||||
db.commit()
|
||||
return table
|
||||
except IntegrityError as e:
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise e
|
||||
raise
|
||||
|
||||
|
||||
def delete_vertex_builds_by_flow_id(db: Session, flow_id: UUID) -> None:
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ def initialize_database(fix_migration: bool = False):
|
|||
if "overlaps with other requested revisions" not in str(
|
||||
exc
|
||||
) and "Can't locate revision identified by" not in str(exc):
|
||||
raise exc
|
||||
raise
|
||||
# This means there's wrong revision in the DB
|
||||
# We need to delete the alembic_version table
|
||||
# and run the migrations again
|
||||
|
|
|
|||
|
|
@ -133,8 +133,8 @@ class StoreService(Service):
|
|||
try:
|
||||
response = await client.get(url, headers=headers, params=params, timeout=self.timeout)
|
||||
response.raise_for_status()
|
||||
except HTTPError as exc:
|
||||
raise exc
|
||||
except HTTPError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
msg = f"GET failed: {exc}"
|
||||
raise ValueError(msg) from exc
|
||||
|
|
@ -159,8 +159,8 @@ class StoreService(Service):
|
|||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except HTTPError as exc:
|
||||
raise exc
|
||||
except HTTPError:
|
||||
raise
|
||||
except Exception: # noqa: BLE001
|
||||
logger.opt(exception=True).debug("Webhook failed")
|
||||
|
||||
|
|
|
|||
|
|
@ -225,7 +225,7 @@ class TracingService(Service):
|
|||
yield self
|
||||
except Exception as e:
|
||||
self._end_traces(trace_id, trace_name, e)
|
||||
raise e
|
||||
raise
|
||||
finally:
|
||||
asyncio.create_task(await asyncio.to_thread(self._end_and_reset, trace_id, trace_name, None))
|
||||
|
||||
|
|
|
|||
|
|
@ -166,8 +166,8 @@ def initialize_services(fix_migration: bool = False, socketio_server=None):
|
|||
# Setup the superuser
|
||||
try:
|
||||
initialize_database(fix_migration=fix_migration)
|
||||
except Exception as exc:
|
||||
raise exc
|
||||
except Exception:
|
||||
raise
|
||||
setup_superuser(get_service(ServiceType.SETTINGS_SERVICE), next(get_session()))
|
||||
try:
|
||||
get_db_service().migrate_flows_if_auto_login()
|
||||
|
|
|
|||
|
|
@ -65,8 +65,6 @@ ignore = [
|
|||
"S",
|
||||
"SLF",
|
||||
"T201",
|
||||
"TRY002",
|
||||
"TRY2",
|
||||
"TRY3",
|
||||
]
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue