1

I need to serve/return javascript files from a Django Rest Framework api, so in any other website client I can do:

<script src="https://myserveraddress.com/django-api/my-view/my-js-file.js"></script>

and import the content from it to my clients websites by coding this tag on them.

How can i do the view and the url pattern for it?

I want to use DRF because of the CORS policy.

Thanks in advance!

2 Answers2

0

Thanks, @mehran heydarian for your contribution. With your tip and looking inside the rest_framework views module, using views.APIView, I have solved my problem and implemented both the view and the url. Additionaly to the view I have implemented a filter, so I can pass an argument on the url to be filtered on a query:

# views.py
from django.http import HttpResponse
from rest_framework import views
from . models import MYMODEL, 

class MYMODELApiView(views.APIView):
    @classmethod
    def get_extra_actions(cls):
        return []
    @api_view(('GET',))
    def my_def(request, some_string):
        """
        some code to implement a condition
        for validation
        """

        def get_queryset(some_string):
            """
            This view returns a string.
            """
            if condition:
                res = MYMODEL.objects.filter(some_field_from_model=some_string).values('file')
                the_file = open('/myserver/directory_before_static/' + res[0]['file'], 'r')
                file_content = the_file.read()
                the_file.close()
                return file_content
            else:
                the_file = open('/myserver/directory_before_static/static/another_directory/another.js', 'r')
                file_content = the_file.read()
                the_file.close()
                return file_content

        file_content = get_queryset(some_string)

        return HttpResponse(file_content, content_type="application/javascript", charset='utf-8')

# urls.py
from django.urls import re_path
from .views import MYMODELApiView

urlpatterns = [
...
re_path('^my_url/(?P<some_string>.+)/$', MYMODELApiView.my_def, name='my_url'),
...
]

This works fine to me.

-1

use django HttpResponse and return it

return HttpResponse("<script src="https://myserveraddress.com/django-api/my-view/my-js-file.js"></script>",content_type="application/x-javascript")

HttpResponse comes from django -> from django.http import HttpResponse