我通过我的代码生成了一个csv文件,生成后,它转到我的项目路径,我的项目名为sample
,所以文件路径为sample/output.csv
..我添加了一个函数下载,我在我的主函数(home)中调用了这个函数,但下载不起作用,我做错了什么?
def save_file(request):
# data = open(os.path.join(settings.PROJECT_PATH,'data/table.csv'),'r').read()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=output1.csv'
return response
def home(request):
if request.method=="POST":
img = UploadForm(request.POST, request.FILES)
if img.is_valid():
logging.warning('Watch out!') # will print a message to the console
# paramFile = request.FILES['pic']
paramFile =io.TextIOWrapper(request.FILES['pic'].file)
portfolio1 = csv.DictReader(paramFile)
print(type(paramFile))
users = []
# users = [row["BASE_NAME"] for row in csv_file]
# users = zip(*csv_file)
# users = [row[0] for row in csv_file]
# for row in portfolio1:
# users.append(row)
users = [row["BASE_NAME"] for row in portfolio1]
print(len(users))
my_list = users
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)
# print(1-similarity)
k = len(my_list)
dist1 = np.subtract(np.ones((k, k), dtype=np.float), similarity)
# dist1=similarity
# dist1.astype(float)
#print(dist1)
# print(cosine_similarity(tfidf_matrix[3:4], tfidf_matrix))
# float dist = 1 - similarity;
data2 = np.asarray(dist1)
arr_3d = data2.reshape((1, k, k))
# arr_3d= 1- arr_3d
#print(arr_3d)
no_clus = 40
for i in range(len(arr_3d)):
# print (i+1910)
# km = AgglomerativeClustering(n_clusters=no_clus, linkage='ward').fit(arr_3d[i])
km = AgglomerativeClustering(n_clusters=no_clus, linkage='average').fit(arr_3d[i])
# km = AgglomerativeClustering(n_clusters=no_clus, linkage='complete').fit(arr_3d[i])
# km = MeanShift()
# km = KMeans(n_clusters=no_clus, init='k-means++')
# km = MeanShift()
# km = km.fit(arr_3d[i])
# print km
labels = km.labels_
csvfile = r'C:\users\A6B0SZZ\PycharmProjects\sample\media\images\export.csv'
csv_input = pd.read_csv(csvfile, encoding='latin-1')
csv_input['cluster_ID'] = labels
csv_input['BASE_NAME'] = my_list
csv_input.to_csv('output.csv', index=False)
clus_groups = list()
for j in range(no_clus):
# print(" cluster no %i:%s" % (j, [my_list[i] for i, x in enumerate(labels) if x == j]))
list_of_ints = ([my_list[i] for 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))
# arr_3d= 1- arr_3d
no_clus = 5
for i in range(len(arr_3d)):
# print (i+1910)
# km = AgglomerativeClustering(n_clusters=no_clus, linkage='ward').fit(arr_3d[i])
# km = AgglomerativeClustering(n_clusters=no_clus, linkage='average').fit(arr_3d[i])
# km = AgglomerativeClustering(n_clusters=no_clus, linkage='complete').fit(arr_3d[i])
km = KMeans(n_clusters=5, init='k-means++')
km = km.fit(arr_3d[i])
# print km
labels2 = km.labels_
# error = km.inertia_
print(labels2)
labels = labels.tolist()
labels2 = labels2.tolist()
# new=list()
csv_input = pd.read_csv(r'C:\users\A6B0SZZ\PycharmProjects\sample\output.csv',encoding='latin-1')
labels1 = csv_input['cluster_ID']
new_list = []
for k in labels1:
new_list.append(labels2[k]) # lookup the value in list2 at the index given by list1
print(new_list)
print(len(new_list))
csv_input = pd.read_csv(r'C:\users\A6B0SZZ\PycharmProjects\sample\output.csv',encoding='latin-1')
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)
# my_list = portfolio
save_file(request)
# return HttpResponseRedirect(reverse('portfolio'))
return render(request, 'home.html', {'labels': labels})
else:
img=UploadForm()
images=Upload.objects.all()
return render(request,'home.html',{'form':img,'images':images})
我的home.html
是:
<!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 the CSV File to Run the Algorithm on:</h1>
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %} {{form}}
<input type="submit" value="Upload" />
</form>
{% for img in images %}
{{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>
({{img.upload_date}})<hr />
{% endfor %}
</div>
</body>
</html>
Url.py
:
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^upload/$', 'uploader.views.home', name='labels'),
url(r'^admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
编辑,我的功能现在是:但仍无效:
def save_file(request):
# data = open(os.path.join(settings.PROJECT_PATH,'data/table.csv'),'r').read()
# file_path = r'C:\users\A6B0SZZ\PycharmProjects\sample\output1.csv'
# fsock = open(file_path, "r")
fsock= pd.read_csv(r'C:\users\A6B0SZZ\PycharmProjects\sample\output1.csv', encoding='latin-1')
response = HttpResponse(fsock, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=output1.csv'
return response
答案 0 :(得分:1)
对于下载无效的主要问题,请查看this answer,因为您的HttpResponse的第一个参数应该是您实际发送的数据。
现在,你应该做的是看看与存储类的交互&amp; MEDIA_ROOT
。
这将使您的项目能够在服务器上本地或远程工作。看看您发布的内容,我假设您的settings.py
包含MEDIA_ROOT = 'C:\users\A6B0SZZ\PycharmProjects\sample\media'
您可能需要在settings.py
中考虑一些更通用,可重复使用的路径(取决于项目的结构,但这就是我所拥有的);
SETTINGS_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.abspath(os.path.join(SETTINGS_DIR, '../'))
BASE_DIR = os.path.abspath(os.path.join(PROJECT_DIR, '../'))
STATIC_ROOT = os.path.join(BASE_DIR, 'static-collection')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
这里的一些好的阅读将是Managing Files,它将带您了解创建文件的各种方法。访问他们的路径。
答案 1 :(得分:0)
如果要以这种方式将文件发送到浏览器,则该文件必须是webserver可直接访问的目录。在大多数情况下,存储所有Python代码的文件夹是不可访问的。
尝试将文件放在webserver可访问的目录中。另一种发送文件的方法是通过Python读取它并将其发送到内联,就像用户在这个问题中所做的那样:django return file over HttpResponse - file is not served correctly
答案 2 :(得分:0)
我使用FILEwrapper:
def send_file(request):
filename = settings.MEDIA_ROOT +'/'+ 'output1.csv'
#filename= r"C:\Users\A6B0SZZ\PycharmProjects\sample\media\output1.csv"
download_name ="output1.csv"
wrapper = FileWrapper(open(filename))
response = HttpResponse(wrapper,content_type='text/csv')
response['Content-Disposition'] = "attachment; filename=%s"%download_name
return response