Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/change port #88

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion frontend/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ export default defineConfig({
},
server: {
proxy: {
"/api": "http://localhost:8501", // Forward API requests to FastAPI
"/api": {
target: `http://localhost:${process.env.PRESWALD_PORT || '8501'}`,
changeOrigin: true,
},
},
},
});
9 changes: 6 additions & 3 deletions preswald/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def init(name):

@cli.command()
@click.argument("script", default="hello.py")
@click.option("--port", default=8501, help="Port to run the server on.")
@click.option("--port", default=8501, help="Port to run the server on. Overrides port in config file if specified.")
@click.option(
"--log-level",
type=click.Choice(
Expand All @@ -82,7 +82,10 @@ def run(script, port, log_level):
"""
Run a Preswald app.

By default, it runs the `hello.py` script on localhost:8501.
Port priority:
1. --port argument (if provided)
2. port from preswald.toml (if exists)
3. default port 8501
"""
if not os.path.exists(script):
click.echo(f"Error: Script '{script}' not found. ❌")
Expand Down Expand Up @@ -160,7 +163,7 @@ def run(script, port, log_level):
default="local",
help="Target platform for deployment.",
)
@click.option("--port", default=8501, help="Port for deployment.")
@click.option("--port", default=8501, help="Port for deployment. Overrides port in config file if specified.")
@click.option(
"--log-level",
type=click.Choice(
Expand Down
24 changes: 17 additions & 7 deletions preswald/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ def create_app(script_path: Optional[str] = None) -> FastAPI:
allow_headers=["*"],
)

# Configure static files
service.branding_manager = _setup_static_files(app)
# Configure static files and branding manager
branding_manager = _setup_static_files(app)
setattr(service, 'branding_manager', branding_manager)

# Store service instance
app.state.service = service
Expand Down Expand Up @@ -144,6 +145,7 @@ def start_server(script: Optional[str] = None, port: int = 8501):
"""Start the FastAPI server"""
app = create_app(script)

config_port = None
# Load port from config if available
if script:
try:
Expand All @@ -154,11 +156,19 @@ def start_server(script: Optional[str] = None, port: int = 8501):

config = toml.load(config_path)
if "project" in config and "port" in config["project"]:
port = config["project"]["port"]
config_port = config["project"]["port"]
logger.info(f"Using port {config_port} from config.toml")
except Exception as e:
logger.error(f"Error loading config: {e}")

config = uvicorn.Config(app, host="0.0.0.0", port=port, loop="asyncio")
# Use port priority: CLI argument > config file > default
final_port = port if port != 8501 else (config_port if config_port is not None else 8501)
logger.info(f"Starting server on port {final_port}")

# Set environment variable for frontend
os.environ["PRESWALD_PORT"] = str(final_port)

config = uvicorn.Config(app, host="0.0.0.0", port=final_port, loop="asyncio")
server = uvicorn.Server(config)

# Handle shutdown signals
Expand Down Expand Up @@ -250,12 +260,12 @@ def _handle_index_request(service: PreswaldService) -> HTMLResponse:
raise HTTPException(status_code=500, detail="Internal server error") from e


def _handle_favicon_request(service: PreswaldService) -> HTMLResponse:
"""Handle index.html requests with proper branding"""
def _handle_favicon_request(service: PreswaldService) -> FileResponse:
"""Handle favicon requests with proper branding"""
try:
# Get branding configuration
branding = service.branding_manager.get_branding_config(service.script_path)
return FileResponse(branding["favicon"])
except Exception as e:
logger.error(f"Error serving index: {e}")
logger.error(f"Error serving favicon: {e}")
raise HTTPException(status_code=500, detail="Internal server error") from e