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

Add cors to backend server #524

Merged
merged 4 commits into from
Feb 12, 2023
Merged
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
32 changes: 32 additions & 0 deletions pynecone/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Any, Callable, Coroutine, Dict, List, Optional, Type, Union

from fastapi import FastAPI
from fastapi.middleware import cors
from socketio import ASGIApp, AsyncNamespace, AsyncServer

from pynecone import constants, utils
Expand Down Expand Up @@ -74,6 +75,8 @@ def __init__(self, *args, **kwargs):

# Set up the API.
self.api = FastAPI()
self.add_cors(config.cors_allowed_origins)
self.add_default_endpoints()

# Set up CORS options.
cors_allowed_origins = config.cors_allowed_origins
Expand Down Expand Up @@ -116,6 +119,26 @@ def __call__(self) -> FastAPI:
"""
return self.api

def add_default_endpoints(self):
"""Add the default endpoints."""
# To test the server.
self.api.get(str(constants.Endpoint.PING))(ping)

def add_cors(self, allowed_origins: Optional[List[str]] = None):
"""Add CORS middleware to the app.

Args:
allowed_origins: A list of allowed origins.
"""
allowed_origins = allowed_origins or ["*"]
self.api.add_middleware(
cors.CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

def preprocess(self, state: State, event: Event) -> Optional[Delta]:
"""Preprocess the event.

Expand Down Expand Up @@ -392,6 +415,15 @@ async def process(
return update


async def ping() -> str:
"""Test API endpoint.

Returns:
The response.
"""
return "pong"


class EventNamespace(AsyncNamespace):
"""The event namespace."""

Expand Down
1 change: 1 addition & 0 deletions pynecone/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ class LogLevel(str, Enum):
class Endpoint(Enum):
"""Endpoints for the pynecone backend API."""

PING = "ping"
EVENT = "event"

def __str__(self) -> str:
Expand Down