Skip to content

Commit

Permalink
Fix ruff rules in preview mode
Browse files Browse the repository at this point in the history
  • Loading branch information
cbornet committed Oct 7, 2024
1 parent a021009 commit 16de7e1
Show file tree
Hide file tree
Showing 76 changed files with 227 additions and 7,470 deletions.
8 changes: 4 additions & 4 deletions src/backend/base/langflow/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def set_var_for_macos_issue():
# we need to set this var is we are running on MacOS
# otherwise we get an error when running gunicorn

if platform.system() in ["Darwin"]:
if platform.system() == "Darwin":
import os

os.environ["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES"
Expand Down Expand Up @@ -202,7 +202,7 @@ def run(
return
process: Process | None = None
try:
if platform.system() in ["Windows"]:
if platform.system() == "Windows":
# Run using uvicorn on MacOS and Windows
# Windows doesn't support gunicorn
# MacOS requires an env variable to be set to use gunicorn
Expand Down Expand Up @@ -370,7 +370,7 @@ def run_langflow(host, port, log_level, options, app):
Run Langflow server on localhost
"""

if platform.system() in ["Windows"]:
if platform.system() == "Windows":
# Run using uvicorn on MacOS and Windows
# Windows doesn't support gunicorn
# MacOS requires an env variable to be set to use gunicorn
Expand Down Expand Up @@ -539,7 +539,7 @@ def api_key_banner(unmasked_api_key):
f"[bold blue]{unmasked_api_key.api_key}[/bold blue]\n\n"
"This is the only time the API key will be displayed. \n"
"Make sure to store it in a secure location. \n\n"
f"The API key has been copied to your clipboard. [bold]{['Ctrl','Cmd'][is_mac]} + V[/bold] to paste it.",
f"The API key has been copied to your clipboard. [bold]{['Ctrl', 'Cmd'][is_mac]} + V[/bold] to paste it.",
box=box.ROUNDED,
border_style="blue",
expand=False,
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
from langflow.api.log_router import log_router
from langflow.api.router import router

__all__ = ["router", "health_check_router", "log_router"]
__all__ = ["health_check_router", "log_router", "router"]
3 changes: 2 additions & 1 deletion src/backend/base/langflow/api/health_check_router.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import uuid
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, status
from loguru import logger
Expand Down Expand Up @@ -37,7 +38,7 @@ async def health():
# It's a reliable health check for a langflow instance
@health_check_router.get("/health_check", response_model=HealthResponse)
async def health_check(
session: Session = Depends(get_session),
session: Annotated[Session, Depends(get_session)],
):
response = HealthResponse()
# use a fixed valid UUId that UUID collision is very unlikely
Expand Down
10 changes: 5 additions & 5 deletions src/backend/base/langflow/api/log_router.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio
import json
from http import HTTPStatus
from typing import Any
from typing import Annotated, Any

from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import JSONResponse, StreamingResponse
Expand Down Expand Up @@ -38,7 +38,7 @@ async def event_generator(request: Request):
last_read_item = item
if to_write:
for ts, msg in to_write:
yield f"{json.dumps({ts:msg})}\n\n"
yield f"{json.dumps({ts: msg})}\n\n"
else:
current_not_sent += 1
if current_not_sent == 5:
Expand Down Expand Up @@ -69,9 +69,9 @@ async def stream_logs(

@log_router.get("/logs")
async def logs(
lines_before: int = Query(0, description="The number of logs before the timestamp or the last log"),
lines_after: int = Query(0, description="The number of logs after the timestamp"),
timestamp: int = Query(0, description="The timestamp to start getting logs from"),
lines_before: Annotated[int, Query(0, description="The number of logs before the timestamp or the last log")],
lines_after: Annotated[int, Query(0, description="The number of logs after the timestamp")],
timestamp: Annotated[int, Query(0, description="The timestamp to start getting logs from")],
):
global log_buffer
if log_buffer.enabled() is False:
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def build_input_keys_response(langchain_object, artifacts):
"""Build the input keys response."""

input_keys_response = {
"input_keys": {key: "" for key in langchain_object.input_keys},
"input_keys": dict.fromkeys(langchain_object.input_keys, ""),
"memory_keys": [],
"handle_keys": artifacts.get("handle_keys", []),
}
Expand Down
14 changes: 7 additions & 7 deletions src/backend/base/langflow/api/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@
from langflow.api.v1.variable import router as variables_router

__all__ = [
"api_key_router",
"chat_router",
"endpoints_router",
"store_router",
"validate_router",
"files_router",
"flows_router",
"users_router",
"api_key_router",
"folders_router",
"login_router",
"variables_router",
"monitor_router",
"files_router",
"folders_router",
"starter_projects_router",
"store_router",
"users_router",
"validate_router",
"variables_router",
]
18 changes: 9 additions & 9 deletions src/backend/base/langflow/api/v1/api_key.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Annotated
from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, Response
Expand All @@ -21,8 +21,8 @@

@router.get("/", response_model=ApiKeysResponse)
def get_api_keys_route(
db: Session = Depends(get_session),
current_user: User = Depends(auth_utils.get_current_active_user),
db: Annotated[Session, Depends(get_session)],
current_user: Annotated[User, Depends(auth_utils.get_current_active_user)],
):
try:
user_id = current_user.id
Expand All @@ -36,8 +36,8 @@ def get_api_keys_route(
@router.post("/", response_model=UnmaskedApiKeyRead)
def create_api_key_route(
req: ApiKeyCreate,
current_user: User = Depends(auth_utils.get_current_active_user),
db: Session = Depends(get_session),
current_user: Annotated[User, Depends(auth_utils.get_current_active_user)],
db: Annotated[Session, Depends(get_session)],
):
try:
user_id = current_user.id
Expand All @@ -63,8 +63,8 @@ def delete_api_key_route(
def save_store_api_key(
api_key_request: ApiKeyCreateRequest,
response: Response,
current_user: User = Depends(auth_utils.get_current_active_user),
db: Session = Depends(get_session),
current_user: Annotated[User, Depends(auth_utils.get_current_active_user)],
db: Annotated[Session, Depends(get_session)],
settings_service=Depends(get_settings_service),
):
auth_settings = settings_service.auth_settings
Expand Down Expand Up @@ -95,8 +95,8 @@ def save_store_api_key(

@router.delete("/store")
def delete_store_api_key(
current_user: User = Depends(auth_utils.get_current_active_user),
db: Session = Depends(get_session),
current_user: Annotated[User, Depends(auth_utils.get_current_active_user)],
db: Annotated[Session, Depends(get_session)],
):
try:
current_user.store_api_key = None
Expand Down
13 changes: 6 additions & 7 deletions src/backend/base/langflow/api/v1/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ async def simple_run_flow_task(
logger.exception(f"Error running flow {flow.id} task")


@router.post("/run/{flow_id_or_name}", response_model=RunResponse, response_model_exclude_none=True)
@router.post("/run/{flow_id_or_name}", response_model=RunResponse, response_model_exclude_none=True) # noqa: RUF100, FAST003
async def simplified_run_flow(
background_tasks: BackgroundTasks,
flow: Annotated[FlowRead | None, Depends(get_flow_by_id_or_endpoint_name)],
Expand Down Expand Up @@ -296,13 +296,13 @@ async def simplified_run_flow(
raise APIException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=exc, flow=flow) from exc


@router.post("/webhook/{flow_id_or_name}", response_model=dict, status_code=HTTPStatus.ACCEPTED)
@router.post("/webhook/{flow_id_or_name}", response_model=dict, status_code=HTTPStatus.ACCEPTED) # noqa: RUF100, FAST003
async def webhook_run_flow(
flow: Annotated[Flow, Depends(get_flow_by_id_or_endpoint_name)],
user: Annotated[User, Depends(get_user_by_flow_id_or_endpoint_name)],
request: Request,
background_tasks: BackgroundTasks,
telemetry_service: TelemetryService = Depends(get_telemetry_service),
telemetry_service: Annotated[TelemetryService, Depends(get_telemetry_service)],
):
"""
Run a flow using a webhook request.
Expand Down Expand Up @@ -441,10 +441,9 @@ async def experimental_run_flow(
if inputs is None:
inputs = [InputValueRequest(components=[], input_value="")]

artifacts = {}
if session_id:
session_data = await session_service.load_session(session_id, flow_id=flow_id_str)
graph, artifacts = session_data if session_data else (None, None)
graph, _artifacts = session_data or (None, None)
if graph is None:
msg = f"Session {session_id} not found"
raise ValueError(msg)
Expand Down Expand Up @@ -585,7 +584,7 @@ def get_version():
@router.post("/custom_component", status_code=HTTPStatus.OK, response_model=CustomComponentResponse)
async def custom_component(
raw_code: CustomComponentRequest,
user: User = Depends(get_current_active_user),
user: Annotated[User, Depends(get_current_active_user)],
):
component = Component(_code=raw_code.code)

Expand All @@ -600,7 +599,7 @@ async def custom_component(
@router.post("/custom_component/update", status_code=HTTPStatus.OK)
async def custom_component_update(
code_request: UpdateCustomComponentRequest,
user: User = Depends(get_current_active_user),
user: Annotated[User, Depends(get_current_active_user)],
):
"""
Update a custom component with the provided code request.
Expand Down
22 changes: 15 additions & 7 deletions src/backend/base/langflow/api/v1/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from http import HTTPStatus
from io import BytesIO
from pathlib import Path
from typing import Annotated
from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, UploadFile
Expand Down Expand Up @@ -39,7 +40,7 @@ def get_flow_id(
@router.post("/upload/{flow_id}", status_code=HTTPStatus.CREATED)
async def upload_file(
file: UploadFile,
flow_id: UUID = Depends(get_flow_id),
flow_id: Annotated[UUID, Depends(get_flow_id)],
current_user=Depends(get_current_active_user),
session=Depends(get_session),
storage_service: StorageService = Depends(get_storage_service),
Expand Down Expand Up @@ -68,7 +69,9 @@ async def upload_file(


@router.get("/download/{flow_id}/{file_name}")
async def download_file(file_name: str, flow_id: UUID, storage_service: StorageService = Depends(get_storage_service)):
async def download_file(
file_name: str, flow_id: UUID, storage_service: Annotated[StorageService, Depends(get_storage_service)]
):
try:
flow_id_str = str(flow_id)
extension = file_name.split(".")[-1]
Expand All @@ -93,7 +96,9 @@ async def download_file(file_name: str, flow_id: UUID, storage_service: StorageS


@router.get("/images/{flow_id}/{file_name}")
async def download_image(file_name: str, flow_id: UUID, storage_service: StorageService = Depends(get_storage_service)):
async def download_image(
file_name: str, flow_id: UUID, storage_service: Annotated[StorageService, Depends(get_storage_service)]
):
try:
extension = file_name.split(".")[-1]
flow_id_str = str(flow_id)
Expand All @@ -118,7 +123,7 @@ async def download_image(file_name: str, flow_id: UUID, storage_service: Storage
async def download_profile_picture(
folder_name: str,
file_name: str,
storage_service: StorageService = Depends(get_storage_service),
storage_service: Annotated[StorageService, Depends(get_storage_service)],
):
try:
extension = file_name.split(".")[-1]
Expand All @@ -134,7 +139,7 @@ async def download_profile_picture(


@router.get("/profile_pictures/list")
async def list_profile_pictures(storage_service: StorageService = Depends(get_storage_service)):
async def list_profile_pictures(storage_service: Annotated[StorageService, Depends(get_storage_service)]):
try:
config_dir = get_storage_service().settings_service.settings.config_dir
config_path = Path(config_dir) # type: ignore
Expand All @@ -156,7 +161,8 @@ async def list_profile_pictures(storage_service: StorageService = Depends(get_st

@router.get("/list/{flow_id}")
async def list_files(
flow_id: UUID = Depends(get_flow_id), storage_service: StorageService = Depends(get_storage_service)
flow_id: Annotated[UUID, Depends(get_flow_id)],
storage_service: Annotated[StorageService, Depends(get_storage_service)],
):
try:
flow_id_str = str(flow_id)
Expand All @@ -168,7 +174,9 @@ async def list_files(

@router.delete("/delete/{flow_id}/{file_name}")
async def delete_file(
file_name: str, flow_id: UUID = Depends(get_flow_id), storage_service: StorageService = Depends(get_storage_service)
file_name: str,
flow_id: Annotated[UUID, Depends(get_flow_id)],
storage_service: Annotated[StorageService, Depends(get_storage_service)],
):
try:
flow_id_str = str(flow_id)
Expand Down
9 changes: 6 additions & 3 deletions src/backend/base/langflow/api/v1/flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
import zipfile
from datetime import datetime, timezone
from typing import Annotated
from uuid import UUID

import orjson
Expand Down Expand Up @@ -326,7 +327,9 @@ async def upload_file(

@router.delete("/")
async def delete_multiple_flows(
flow_ids: list[UUID], user: User = Depends(get_current_active_user), db: Session = Depends(get_session)
flow_ids: list[UUID],
user: Annotated[User, Depends(get_current_active_user)],
db: Annotated[Session, Depends(get_session)],
):
"""
Delete multiple flows by their IDs.
Expand Down Expand Up @@ -362,8 +365,8 @@ async def delete_multiple_flows(
@router.post("/download/", status_code=200)
async def download_multiple_file(
flow_ids: list[UUID],
user: User = Depends(get_current_active_user),
db: Session = Depends(get_session),
user: Annotated[User, Depends(get_current_active_user)],
db: Annotated[Session, Depends(get_session)],
):
"""Download all flows as a zip file."""
flows = db.exec(select(Flow).where(and_(Flow.user_id == user.id, Flow.id.in_(flow_ids)))).all() # type: ignore
Expand Down
12 changes: 7 additions & 5 deletions src/backend/base/langflow/api/v1/login.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlmodel import Session
Expand All @@ -23,8 +25,8 @@
@router.post("/login", response_model=Token)
async def login_to_get_access_token(
response: Response,
form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_session),
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
db: Annotated[Session, Depends(get_session)],
# _: Session = Depends(get_current_active_user)
settings_service=Depends(get_settings_service),
variable_service: VariableService = Depends(get_variable_service),
Expand Down Expand Up @@ -82,7 +84,7 @@ async def login_to_get_access_token(

@router.get("/auto_login")
async def auto_login(
response: Response, db: Session = Depends(get_session), settings_service=Depends(get_settings_service)
response: Response, db: Annotated[Session, Depends(get_session)], settings_service=Depends(get_settings_service)
):
auth_settings = settings_service.auth_settings

Expand Down Expand Up @@ -129,8 +131,8 @@ async def auto_login(
async def refresh_token(
request: Request,
response: Response,
settings_service: SettingsService = Depends(get_settings_service),
db: Session = Depends(get_session),
settings_service: Annotated[SettingsService, Depends(get_settings_service)],
db: Annotated[Session, Depends(get_session)],
):
auth_settings = settings_service.auth_settings

Expand Down
Loading

0 comments on commit 16de7e1

Please sign in to comment.