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

KeyError on CORS Middleware in hug.extend #767

Open
JGabrielGruber opened this issue Apr 8, 2019 · 1 comment
Open

KeyError on CORS Middleware in hug.extend #767

JGabrielGruber opened this issue Apr 8, 2019 · 1 comment

Comments

@JGabrielGruber
Copy link

JGabrielGruber commented Apr 8, 2019

Hi,
I'm really sorry about adding another issue, but, there is a problem with the CORS middleware; if you're using hug.extend, like in this code:

# teste.py
import	hug

import extended

api = hug.API(__name__)
api.http.add_middleware(hug.middleware.CORSMiddleware(api, allow_origins=["*"]))

@hug.extend_api('/extended')
def empresa_api():
	return [extended]
# extended.py
import	hug

@hug.get('/')
def testing():
	return "Testing!"

@hug.get('/{id}')
def test(id):
	return "Testing " + id

It generates this beautiful error, if you make a OPTIONS request in /extended/:

Traceback (most recent call last):
  File "/usr/lib64/python3.7/wsgiref/handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "/directory/lib/python3.7/site-packages/falcon/api.py", line 260, in __call__
    process_response(req, resp, resource, req_succeeded)
  File "/directory/lib/python3.7/site-packages/hug/middleware.py", line 147, in process_response
    for _, routes in self.api.http.routes.items()
  File "/directory/lib/python3.7/site-packages/hug/middleware.py", line 148, in <genexpr>
    for method, _ in routes[self.match_route(request.path)].items()
KeyError: '/extended'
127.0.0.1 - - [08/Apr/2019 09:13:37] "OPTIONS /extended HTTP/1.1" 500 59

If I make a OPTIONS request in /extended/666(or any number), it works fine;
127.0.0.1 - - [08/Apr/2019 09:23:32] "OPTIONS /extended/666 HTTP/1.1" 200 0
I made a temporary fix for this in my use case, it works, but, it's not right:

class CORSMiddleware(object):
	"""A middleware for allowing cross-origin request sharing (CORS)

	Adds appropriate Access-Control-* headers to the HTTP responses returned from the hug API,
	especially for HTTP OPTIONS responses used in CORS preflighting.
	"""
	__slots__ = ('api', 'allow_origins', 'allow_credentials', 'max_age')

	def __init__(self, api, allow_origins: list=['*'], allow_credentials: bool=True, max_age: int=None):
		self.api = api
		self.allow_origins = allow_origins
		self.allow_credentials = allow_credentials
		self.max_age = max_age

	def process_response(self, request, response, resource):
		"""Add CORS headers to the response"""
		response.set_header('Access-Control-Allow-Credentials', str(self.allow_credentials).lower())

		origin = request.get_header('ORIGIN')
		if origin and (origin in self.allow_origins) or ('*' in self.allow_origins):
			response.set_header('Access-Control-Allow-Origin', origin)

		if request.method == 'OPTIONS': # check if we are handling a preflight request
			#allowed_methods = set(
			#	method
			#	for _, routes in self.api.http.routes.items()
			#	for method, _ in routes[self.match_route(request.path)].items()
			#)
			#allowed_methods.add('OPTIONS')

			# return allowed methods
			response.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
			#response.set_header('Allow', ', '.join(allowed_methods))

			# get all requested headers and echo them back
			requested_headers = request.get_header('Access-Control-Request-Headers')
			response.set_header('Access-Control-Allow-Headers', requested_headers or '')

			# return valid caching time
			if self.max_age:
				response.set_header('Access-Control-Max-Age', self.max_age)

I'm using:

  • hug 2.4.8
  • ManjaroLinux 18.0.4
  • python 3.7.2

I didn't know what to use as title, sorry.

@JGabrielGruber
Copy link
Author

Hey guys,

This is still a issue...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant