samedi 2 janvier 2016

Read static file in view

To integrate Django and Ember, I have decided to serve my Ember SPA in a Django view (avoids CORS issues, only one server for frontend and API, etc). I do it like this:

# urls.py

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include(api_urls, namespace='api')),
    ...
    url(r'^$', views.emberapp, name='emberapp'),
    ...
]

# views.py

from django.http import HttpResponse


def emberapp(request):
    # The Ember frontend SPA index file
    # This only works in development, and is anyway hacky
    EMBER_FE_INDEX_HTML = '/absolute/path/to/my/frontend/static/fe-dist/index.html'
    template_file = open(EMBER_FE_INDEX_HTML)
    html_content = template_file.read()
    template_file.close()
    return HttpResponse(html_content)

The index.html is part of the static assets. In development this is very easy:

  • The index.html is directly accessible to the Django application in the file system
  • I know the absolute path to the index file

But in production things are more complex, because the static assets are not local to the django application, but accessible on Amazon S3. I use django-storages for that.

How can I read the contents of a static file from a view, in a generic way, no matter what backend is used to store/serve the static files?




Aucun commentaire:

Enregistrer un commentaire