Skip to content

Instantly share code, notes, and snippets.

@jeremydw
Last active August 11, 2017 00:14
Show Gist options
  • Save jeremydw/16c263da7e1833f763c0 to your computer and use it in GitHub Desktop.
Save jeremydw/16c263da7e1833f763c0 to your computer and use it in GitHub Desktop.
ProtoRPC CORS middleware App Engine app
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
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