Skip to content

Commit

Permalink
edit for django 3 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolasmoreau committed Jan 11, 2022
1 parent a0da420 commit 44842ab
Show file tree
Hide file tree
Showing 13 changed files with 817 additions and 1,092 deletions.
20 changes: 9 additions & 11 deletions applyXSL/urls.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
from django.conf.urls import patterns, url, include
from django.conf.urls import url
from django.views.generic import TemplateView

urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='homepage.html'), name="home"),
)

from . import views
from django.conf import settings

class CapabilitiesView(TemplateView):
Expand All @@ -16,10 +13,11 @@ def get_context_data(self, **kwargs):



urlpatterns = patterns('applyXSL.views',
(r'^(?P<xsl>\w+)/$', 'showForm'),
(r'^(?P<xsl>\w+)/service$', 'receiveInput'),
(r'^(?P<xsl>\w+)/result/(?P<rid>\w+)$', 'deliverResult'),
(r'^(?P<xsl>\w+)/availability$', TemplateView.as_view(template_name='availability.xml')),
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='index.html'), name="home"),
url(r'^(?P<xsl>\w+)/$', views.showForm),
url(r'^(?P<xsl>\w+)/service$', views.receiveInput),
url(r'^(?P<xsl>\w+)/result/(?P<rid>\w+)$', views.deliverResult),
url(r'^(?P<xsl>\w+)/availability$', TemplateView.as_view(template_name='availability.xml')),
url(r'^(?P<xsl>\w+)/capabilities$', CapabilitiesView.as_view()),
)
]
91 changes: 26 additions & 65 deletions applyXSL/views.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,29 @@
# -*- coding: utf-8 -*-

from django.shortcuts import render,render_to_response, get_object_or_404
from django.shortcuts import render,get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound
from django.forms import Form,FileField,URLField,TextInput
from django.core.exceptions import ValidationError

from lxml import etree as e
from urllib2 import urlopen
from urllib.request import urlopen
import os
import threading
from time import sleep
from . import xsl

from . import models

from django.conf import settings
STATIC=settings.STATIC_DIR
if hasattr(settings,'DEPLOY_URL'):
APPURL = settings.DEPLOY_URL+'applyXSL/'
else:
APPURL = '/applyXSL/'


if hasattr(settings,'SAXON_JAR'):
import xsl
useJAVAxsl = True
else: useJAVAxsl = False

from models import Conversion
STATIC=settings.STATIC_DIR
XSL_MIME = {'xsams2sme':'text/plain',
'linespec':'image/svg+xml',
'atomicxsams2html':'text/html',
'molecularxsams2html':'text/html',
'collisions2html':'text/html',}

