python-eel / Eel

A little Python library for making simple Electron-like HTML/JS GUI apps
MIT License
6.47k stars 589 forks source link

Is it possible to add headers to enable CORS? #231

Open wd77 opened 4 years ago

wd77 commented 4 years ago

Hi Samuel,

I would like to use an eel-based App from another web-based system and have that system call eel on localhost. Therefore to allow Cross-Origin Requests i would need my eel-based app add the needed headers. But since the bottle webserver is wrapped inside eel I don't find any obvious way to add the headers. When working directly with bottle you would be able to set them e.g. through: response.headers['Access-Control-Allow-Origin'] = 'http://localhost:8000/'

Is there a way to hand this through eel to the webserver?

wd77 commented 4 years ago

Any ideas on this? Is this a scenario you have considered or have come across?

ilkerx commented 4 years ago

Looking for the same thing. Any ideas how to do it?

samuelhwilliams commented 4 years ago

Hi. Sorry for the slow reply.

I think this is probably starting to push the bounds of the scope that Eel was designer for - i.e. mostly simple local prototypes/scripts.

That said, there is a user-space solution for this that should work for most cases - custom middleware for the Bottle app that adds the CORS header you need. Here's an example:

import bottle
import eel

eel.init("web")

class CORSMiddleware():
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        def custom_header_response(status, headers, exc_info=None):
            headers.append(('Access-Control-Allow-Origin, 'http://localhost:8000/'))
            return start_response(status, headers, exc_info)
        resp = self.app(environ, custom_header_response)
        return resp

btl = bottle.app()
myapp = CORSMiddleware(btl)

eel.start("hello.html", app=myapp)

You can read (a bit) more about Bottle middleware here: https://bottlepy.org/docs/dev/recipes.html#debugging-with-style-debugging-middleware

But it's probably worth reading up in general on WSGI middleware.

Does that help @wd77 @ilkerx?