forked from hydroshare/hs_app_template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviews.py
executable file
·268 lines (205 loc) · 9.14 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.views import generic
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
#from django.common.decorators import render_to
from hs_core import hydroshare
from django import forms
from .models import HydroProgramResource
from django.utils.timezone import now
from ga_resources.utils import json_or_jsonp
import json
import os
from django.conf import settings
from .metadata import parser
import mmap
from mezzanine.pages.page_processors import processor_for
from django.template import RequestContext
# from django.contrib import messages
from crispy_forms.helper import FormHelper
class DetailView(generic.DetailView):
model = HydroProgramResource
#template_name = 'hydromodel/detail.html'
template_name = 'hs_hydroprogram/detail.html'
class CreateHydroProgramForm(forms.Form):
#
# def __init__(self, *args, **kwargs):
# super(CreateHydroProgramForm,self).__init(*args, **kwargs)
# self.helper= FormHelper()
# self.helper.html5_required = True
title = forms.CharField(required=True)
creators = forms.CharField(required=False, min_length=0)
contributors = forms.CharField(required=False, min_length=0)
abstract = forms.CharField(required=False, min_length=0)
keywords = forms.CharField(required=False, min_length=0)
# # rest_url = forms.URLField(required=False)
# # wsdl_url = forms.URLField(required=False)
# reference_type = forms.CharField(required=False, min_length=0)
# # site = forms.CharField(required=False, min_length=0)
# # variable = forms.CharField(required=False, min_length=0)
# software_url = forms.CharField(required=False, min_length=0)
software_version = forms.CharField(required=False,max_length=255)
software_language = forms.CharField(required=False,max_length=100)
operating_sys = forms.CharField(required=False,max_length=255)
date_released = forms.DateTimeField(required=True)
release_notes = forms.CharField(required=False)
program_website = forms.CharField(required=True, max_length=255)
software_repo = forms.CharField(required=True, max_length=255)
user_manual = forms.FileField(required=False)
theoretical_manual = forms.FileField(required=False)
source_code = forms.FileField(required=False)
exec_code = forms.FileField(required=False)
build_notes = forms.CharField(required=False)
def file_upload(request):
print 'Upload function'
form_data = {'title':'My Title'}
# return back some info
#return render(request,'pages/create-hydro-program.html',form_data)
return render_to_response('pages/create-hydro-program.html',form_data, context_instance=RequestContext(request))
#return render_to_response('create-resource.html',{'form':form})
# return HttpResponse()
def mytest(request, *args, **kwargs):
print 'TEST'
@login_required
def create_hydro_program(request, *args, **kwargs):
print 'CREATE RESOURCE'
form = CreateHydroProgramForm(request.POST)
print request.POST['creators']
#print frm
#print request.FILES.getlist('files'),
if form.is_valid():
dcterms = [
{ 'term': 'T', 'content': form.cleaned_data['title']},
{ 'term': 'AB', 'content': form.cleaned_data['abstract'] or form.cleaned_data['title']},
{ 'term': 'DTS', 'content': now().isoformat()}
]
for cn in form.cleaned_data['contributors'].split(','):
cn = cn.strip()
dcterms.append({'term' : 'CN', 'content' : cn})
for cr in form.cleaned_data['creators'].split(','):
cr = cr.strip()
dcterms.append({'term' : 'CR', 'content' : cr})
# get files
file_map = form.cleaned_data['file_map']
uploaded_files = {}
for f in request.files:
tag = file_map[f.name]
upload_files[tag] = f
res = hydroshare.create_resource(
resource_type='HydroProgramResource',
owner=request.user,
title=form.cleaned_data['title'],
keywords=[k.strip() for k in form.cleaned_data['keywords'].split(',')] if form.cleaned_data['keywords'] else None,
dublin_metadata=dcterms,
content=form.cleaned_data['abstract'] or form.cleaned_data['title'],
###########
software_version = form.cleaned_data['sofware_version'],
software_language = form.cleaned_data['software_language'],
operating_sys = form.cleaned_data['operating_sys'],
date_released = form.cleaned_data['date_released'],
release_notes = form.cleaned_data['release_notes'],
program_website =form.cleaned_data['program_website'],
software_repo =form.cleaned_data['software_repo'],
user_manual =form.cleaned_data[''],
theoretical_manual =form.cleaned_data[''],
source_code =form.cleaned_data[''],
exec_code =form.cleaned_data[''],
build_notes =form.cleaned_data[''],
)
return HttpResponseRedirect(res.get_absolute_url())
else:
# messages.error(request, "Error")
#return render_to_response('pages/create-hydro-program.html',frm, context_instance=RequestContext(request))
context = {'form': form,'test':'somevalue'}
return render_to_response('pages/create-hydro-program.html', context ,context_instance=RequestContext(request))
#return render(request, 'pages/create-hydro-program.html', {'form':frm})
# #todo: Copied from Ref Time Series. Do I need this?
# @processor_for(HydroProgramResource)
# def add_dublin_core(request, page):
# from dublincore import models as dc
#
# class DCTerm(forms.ModelForm):
# class Meta:
# model = dc.QualifiedDublinCoreElement
# fields = ['term', 'content']
#
# cm = page.get_content_model()
# try:
# abstract = cm.dublin_metadata.filter(term='AB').first().content
# except:
# abstract = None
#
# return {
# 'dublin_core': [t for t in cm.dublin_metadata.all().exclude(term='AB').exclude(term='DM').exclude(term='DC').exclude(term='DTS').exclude(term='T')],
# 'abstract' : abstract,
# 'short_id' : cm.short_id,
# 'resource_type': cm._meta.verbose_name,
# 'reference_type': cm.reference_type,
# 'url': cm.url,
# 'site_name': cm.data_site_name if cm.data_site_name else '',
# 'site_code' : cm.data_site_code if cm.data_site_code else '',
# 'variable_name': cm.variable_name if cm.variable_name else '',
# 'variable_code': cm.variable_code if cm.variable_code else '',
# 'files': cm.files.all(),
# 'dcterm_frm': DCTerm(),
# 'bag': cm.bags.first(),
# 'users': User.objects.all(),
# 'groups': Group.objects.all(),
# 'owners': set(cm.owners.all()),
# 'view_users': set(cm.view_users.all()),
# 'view_groups': set(cm.view_groups.all()),
# 'edit_users': set(cm.edit_users.all()),
# 'edit_groups': set(cm.edit_groups.all()),
# }
def upload_files(request):
print 'here!'
files = request.POST.get('content', 'NONE')
data = {'response': 'I received the file list on the server!'}
#render_to_response('create_hydro_program.html', {'h': 'test'})
return json_response(True,data)
def parse_metadata(request):
name = request.POST.get('name','NONE')
type = request.POST.get('type','NONE')
size = request.POST.get('size','NONE')
content = request.POST.get('content', 'NONE')
parsed_metadata = {}
if content != 'NONE':
# todo: validate the metadata file
#if parser.validate(content):
# create a file object in memory
fileObj = mmap.mmap(-1,len(content))
fileObj.write(content)
fileObj.seek(0)
# parse the file object
parsed_metadata = parser.get_metadata_dictionary(fileObj)
data = {'name':name,
'type':type,
'size':size,
'content':parsed_metadata}
#render_to_response('create_hydro_program.html', {'h': 'test'})
return json_response(True,data)
def get_eula(request):
print 'IN: get_eula(request)'
name = request.GET.get('name','NONE')
response = {'eula':'Could not find a EULA for: '+name}
formatted_name = name.lower().replace(' ','')
try:
path = os.path.join(settings.STATIC_ROOT, 'resources/eulas.json')
txt = open(path,'r').readlines()[0]
# todo: move th is to view load, so that it isn't constantly repeated
# load the eula dictionary
eula_dict = json.loads(txt)
# set the response
if formatted_name in eula_dict:
response['eula'] = eula_dict[formatted_name]
else:
print formatted_name, 'not in dictionary!'
except Exception, e:
print e
return json_response(True,response)
def json_response(result, data):
response = json.dumps({"result" : result, "data" : data })
return HttpResponse(response, mimetype="application/json")