52 lines
2.0 KiB
Python
52 lines
2.0 KiB
Python
import os
|
|
from optparse import make_option
|
|
|
|
from django.conf import settings
|
|
from django.contrib.staticfiles.handlers import StaticFilesHandler
|
|
from django.contrib.staticfiles.management.commands.runserver import Command as StaticRunserverCommand
|
|
from django.contrib.staticfiles.views import serve
|
|
from django.core.management.commands.runserver import Command as RunserverCommand
|
|
from django.views import static
|
|
|
|
from hobo.multitenant.middleware import TenantMiddleware, TenantNotFound
|
|
|
|
|
|
class TenantStaticFilesHandler(StaticFilesHandler):
|
|
def serve(self, request):
|
|
file_path = self.file_path(request.path)
|
|
hostname_without_port = request.get_host().split(':')[0]
|
|
response = None
|
|
try:
|
|
tenant = TenantMiddleware.get_tenant_by_hostname(hostname_without_port)
|
|
except TenantNotFound:
|
|
pass
|
|
else:
|
|
for dirname in ('static', 'theme/static'):
|
|
tenant_static_dir = os.path.join(tenant.get_directory(), dirname)
|
|
tenant_file_path = os.path.join(tenant_static_dir, file_path)
|
|
if os.path.exists(tenant_file_path):
|
|
response = static.serve(request, file_path, document_root=tenant_static_dir)
|
|
if not response:
|
|
response = serve(request, file_path, insecure=True)
|
|
response['Access-Control-Allow-Origin'] = '*'
|
|
return response
|
|
|
|
|
|
class Command(StaticRunserverCommand):
|
|
def get_handler(self, *args, **options):
|
|
"""
|
|
Returns the static files serving handler wrapping the default handler,
|
|
if static files should be served. Otherwise just returns the default
|
|
handler.
|
|
|
|
"""
|
|
handler = super().get_handler(*args, **options)
|
|
use_static_handler = options.get('use_static_handler', True)
|
|
insecure_serving = options.get('insecure_serving', False)
|
|
if use_static_handler and (settings.DEBUG or insecure_serving):
|
|
return TenantStaticFilesHandler(handler)
|
|
return handler
|
|
|
|
def check_migrations(self):
|
|
pass
|