python - Django Biginner - How to connect my algorithm code in django -


this might simple, i'm quite new django. want build app make user upload csv file, run algorithm on it, , make output file available downloaded user. started uploading file thing , looks it's working, , have algorithm code ready, however, i'm not sure how connect algorithm code, not sure how make function include that, , need new url each uploading,running algorithm , downloading? 1 url displays 3 of them. here project files , app, model.py:

from django.db import models django.forms import modelform  class upload(models.model):     pic = models.filefield("csv file", upload_to="images/")     upload_date=models.datetimefield(auto_now_add =true)  # fileupload form class. class uploadform(modelform):     class meta:         model = upload         fields = '__all__'  # or list of fields want include in form 

view.py:

from __future__ import division django.shortcuts import render uploader.models import uploadform,upload io import textiowrapper io import stringio django.http import httpresponseredirect django.core.urlresolvers import reverse import csv import logging def home(request):     if request.method=="post":         img = uploadform(request.post, request.files)         if img.is_valid():             img.save()           #  request.files['pic'].open("f")           #  portfolio = csv.dictreader(request.files['uploadfile'].file)             #file =request.files['pic']             file1 = textiowrapper(request.files['pic'].file)            # reader = stringio(file.read().decode())             reader = file1.read()             file1.seek(0)             portfolio = csv.dictreader(reader)             print(portfolio)             #with open(reader) f:             my_list=[]             import pdb;pdb.set_trace()           #  open(portfolio) f:             my_list = [row["base_name"] row in portfolio]           #  row in portfolio:              #   my_list = [row["base_name"]]               #             print(my_list)             logging.warning('watch out!')  # print message console           #   row in reader:          #       print (row)         #else:          #   print (img.errors)          #   print  (request.files)            # img.save()             #file = request.files[pic]            # open(file) f:                # my_list = [row["base_name"] row in dictreader(f)]              return httpresponseredirect(reverse('imageupload'))     else:         img=uploadform()     images=upload.objects.all()     return render(request,'home.html',{'form':img,'images':images}) 

my home.html file:

<!doctype html> <html lang="en"> <head>     <meta charset="utf-8">     <title>title</title> </head> <body> <div style="padding:40px;margin:40px;border:1px solid #ccc">     <h1>upload csv file</h1>     <form action="#" method="post" enctype="multipart/form-data">         {% csrf_token %} {{form}}         <input type="submit" value="upload" />     </form>     {% img in images %}         {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>         ({{img.upload_date}})<hr />     {% endfor %} </div> </body> </html> 

and url.py

from django.conf.urls import url django.contrib import admin django.conf import settings django.conf.urls.static import static  urlpatterns = [     url(r'^upload/$', 'uploader.views.home', name='imageupload'),     url(r'^admin/', admin.site.urls), ]+ static(settings.media_url, document_root=settings.media_root) 

my algorithm code want implement is:

with open("export.csv") f:     my_list = [row["base_name"] row in dictreader(f)] # codecsvmodel.import_from_file(file) vectorizer = countvectorizer() dtm = vectorizer.fit_transform(my_list)  lsa = truncatedsvd(n_components=100) dtm_lsa = lsa.fit_transform(dtm) dtm_lsa = normalizer(copy=false).fit_transform(dtm_lsa) similarity = np.asarray(numpy.asmatrix(dtm_lsa) * numpy.asmatrix(dtm_lsa).t) k = len(my_list) dist1 = np.subtract(np.ones((k, k), dtype=np.float), similarity) data2 = np.asarray(dist1) arr_3d = data2.reshape((1, k, k))  no_clus = 1500 in range(len(arr_3d)):     km = agglomerativeclustering(n_clusters=no_clus, linkage='average').fit(arr_3d[i])      labels = km.labels_  csvfile = file csv_input = pd.read_csv(csvfile) csv_input['cluster_id'] = labels csv_input['base_name'] = my_list csv_input.to_csv('output.csv', index=false) clus_groups = list() j in range(no_clus):     list_of_ints = ([my_list[i] i, x in enumerate(labels) if x == j])     clus_groups.append('  '.join(list_of_ints)) vectorizer = countvectorizer() dtm = vectorizer.fit_transform(my_list)  lsa = truncatedsvd(n_components=100) dtm_lsa = lsa.fit_transform(dtm) dtm_lsa = normalizer(copy=false).fit_transform(dtm_lsa) similarity = np.asarray(numpy.asmatrix(dtm_lsa) * numpy.asmatrix(dtm_lsa).t) k = len(my_list) dist1 = 1 - similarity data2 = np.asarray(dist1) arr_3d = data2.reshape((1, k, k))  no_clus = 5 in range(len(arr_3d)):     km = kmeans(n_clusters=5, init='k-means++')     km = km.fit(arr_3d[i])     labels2 = km.labels_  labels = labels.tolist() labels2 = labels2.tolist()  csv_input = pd.read_csv('output.csv') labels1 = csv_input['cluster_id'] new_list = [] k in labels1:     new_list.append(labels2[k])  # lookup value in list2 @ index given list1 csv_input = pd.read_csv('output.csv') csv_input['cluster_id'] = labels csv_input['base_name'] = my_list csv_input['user_map'] = new_list csv_input.to_csv('output1.csv', index=false) 

i tried in view.py make my_list , start, not sure if got my_list right since no print statements showing, want make function inside view implement algorithm above, , how link file got home function new function of algorithm, need function downloading thing, , not sure templates. i'm kinda lost , did uploading function example online. appreciate help.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -