我需要从Django Rest Framework api提供/返回javascript文件,所以在任何其他网站客户端中我都可以做到:
<script src="https://myserveraddress.com/django-api/my-view/my-js-file.js"></script>
并通过在我的客户网站上编码这个标签,将其中的内容导入到他们的网站。
如何为其创建视图和url模式?
由于CORS策略,我想使用DRF。
提前感谢!
感谢@mehran heydarian的贡献。根据您的提示并查看rest_framework视图模块内部,使用views.APIView,我已经解决了我的问题,并实现了视图和url。除了视图之外,我还实现了一个过滤器,这样我就可以在查询中传递一个要过滤的url参数:
# 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'),
...
]
这对我来说很好。
使用django HttpResponse并返回
return HttpResponse("<script src="https://myserveraddress.com/django-api/my-view/my-js-file.js"></script>",content_type="application/x-javascript")
HttpResponse来自django->从django.http导入HttpResponse