Skip to content

Commit

Permalink
for marcgibbons#434: remove inline scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
groovecoder committed Apr 25, 2016
1 parent cb999b2 commit fcd8052
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 120 deletions.
40 changes: 1 addition & 39 deletions rest_framework_swagger/static/rest_framework_swagger/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,45 +20,7 @@
<!-- enabling this will enable oauth2 implicit scope support -->
<script src='lib/swagger-oauth.js' type='text/javascript'></script>

<script type="text/javascript">
$(function () {
window.swaggerUi = new SwaggerUi({
url: "http://petstore.swagger.wordnik.com/api/api-docs",
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
onComplete: function(swaggerApi, swaggerUi){
log("Loaded SwaggerUI");

if(typeof initOAuth == "function") {
/*
initOAuth({
clientId: "your-client-id",
realm: "your-realms",
appName: "your-app-name"
});
*/
}
$('pre code').each(function(i, e) {
hljs.highlightBlock(e)
});
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none"
});

$('#input_apiKey').change(function() {
var key = $('#input_apiKey')[0].value;
log("key: " + key);
if(key && key.trim() != "") {
log("added key " + key);
window.authorizations.add("key", new ApiKeyAuthorization("api_key", key, "query"));
}
})
window.swaggerUi.load();
});
</script>
<script src='index.js' type='text/javascript'></script>
</head>

<body>
Expand Down
37 changes: 37 additions & 0 deletions rest_framework_swagger/static/rest_framework_swagger/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
$(function () {
window.swaggerUi = new SwaggerUi({
url: "http://petstore.swagger.wordnik.com/api/api-docs",
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
onComplete: function(swaggerApi, swaggerUi){
log("Loaded SwaggerUI");

if(typeof initOAuth == "function") {
/*
initOAuth({
clientId: "your-client-id",
realm: "your-realms",
appName: "your-app-name"
});
*/
}
$('pre code').each(function(i, e) {
hljs.highlightBlock(e)
});
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none"
});

$('#input_apiKey').change(function() {
var key = $('#input_apiKey')[0].value;
log("key: " + key);
if(key && key.trim() != "") {
log("added key " + key);
window.authorizations.add("key", new ApiKeyAuthorization("api_key", key, "query"));
}
})
window.swaggerUi.load();
});
Original file line number Diff line number Diff line change
Expand Up @@ -392,9 +392,10 @@ function program18(depth0,data) {
}

function program20(depth0,data) {
var static_url = $("html").dataset.static_url;


return "\n <div class='sandbox_header'>\n <input class='submit' name='commit' type='button' value='Try it out!' />\n <a href='#' class='response_hider' style='display:none'>Hide Response</a>\n <img alt='Throbber' class='response_throbber' src='"+ window.static_url +"rest_framework_swagger/images/throbber.gif' style='display:none' />\n </div>\n ";
return "\n <div class='sandbox_header'>\n <input class='submit' name='commit' type='button' value='Try it out!' />\n <a href='#' class='response_hider' style='display:none'>Hide Response</a>\n <img alt='Throbber' class='response_throbber' src='"+ static_url +"rest_framework_swagger/images/throbber.gif' style='display:none' />\n </div>\n ";
}

buffer += "\n <ul class='operations' >\n <li class='";
Expand Down
50 changes: 50 additions & 0 deletions rest_framework_swagger/templates/base.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
$(function () {
window.swaggerUi = new SwaggerUi({
url: '{{ swagger_settings.discovery_url }}',
apiKey: '{{ swagger_settings.api_key }}',
dom_id: 'swagger-ui-container',
supportedSubmitMethods: {{ swagger_settings.enabled_methods }},
onComplete: function (swaggerApi, swaggerUi){
log('Loaded SwaggerUI')
$('pre code').each(function(i, e) {hljs.highlightBlock(e)});
},
onFailure: function (data) {
log('Unable to Load SwaggerUI');
},
docExpansion: '{{ swagger_settings.doc_expansion }}',
csrfCookieName: {{ django_settings.CSRF_COOKIE_NAME }}
});

$('#input_apiKey').change(function () {
var key = $('#input_apiKey')[0].value;
log('key: ' + key);

if (key && key.trim() != '') {
console.log('added key ' + key);
window.authorizations.add('key', new ApiKeyAuthorization('Authorization', '{{ swagger_settings.token_type }} ' + key, 'header'));
}
});

{% if swagger_settings.api_key %}
window.authorizations.add('key', new ApiKeyAuthorization('Authorization', '{{ swagger_settings.token_type }} ' + '{{ swagger_settings.api_key }}', 'header'));
{% endif %}

{# Add version to Accept header, if AcceptHeaderVersioning is used. #}
{% if swagger_settings.api_version and rest_framework_settings.DEFAULT_VERSIONING_CLASS == 'rest_framework.versioning.AcceptHeaderVersioning' %}
window.authorizations.add('version', {
apply: function(obj, authorizations) {
$.each(obj.headers, function(k, v) {
if (k.toLowerCase() === "accept") {
if (v.indexOf('; version=') === -1) {
obj.headers[k] += "; version={{ swagger_settings.api_version }}";
}
return false; // break.
}
});
return true;
}
});
{% endif %}

window.swaggerUi.load();
});
58 changes: 2 additions & 56 deletions rest_framework_swagger/templates/rest_framework_swagger/base.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{% load staticfiles %}
{% spaceless %}
<!DOCTYPE html>
<html>
<html data-static_url="{% static '' %}">
<head>
<meta name="viewport" content="width=device-width initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>{% block title %}Swagger UI{% endblock %}</title>
Expand Down Expand Up @@ -46,9 +46,6 @@
<div id="message-bar" class="swagger-ui-wrap"></div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>

<script>
window.static_url = "{% static '' %}";
</script>
<script src="{% static 'rest_framework_swagger/lib/shred.bundle.js' %}" type="text/javascript"></script>
<script src="{% static 'rest_framework_swagger/lib/jquery-1.8.0.min.js' %}" type="text/javascript"></script>
<script src="{% static 'rest_framework_swagger/lib/jquery.slideto.min.js' %}" type="text/javascript"></script>
Expand All @@ -61,58 +58,7 @@
<script src="{% static 'rest_framework_swagger/lib/swagger.js' %}" type="text/javascript"></script>
<script src="{% static 'rest_framework_swagger/swagger-ui.min.js' %}" type="text/javascript"></script>
<script src="{% static 'rest_framework_swagger/lib/highlight.8.0.pack.js' %}" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
window.swaggerUi = new SwaggerUi({
url: '{{ swagger_settings.discovery_url }}',
apiKey: '{{ swagger_settings.api_key }}',
dom_id: 'swagger-ui-container',
supportedSubmitMethods: {{ swagger_settings.enabled_methods }},
onComplete: function (swaggerApi, swaggerUi){
log('Loaded SwaggerUI')
$('pre code').each(function(i, e) {hljs.highlightBlock(e)});
},
onFailure: function (data) {
log('Unable to Load SwaggerUI');
},
docExpansion: '{{ swagger_settings.doc_expansion }}',
csrfCookieName: {{ django_settings.CSRF_COOKIE_NAME }}
});

$('#input_apiKey').change(function () {
var key = $('#input_apiKey')[0].value;
log('key: ' + key);

if (key && key.trim() != '') {
console.log('added key ' + key);
window.authorizations.add('key', new ApiKeyAuthorization('Authorization', '{{ swagger_settings.token_type }} ' + key, 'header'));
}
});

{% if swagger_settings.api_key %}
window.authorizations.add('key', new ApiKeyAuthorization('Authorization', '{{ swagger_settings.token_type }} ' + '{{ swagger_settings.api_key }}', 'header'));
{% endif %}

{# Add version to Accept header, if AcceptHeaderVersioning is used. #}
{% if swagger_settings.api_version and rest_framework_settings.DEFAULT_VERSIONING_CLASS == 'rest_framework.versioning.AcceptHeaderVersioning' %}
window.authorizations.add('version', {
apply: function(obj, authorizations) {
$.each(obj.headers, function(k, v) {
if (k.toLowerCase() === "accept") {
if (v.indexOf('; version=') === -1) {
obj.headers[k] += "; version={{ swagger_settings.api_version }}";
}
return false; // break.
}
});
return true;
}
});
{% endif %}

window.swaggerUi.load();
});
</script>
<script src="base.js" type="text/javascript"></script>
{% endblock %}
</body>
</html>
Expand Down
5 changes: 4 additions & 1 deletion rest_framework_swagger/urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from django.conf.urls import url
from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView
from rest_framework_swagger.views import (SwaggerBaseJSView,
SwaggerResourcesView, SwaggerApiView,
SwaggerUIView)


urlpatterns = [
url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"),
url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"),
url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'),
url(r'^base.js$', SwaggerBaseJSView.as_view(), name='django.swagger.basejs.view')
]
66 changes: 43 additions & 23 deletions rest_framework_swagger/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.utils import six

from django.conf import settings
from django.views.generic import View
from django.views.generic import View, TemplateView
from django.utils.safestring import mark_safe
from django.utils.encoding import smart_text
from django.shortcuts import render_to_response, RequestContext
Expand Down Expand Up @@ -45,40 +45,48 @@ def get_full_base_path(request):
try:
base_path = rfs.SWAGGER_SETTINGS['base_path']
except KeyError:
return request.build_absolute_uri(request.path).rstrip('/')
base_path = request.build_absolute_uri(request.path).rstrip('/')
base_path = base_path.replace('/base.js', '')
return base_path
else:
protocol = 'https' if request.is_secure() else 'http'
return '{0}://{1}'.format(protocol, base_path.rstrip('/'))


def context_data(request):
data = {
'swagger_settings': {
'discovery_url': "%s/api-docs/" % get_full_base_path(request),
'api_key': rfs.SWAGGER_SETTINGS.get('api_key', ''),
'api_version': rfs.SWAGGER_SETTINGS.get('api_version', ''),
'token_type': rfs.SWAGGER_SETTINGS.get('token_type'),
'enabled_methods': mark_safe(
json.dumps(rfs.SWAGGER_SETTINGS.get('enabled_methods'))),
'doc_expansion': rfs.SWAGGER_SETTINGS.get('doc_expansion', ''),
},
'rest_framework_settings': {
'DEFAULT_VERSIONING_CLASS':
settings.REST_FRAMEWORK.get('DEFAULT_VERSIONING_CLASS', '')
if hasattr(settings, 'REST_FRAMEWORK') else None,

},
'django_settings': {
'CSRF_COOKIE_NAME': mark_safe(
json.dumps(getattr(settings, 'CSRF_COOKIE_NAME', 'csrftoken'))),
}
}
return data


class SwaggerUIView(View):
def get(self, request, *args, **kwargs):

if not self.has_permission(request):
return self.handle_permission_denied(request)

data = context_data(request)

template_name = rfs.SWAGGER_SETTINGS.get('template_path')
data = {
'swagger_settings': {
'discovery_url': "%s/api-docs/" % get_full_base_path(request),
'api_key': rfs.SWAGGER_SETTINGS.get('api_key', ''),
'api_version': rfs.SWAGGER_SETTINGS.get('api_version', ''),
'token_type': rfs.SWAGGER_SETTINGS.get('token_type'),
'enabled_methods': mark_safe(
json.dumps(rfs.SWAGGER_SETTINGS.get('enabled_methods'))),
'doc_expansion': rfs.SWAGGER_SETTINGS.get('doc_expansion', ''),
},
'rest_framework_settings': {
'DEFAULT_VERSIONING_CLASS':
settings.REST_FRAMEWORK.get('DEFAULT_VERSIONING_CLASS', '')
if hasattr(settings, 'REST_FRAMEWORK') else None,

},
'django_settings': {
'CSRF_COOKIE_NAME': mark_safe(
json.dumps(getattr(settings, 'CSRF_COOKIE_NAME', 'csrftoken'))),
}
}
response = render_to_response(
template_name, RequestContext(request, data))

Expand Down Expand Up @@ -177,3 +185,15 @@ def get_apis_for_resource(self, filter_path):
authorized_apis = filter(lambda a: self.handle_resource_access(self.request, a['pattern']), apis)
authorized_apis_list = list(authorized_apis)
return authorized_apis_list


class SwaggerBaseJSView(TemplateView):
def get(self, request, *args, **kwargs):
data = context_data(request)

response = render_to_response('base.js',
RequestContext(request, data),
content_type="text/javascript"
)

return response

0 comments on commit fcd8052

Please sign in to comment.