Last active
August 11, 2017 00:14
-
-
Save jeremydw/16c263da7e1833f763c0 to your computer and use it in GitHub Desktop.
ProtoRPC CORS middleware App Engine app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
application: protorpc-cors-middleware | |
version: protorpc-cors-middleware | |
api_version: 1 | |
runtime: python27 | |
threadsafe: true | |
libraries: | |
- name: webapp2 | |
version: latest | |
handlers: | |
- url: /.* | |
script: main.app |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from protorpc import messages | |
from protorpc import remote | |
from protorpc.wsgi import service | |
class TestRequest(messages.Message): | |
pass | |
class TestResponse(messages.Message): | |
pass | |
class TestService(remote.Service): | |
@remote.method(TestRequest, TestResponse) | |
def run(self, request): | |
return TestResponse() | |
def CorsMiddleware(app): | |
def _set_headers(headers): | |
headers.append(('Access-Control-Allow-Origin', '*')) | |
headers.append(('Access-Control-Allow-Methods', '*')) | |
headers.append(('Access-Control-Allow-Headers', 'origin, content-type, accept')) | |
return headers | |
def middleware(environ, start_response): | |
if environ.get('REQUEST_METHOD') == 'OPTIONS': | |
headers = [] | |
headers = _set_headers(headers) | |
start_response('200 OK', headers) | |
return [] | |
def headers_start_response(status, headers, *args, **kwargs): | |
all_headers = [key.lower() for key, val in headers] | |
if 'access-control-allow-origin' not in all_headers: | |
headers = _set_headers(headers) | |
return start_response(status, headers, *args, **kwargs) | |
return app(environ, headers_start_response) | |
return middleware | |
services = service.service_mappings(( | |
('/_api/test.*', TestService), | |
), registry_path='/_api/protorpc') | |
app = CorsMiddleware(services) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment