从mongodb atlas获取图像数据(二进制)到我的Django项目期间,我面临两种问题。
第一种情况
每当搜索http://127.0.0.1:8000/时,数据就会根据需要填充到html模板中,并显示长的跟踪信息,如here所示。
第二种情况
无论何时发送GET请求,浏览器都会通过在cmd或浏览器中不显示任何内容来保持无限加载。
在此处发布之前,我先搜索了错误并访问了github的django helpdesk,从中我无法找出问题的根源。
此处是要检查的代码 views.py
from django import template
from django.shortcuts import render
import gridfs
import pymongo
import random
register = template.Library()
client = pymongo.MongoClient('mongodb+srv://danial:1234@wearit-qyueb.mongodb.net/test?retryWrites=true&w=majority')
db=client.scraped_data.all_brands
fs = gridfs.GridFS(client.scraped_data)
# Create your views here.
def index(request):
template='products/products.html'
return render(request,template,{'documents': get_random()[:20], 'categories':categories(), 'brands': brands()})
def categories():
raw_data=get_random()
all_categories=[]
for doc in raw_data:
if doc.get('cat_name') not in all_categories:
all_categories.append(doc.get('cat_name'))
return all_categories
def query_form(request):
if request.method == 'GET':
query_dict=request.GET
select_category= query_dict.__getitem__('category-selected')
min_price=query_dict.__getitem__('min-price')
max_price=query_dict.__getitem__('max-price')
listOfDocumets=[]
if min_price!='' or max_price!='':
listOfDocumets=range(min_price,max_price, db.find({'cat_name': select_category}))
else:
listOfDocumets=list(db.find({'cat_name': select_category}))
random.shuffle(listOfDocumets)
return render(request, 'products/products.html',{"documents": listOfDocumets, 'categories':categories(), 'brands': brands()})
def search_query(request):
if request.method == 'GET':
query_dict=request.GET
select_brands= query_dict.__getitem__('search')
if select_brands!='':
listOfDocumets=list(db.find({'Brand': select_brands}))
if len(listOfDocumets)>0:
return render(request, 'products/products.html',{"documents": listOfDocumets, 'categories':categories()})
else:
return render(request,'products/errorpage.html')
else:
return(index(request))
def get_random():
rand_doc = db.aggregate([{ '$sample': { 'size': db.count() } }])
li=list(rand_doc)
return li
def range(min_price,max_price, cat):
listOfDocumets=list(cat)
if min_price!=None:
listOfDocumets=list(filter(lambda item:item.get('Price') >= int(min_price),listOfDocumets))
if max_price!=None:
listOfDocumets=list(filter(lambda item:item.get('Price') <= int(max_price),listOfDocumets))
return listOfDocumets
def brands():
raw_data=get_random()
all_brands=[]
for doc in raw_data:
if doc.get('Brand') not in all_brands:
all_brands.append(doc.get('Brand'))
return all_brands
这是template_filter.py
from django import template
from products.views import fs
import codecs
register = template.Library()
@register.filter
def get_item(dictionary, key):
if key=='data_chunk_id':
return get_file_object(dictionary.get(key))
else:
return dictionary.get(key)
@register.filter
def get_file_object(file_id):
out = fs.get(file_id[0]).read()
base64_data = codecs.encode(out, 'base64')
image = base64_data.decode('utf-8')
return image