- 简述:之前简单笔记了抓取30条某房产中介房源信息和图片存储在mongo:https://blog.csdn.net/qq284489030/article/details/80840994,
- 目标:现在要实现python+django从mongo读取信息和图片,展示在html页面
- 版本:python(3.6)+django(2.0)+mongoengine( 0.15.0)
- 特别说明:只是简单实现目标所述,代码不规范、更好的思路,还请高手指点江山。
- 思路:
- models中建模,对应创建房屋信息collection;
- views中获取房屋信息;
- views中使用获取该房屋信息对应的图片,将图片保存在本地,并将图片路径添加到房屋信息中;
- 使用paginator分页,render传给html
- html中加载展示
- 结构图
- settings.py文件内容及说明
import mongoengine #ys from gridfs import * mongo_con = mongoengine.connect('test7',host='127.0.0.1',port=27017) mongo_db = mongo_con.test7 fs = GridFS(mongo_db,collection='coll_image')#mongo图片连接 DATABASES = { 'default': { # 'ENGINE': 'mypackage.backends.whatever', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }#注释掉默认数据库连接 #ys 图片路径 STATIC_ROOT = os.path.join(os.path.dirname(__file__),'static')STATIC_ROOT_IMG = os.path.join(os.path.dirname(__file__),'static/images')STATICFILES_DIRS = ( ('css',os.path.join(STATIC_ROOT,'css').replace('\\','/') ), ('js',os.path.join(STATIC_ROOT,'js').replace('\\','/') ), ('images',os.path.join(STATIC_ROOT,'images').replace('\\','/') ), ('upload',os.path.join(STATIC_ROOT,'upload').replace('\\','/') ),) #django静态文件加载路径
- models.py
from mongoengine import *
from gridfs import *
class test(Document):
_id = ObjectIdField(required=True)
title = StringField(required=True)
address = StringField(required=True)
flood = StringField(required=True)
followInfo = StringField(required=True)
img_url = StringField(required=True)
img_id = ObjectIdField(required=True)
# creat_time = DateTimeField(required=True)
meta = {'collection':'test'} #指明连接的表,各字段对应collection中房屋信息
gridfs bukects中图片暂时没找到建模方式,在views中读取图片到本地- views.py
from app_demo.models import test,coll_image #引用models.py中的类
from web_ys.settings import * #引入工程配置文件
from urllib import parse
def index_fenye(request):
response_dic_context = {} #{'houses':response_list} ; render 返回字典类型,
global response_list #页面上多个房屋信息的列表,每个房屋信息类型是dict
response_list = []
for t in test.objects(): #遍历mongo中所有房屋信息
response_dic = t._data #每个房屋的所有信息赋值给字典 response_dic
# t.img_id 是房屋信息中对应的图片存储id,
# 使用setting定义的fs从gridfs bukects中查找id属于该房屋的图片
for img_img in fs.find({'_id': t.img_id}, no_cursor_timeout=True):
# 拼接 存放数据库生成图片的本地路径
img_path = (STATICFILES_DIRS[2][1] + '/' + str(t.img_id) + '.jpg').replace('/', '\\')
# 读取并保存图片到本地路径下
with open(img_path, mode='wb') as f:
f.write(img_img.read())
f.flush()
f.close()
# 图片相对路径,添加到房屋信息字典中,在html加载
response_dic['image'] = 'images/' + str(t.img_id) + '.jpg'
response_list.append(response_dic)
response_dic_context['houses'] = response_list
contact_list = response_list #开始没用分页,直接render中返回response_dic_context;后来添加了分页
paginator = Paginator(contact_list, 8) # 每页显示数目
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages)
return render(request, 'index_fenye.html', {'contacts': contacts})
- index_fenye.html
<html>
<head>
<title>Django Page Title</title>
</head>
<body>
<form method="get">
{# staticfiles 加载静态资源#}
{% load staticfiles %}
{# 遍历返回的当前页的所有房屋资料#}
{% for d in contacts %}
{# 遍历每个房屋信息中的每条信息#}
{% for k,v in d.items %}
{% ifequal k "title" %}
<div>【title】: {{ v }} </div>
{% endifequal %}
{% ifequal k "address" %}
<div>【address】: {{ v }} </div>
{% endifequal %}
{% ifequal k "flood" %}
<div>【flood】: {{ v }} </div>
{% endifequal %}
{% ifequal k "followInfo" %}
<div>【followInfo】: {{ v }} </div>
{% endifequal %}
{% ifequal k "img_url" %}
<div>【img_url】:{{ v }} </div>
{% endifequal %}
{% ifequal k "img_id" %}
<div>【img_id】: {{ v }} </div>
{% endifequal %}
{# #特别注意图片路径引用#}
{# {% ifequal k "image" %}#}
{# 【图片】:<image src="{% static v %}"> </image>#}
{# {% endifequal %}#}
{% ifequal k "image" %}
【图片】:<image src="{% static v %}"></image>
{% endifequal %}
{% endfor %}
<ul>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</ul>
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
<a href="?page={{ contacts.previous_page_number }}">previous </a>
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
<a href="?page={{ contacts.next_page_number }}">next </a>
{% endif %}
</span>
</div>
{% csrf_token %}
</form>
</body>
</html>
- 效果
项目上传到 https://download.csdn.net/download/qq284489030/10535190