XSL_VERSION = {'xsams2sme':1,
'linespec':1,
'atomicxsams2html':1,
Expand All @@ -42,7 +33,7 @@
class ConversionForm(Form):
upload = FileField(label='Input file',required=False)
url = URLField(label='Input URL',required=False,widget=TextInput(attrs={'size': 50, 'title': 'Paste here a URL that delivers an XSAMS document.',}))

def clean(self):
upload = self.cleaned_data.get('upload')

Expand All @@ -56,61 +47,31 @@ def showForm(request,xsl):
if xsl not in XSL_MIME:
return HttpResponseNotFound()
ConvForm = ConversionForm()
return render_to_response('applyXSL.html',
RequestContext(request,dict(conversion=ConvForm)))

def transformJAVA(conv,err=None):
transformer = xsl.XslTransformerFactory.getXslTransformer(XSL_VERSION[conv.xsl])
try:
result = transformer.transform(conv)
except:
err = '500 transformation failed\n'
result = None
return err,result


def transformLXML(conv,err=None):
xslfile = open(STATIC+'/xsl/%s.xsl'%conv.xsl)
xsl = e.XSLT(e.parse(xslfile))
try:
if conv.url:
xml = e.parse(urlopen(conv.url))
elif conv.upload:
xml = e.parse(conv.upload)
else:
err = '400 no data to transform\n'
except:
err = '400 input data seems to be broken XML\n'

try:
output = str(xsl(xml))
except:
err = '500 transformation failed\n'
output=None
return err,output
return render(request, 'applyXSL.html',dict(conversion=ConvForm))

class DoWork(threading.Thread):
def __init__(self, conv):
threading.Thread.__init__(self)
self.conv = conv
self.outfile = STATIC+'/results/%s'%conv.pk

self.err = ''

def run(self):
if useJAVAxsl:
err,result = transformJAVA(self.conv)
else:
err,result = transformLXML(self.conv)

if err:
open(self.outfile+'.err','w').write(err)
else:
open(self.outfile,'w').write(result)

transformer = xsl.XslTransformerFactory.getXslTransformer(XSL_VERSION[self.conv.xsl])
result = transformer.transform(self.conv)

try :
open(self.outfile,'w').write(result)
except Exception as exc:
open(self.outfile,'w').write(str(exc))


def receiveInput(request,xsl):
print(dir(request))
ConvForm = ConversionForm(request.POST, request.FILES)

if ConvForm.is_valid():
conv = Conversion(xsl=xsl,
conv = models.Conversion(xsl=xsl,
upload=ConvForm.cleaned_data['upload'],
url=ConvForm.cleaned_data['url'] )
conv.save(force_insert=True)
Expand All @@ -121,19 +82,19 @@ def receiveInput(request,xsl):
# give it a second, so we might skip the
# waiting-page for quick transforms
sleep(2)
return HttpResponseRedirect(APPURL+'%s/result/%s'%(xsl,conv.pk))
return HttpResponseRedirect(settings.DEPLOY_URL+'applyXSL/%s/result/%s'%(xsl,conv.pk))
else:
return HttpResponseRedirect(APPURL+'%s/'%xsl)
return HttpResponseRedirect(settings.DEPLOY_URL+'applyXSL/%s/'%xsl)

def deliverResult(request,xsl,rid):
conv = get_object_or_404(Conversion,pk=rid)
conv = get_object_or_404(models.Conversion,pk=rid)
outfile = STATIC+'/results/%s'%rid

if os.path.exists(outfile+'.err'):
errstring = open(outfile+'.err').readline()
errcode, msg = errstring.split(' ',1)
errcode, msg = open(outfile+'.err').readline().split(' ',1)
return HttpResponse(msg,status=errcode,content_type='text/plain')
elif os.path.exists(outfile):
return HttpResponse(open(outfile),content_type=XSL_MIME.get(xsl,'text/plain'))
else:
return HttpResponse(render(request,'wait5.html',{}),status=202)

29 changes: 15 additions & 14 deletions applyXSL/xsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from abc import ABCMeta, abstractmethod
from lxml import etree as e
from django.conf import settings
import commands
from urllib2 import urlopen
import subprocess
from urllib.request import urlopen
import tempfile

STATIC=settings.STATIC_DIR
Expand Down Expand Up @@ -32,22 +32,23 @@ def __init__(self):

def transform(self, form):
xslfile = STATIC+'/xsl/%s.xsl'%form.xsl
import os.path
try:
if form.url:
command = 'java -jar '+SAXON_JAR+' -s:"%s" -xsl:%s'%(form.url, xslfile)
output = commands.getoutput(command)
command = ['java', '-jar', SAXON_JAR, '-s:"{form.url}"'.format(form.url), '-xsl:{}'.format(xslfile)]
output = subprocess.check_output(' '.join(command), encoding="UTF-8")
elif form.upload:
tmpfile = tempfile.NamedTemporaryFile(delete=False)
xml = e.tostring(e.parse(form.upload))
tmpfile.write(xml)
tmpfile.flush() # be sure that all data have been written
command = 'java -jar '+SAXON_JAR+' -s:"%s" -xsl:%s'%(tmp.name, xslfile)
output = commands.getoutput(command)
with tempfile.NamedTemporaryFile(delete=True) as tmpfile:
xml = e.tostring(e.parse(form.upload))
tmpfile.write(xml)
tmpfile.flush() # be sure that all data have been written
command = ['java', '-jar', SAXON_JAR, '-s:%s'%(tmpfile.name), '-xsl:{}'.format(xslfile)]
output = subprocess.check_output(command, encoding="UTF-8")
else:
self.err = '400 no data to transform\n'
except Exception, exc:
except Exception as exc:
self.err = '400 input data seems to be broken XML\n'
print exc
print(exc)

if self.err:
return self.err
Expand All @@ -71,9 +72,9 @@ def transform(self, form):
xml = e.parse(form.upload)
else:
self.err = '400 no data to transform\n'
except Exception, exc:
except Exception as exc:
self.err = '400 input data seems to be broken XML\n'
print exc
print(exc)

try:
output = str(xsl(xml))
Expand Down
13 changes: 4 additions & 9 deletions processors/urls.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
from django.conf.urls import patterns, include, url
#from django.contrib import admin

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'processors.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# url(r'^admin/', include(admin.site.urls)),
from django.conf.urls import url, include

urlpatterns = [
url(r'^applyXSL/', include('applyXSL.urls')),
url(r'^specsynth/', include('specsynth.urls')),
)
]

16 changes: 10 additions & 6 deletions specsynth/urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
from django.conf.urls import patterns, include, url
from django.conf.urls import url, include

urlpatterns = patterns('specsynth.views',
(r'^$', 'showForm'),
(r'service$', 'receiveInput'),
(r'result/spec_(?P<rid>\w+).json$', 'deliverResult'),
from specsynth import views

urlpatterns = [
url(r'^$', views.showForm),
url(r'service$', views.receiveInput),
url(r'result/spec_(?P<rid>\w+).json$', views.deliverResult),
#(r'^(?P<xsl>\w+)/availability$', direct_to_template, {'template':'availability.xml','extra_context':{'deployurl':settings.DEPLOY_URL}}),
#(r'^(?P<xsl>\w+)/capabilities$', direct_to_template, {'template':'capabilities.xml','extra_context':{'deployurl':settings.DEPLOY_URL}})
)

]

17 changes: 8 additions & 9 deletions specsynth/views.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
# -*- coding: utf-8 -*-

from django.shortcuts import render,render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.forms import Form,FileField,URLField,TextInput
from django.core.exceptions import ValidationError

from lxml import etree as e
from urllib2 import urlopen
from urllib.request import urlopen
import os
import threading
from time import sleep
import json
from models import Spec
from .models import Spec

from django.conf import settings
STATIC = settings.STATIC_DIR
Expand Down Expand Up @@ -49,8 +48,8 @@ def clean(self):

def showForm(request):
ConvForm = ConversionForm()
return render_to_response('specsynth.html',
RequestContext(request,dict(conversion=ConvForm)))
return render(request, 'specsynth.html',
dict(conversion=ConvForm))

class DoWork(threading.Thread):
def __init__(self,conv):
Expand All @@ -70,8 +69,8 @@ def run(self):
self.err += '400 input data seems to be broken XML\n'
try:
output = prepare_json(xml)
except Exception, E:
print E
except Exception as exc:
print(exc)
self.err += '500 transformation failed\n'

if self.err:
Expand Down
16 changes: 12 additions & 4 deletions static/vamdc_files/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -145,20 +145,28 @@ a {
float: left;
}
.main-content-1 {
width: 880px;
width: 70%;
float: left;
position: relative;
}
.main-content-2 {
width: 732px;
width: 70%;
float: left;
}
.main-content-full {
width: 100%}
width: 100%
}

.sidebar-right {
width: 210px;
width: 20%;
float: right;
}

.sidebar-right ul{
margin-bottom: 1em;
list-style:none;
}

.top-bar {
zoom: 1;
width: 100%}
Expand Down
Loading

0 comments on commit 44842ab

Please sign in to comment.