Fonty
Fonty

Reputation: 251

Setting up CORS with Faust webview

I'm attempting to directly post information to a Kaka topic via a Faust web view as per their example. However, I'm getting the familiar CORS issue in the response. Looking into the docs only leads me to see that I need to use aiohttp-cors to set up the options, but it's really unclear how to do this with a Faust application.

Below is a cut down version of my server-side code:

import faust
from faust.web import Request, Response, View
import asyncio
from models.models_2 import AlarmFilterRequest

BROKER_LIST=['kafka://localhost:9092', 'kafka://localhost:9093', 'kafka://localhost:9094']

app = faust.App('alarm-filter-stream', broker=BROKER_LIST, store='memory://')

alarm_filter_requests_topic = app.topic('alarm-filter-requests', value_type=AlarmFilterRequest, value_serializer='json')

@app.agent(alarm_filter_requests_topic)
async def new_filter_request(stream):
  async for event in stream.events():
    # do some processing
    ...

@app.page('/filter')
class test_page_view(View):  
  async def post(self, request: Request) -> Response:
    # Here we want to produce to the alarm_filter_requests topic
    return self.json({"timestamp":f"{datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S.%f')}"})

I simply can't figure out how to set the allowed origins and headers etc. to avoid the CORS errors.

Upvotes: 1

Views: 316

Answers (1)

Fonty
Fonty

Reputation: 251

Thanks to Vikram Patki on the slack channel for offering an answer.

It's not easy to find in the Faust documentation so hopefully anyone else with the same issue will find this solution quickly.

The trick is to include the cors details when you define the app like so:

app = faust.App(
  'app-name',
  broker=BROKER_LIST,
  store=STORE,
  web_cors_options={
    "*": ResourceOptions(
      allow_credentials=False,
      allow_methods="*",
      expose_headers="*",
      allow_headers="*",
    )
  }
)

Then to use anything other than get requests, you need to set up as per the example in the docs.

Upvotes: 1

Related Questions