Skip to content

Commit

Permalink
Add ruff rules for return (RET)
Browse files Browse the repository at this point in the history
  • Loading branch information
cbornet committed Oct 1, 2024
1 parent d19c164 commit e4313e6
Show file tree
Hide file tree
Showing 157 changed files with 439 additions and 653 deletions.
5 changes: 2 additions & 3 deletions src/backend/base/langflow/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def run_on_windows(host, port, log_level, options, app):
"""
print_banner(host, port)
run_langflow(host, port, log_level, options, app)
return None
return


def is_port_in_use(port, host="localhost"):
Expand Down Expand Up @@ -296,8 +296,7 @@ def generate_pip_command(package_names, is_pre_release):
base_command = "pip install"
if is_pre_release:
return f"{base_command} {' '.join(package_names)} -U --pre"
else:
return f"{base_command} {' '.join(package_names)} -U"
return f"{base_command} {' '.join(package_names)} -U"


def stylize_text(text: str, to_style: str, is_prerelease: bool) -> str:
Expand Down
5 changes: 2 additions & 3 deletions src/backend/base/langflow/api/health_check_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,5 @@ async def health_check(

if response.has_error():
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=response.model_dump())
else:
response.status = "ok"
return response
response.status = "ok"
return response
35 changes: 16 additions & 19 deletions src/backend/base/langflow/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ async def check_langflow_version(component: StoreComponentCreate):
langflow_version = get_lf_version_from_pypi()
if langflow_version is None:
raise HTTPException(status_code=500, detail="Unable to verify the latest version of Langflow")
elif langflow_version != component.last_tested_version:
if langflow_version != component.last_tested_version:
warnings.warn(
f"Your version of Langflow ({component.last_tested_version}) is outdated. "
f"Please update to the latest version ({langflow_version}) and try again."
Expand All @@ -117,16 +117,15 @@ def format_elapsed_time(elapsed_time: float) -> str:
if elapsed_time < 1:
milliseconds = int(round(elapsed_time * 1000))
return f"{milliseconds} ms"
elif elapsed_time < 60:
if elapsed_time < 60:
seconds = round(elapsed_time, 2)
unit = "second" if seconds == 1 else "seconds"
return f"{seconds} {unit}"
else:
minutes = int(elapsed_time // 60)
seconds = round(elapsed_time % 60, 2)
minutes_unit = "minute" if minutes == 1 else "minutes"
seconds_unit = "second" if seconds == 1 else "seconds"
return f"{minutes} {minutes_unit}, {seconds} {seconds_unit}"
minutes = int(elapsed_time // 60)
seconds = round(elapsed_time % 60, 2)
minutes_unit = "minute" if minutes == 1 else "minutes"
seconds_unit = "second" if seconds == 1 else "seconds"
return f"{minutes} {minutes_unit}, {seconds} {seconds_unit}"


async def build_graph_from_data(flow_id: str, payload: dict, **kwargs):
Expand Down Expand Up @@ -229,29 +228,27 @@ def get_suggestion_message(outdated_components: list[str]) -> str:
count = len(outdated_components)
if count == 0:
return "The flow contains no outdated components."
elif count == 1:
if count == 1:
return (
"The flow contains 1 outdated component. "
f"We recommend updating the following component: {outdated_components[0]}."
)
else:
components = ", ".join(outdated_components)
return (
f"The flow contains {count} outdated components. "
f"We recommend updating the following components: {components}."
)
components = ", ".join(outdated_components)
return (
f"The flow contains {count} outdated components. "
f"We recommend updating the following components: {components}."
)


def parse_value(value: Any, input_type: str) -> Any:
"""Helper function to parse the value based on input type."""
if value == "":
return value
elif input_type == "IntInput":
if input_type == "IntInput":
return int(value) if value is not None else None
elif input_type == "FloatInput":
if input_type == "FloatInput":
return float(value) if value is not None else None
else:
return value
return value


async def cascade_delete_flow(session: Session, flow: Flow):
Expand Down
18 changes: 7 additions & 11 deletions src/backend/base/langflow/api/v1/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,10 @@ async def get_all(

try:
async with Lock() as lock:
all_types_dict = await get_and_cache_all_types_dict(
return await get_and_cache_all_types_dict(
settings_service=settings_service, cache_service=cache_service, force_refresh=force_refresh, lock=lock
)

return all_types_dict
except Exception as exc:
logger.exception(exc)
raise HTTPException(status_code=500, detail=str(exc)) from exc
Expand Down Expand Up @@ -164,13 +163,12 @@ async def simple_run_flow_task(
Run a flow task as a BackgroundTask, therefore it should not throw exceptions.
"""
try:
result = await simple_run_flow(
return await simple_run_flow(
flow=flow,
input_request=input_request,
stream=stream,
api_key_user=api_key_user,
)
return result

except Exception as exc:
logger.exception(f"Error running flow {flow.id} task: {exc}")
Expand Down Expand Up @@ -280,9 +278,8 @@ async def simplified_run_flow(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
if "not found" in str(exc):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
else:
logger.exception(exc)
raise APIException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=exc, flow=flow) from exc
logger.exception(exc)
raise APIException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=exc, flow=flow) from exc
except InvalidChatInputException as exc:
logger.error(exc)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
Expand Down Expand Up @@ -483,12 +480,11 @@ async def experimental_run_flow(
if f"Flow {flow_id_str} not found" in str(exc):
logger.error(f"Flow {flow_id_str} not found")
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
elif f"Session {session_id} not found" in str(exc):
if f"Session {session_id} not found" in str(exc):
logger.error(f"Session {session_id} not found")
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
else:
logger.exception(exc)
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)) from exc
logger.exception(exc)
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)) from exc
except Exception as exc:
logger.exception(exc)
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)) from exc
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/api/v1/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ async def download_image(file_name: str, flow_id: UUID, storage_service: Storage

if not content_type:
raise HTTPException(status_code=500, detail=f"Content type not found for extension {extension}")
elif not content_type.startswith("image"):
if not content_type.startswith("image"):
raise HTTPException(status_code=500, detail=f"Content type {content_type} is not an image")

file_content = await storage_service.get_file(flow_id=flow_id_str, file_name=file_name)
Expand Down
20 changes: 8 additions & 12 deletions src/backend/base/langflow/api/v1/flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def create_flow(
# If it is a validation error, return the error message
if hasattr(e, "errors"):
raise HTTPException(status_code=400, detail=str(e)) from e
elif "UNIQUE constraint failed" in str(e):
if "UNIQUE constraint failed" in str(e):
# Get the name of the column that failed
columns = str(e).split("UNIQUE constraint failed: ")[1].split(".")[1].split("\n")[0]
# UNIQUE constraint failed: flow.user_id, flow.name
Expand All @@ -113,10 +113,9 @@ def create_flow(
raise HTTPException(
status_code=400, detail=f"{column.capitalize().replace('_', ' ')} must be unique"
) from e
elif isinstance(e, HTTPException):
if isinstance(e, HTTPException):
raise e
else:
raise HTTPException(status_code=500, detail=str(e)) from e
raise HTTPException(status_code=500, detail=str(e)) from e


@router.get("/", response_model=list[FlowRead], status_code=200)
Expand Down Expand Up @@ -198,8 +197,7 @@ def read_flow(
) # noqa
if user_flow := session.exec(stmt).first():
return user_flow
else:
raise HTTPException(status_code=404, detail="Flow not found")
raise HTTPException(status_code=404, detail="Flow not found")


@router.patch("/{flow_id}", response_model=FlowRead, status_code=200)
Expand Down Expand Up @@ -242,7 +240,7 @@ def update_flow(
# If it is a validation error, return the error message
if hasattr(e, "errors"):
raise HTTPException(status_code=400, detail=str(e)) from e
elif "UNIQUE constraint failed" in str(e):
if "UNIQUE constraint failed" in str(e):
# Get the name of the column that failed
columns = str(e).split("UNIQUE constraint failed: ")[1].split(".")[1].split("\n")[0]
# UNIQUE constraint failed: flow.user_id, flow.name
Expand All @@ -253,10 +251,9 @@ def update_flow(
raise HTTPException(
status_code=400, detail=f"{column.capitalize().replace('_', ' ')} must be unique"
) from e
elif isinstance(e, HTTPException):
if isinstance(e, HTTPException):
raise e
else:
raise HTTPException(status_code=500, detail=str(e)) from e
raise HTTPException(status_code=500, detail=str(e)) from e


@router.delete("/{flow_id}", status_code=200)
Expand Down Expand Up @@ -402,5 +399,4 @@ async def download_multiple_file(
media_type="application/x-zip-compressed",
headers={"Content-Disposition": f"attachment; filename={filename}"},
)
else:
return flows_without_api_keys[0]
return flows_without_api_keys[0]
6 changes: 2 additions & 4 deletions src/backend/base/langflow/api/v1/folders.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ def read_folders(
or_(Folder.user_id == current_user.id, Folder.user_id == None) # type: ignore # noqa: E711
)
).all()
sorted_folders = sorted(folders, key=lambda x: x.name != DEFAULT_FOLDER_NAME)
return sorted_folders
return sorted(folders, key=lambda x: x.name != DEFAULT_FOLDER_NAME)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

Expand Down Expand Up @@ -204,8 +203,7 @@ async def download_file(
):
"""Download all flows from folder."""
try:
folder = session.exec(select(Folder).where(Folder.id == folder_id, Folder.user_id == current_user.id)).first()
return folder
return session.exec(select(Folder).where(Folder.id == folder_id, Folder.user_id == current_user.id)).first()
except Exception as e:
if "No result found" in str(e):
raise HTTPException(status_code=404, detail="Folder not found")
Expand Down
22 changes: 10 additions & 12 deletions src/backend/base/langflow/api/v1/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,11 @@ async def login_to_get_access_token(
# Create default folder for user if it doesn't exist
create_default_folder_if_it_doesnt_exist(db, user.id)
return tokens
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)


@router.get("/auto_login")
Expand Down Expand Up @@ -156,12 +155,11 @@ async def refresh_token(
domain=auth_settings.COOKIE_DOMAIN,
)
return tokens
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid refresh token",
headers={"WWW-Authenticate": "Bearer"},
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid refresh token",
headers={"WWW-Authenticate": "Bearer"},
)


@router.post("/logout")
Expand Down
3 changes: 1 addition & 2 deletions src/backend/base/langflow/api/v1/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,7 @@ class VertexBuildResponse(BaseModel):
@field_serializer("data")
def serialize_data(self, data: ResultDataResponse) -> dict:
data_dict = data.model_dump() if isinstance(data, BaseModel) else data
truncated_data = truncate_long_strings(data_dict)
return truncated_data
return truncate_long_strings(data_dict)


class VerticesBuiltResponse(BaseModel):
Expand Down
3 changes: 1 addition & 2 deletions src/backend/base/langflow/api/v1/starter_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ def get_starter_projects(
from langflow.initial_setup.load import get_starter_projects_dump

try:
flows = get_starter_projects_dump()
return flows
return get_starter_projects_dump()
except Exception as exc:
logger.error(exc)
raise HTTPException(status_code=500, detail=str(exc)) from exc
12 changes: 4 additions & 8 deletions src/backend/base/langflow/api/v1/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ def get_user_store_api_key(
if not user.store_api_key:
raise HTTPException(status_code=400, detail="You must have a store API key set.")
try:
decrypted = auth_utils.decrypt_api_key(user.store_api_key, settings_service)
return decrypted
return auth_utils.decrypt_api_key(user.store_api_key, settings_service)
except Exception as e:
raise HTTPException(status_code=500, detail="Failed to decrypt API key. Please set a new one.") from e

Expand All @@ -42,8 +41,7 @@ def get_optional_user_store_api_key(
if not user.store_api_key:
return None
try:
decrypted = auth_utils.decrypt_api_key(user.store_api_key, settings_service)
return decrypted
return auth_utils.decrypt_api_key(user.store_api_key, settings_service)
except Exception as e:
logger.error(f"Failed to decrypt API key: {e}")
return user.store_api_key
Expand Down Expand Up @@ -82,8 +80,7 @@ async def share_component(
):
try:
await check_langflow_version(component)
result = await store_service.upload(store_api_key, component)
return result
return await store_service.upload(store_api_key, component)
except Exception as exc:
raise HTTPException(status_code=400, detail=str(exc))

Expand All @@ -97,8 +94,7 @@ async def update_shared_component(
):
try:
await check_langflow_version(component)
result = await store_service.update(store_api_key, component_id, component)
return result
return await store_service.update(store_api_key, component_id, component)
except Exception as exc:
raise HTTPException(status_code=400, detail=str(exc))

Expand Down
5 changes: 2 additions & 3 deletions src/backend/base/langflow/api/v1/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,7 @@ def patch_user(
if not update_password:
user_update.password = user_db.password
return update_user(user_db, user_update, session)
else:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail="User not found")


@router.patch("/{user_id}/reset-password", response_model=UserRead)
Expand Down Expand Up @@ -146,7 +145,7 @@ def delete_user(
"""
if current_user.id == user_id:
raise HTTPException(status_code=400, detail="You can't delete your own user account")
elif not current_user.is_superuser:
if not current_user.is_superuser:
raise HTTPException(status_code=403, detail="Permission denied")

user_db = session.exec(select(User).where(User.id == user_id)).first()
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/base/agents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def _validate_outputs(self):
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
elif not hasattr(self, method_name):
if not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")

def get_agent_kwargs(self, flatten: bool = False) -> dict:
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/base/chains/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ def _validate_outputs(self):
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
elif not hasattr(self, method_name):
if not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")
Loading

0 comments on commit e4313e6

Please sign in to comment.