python+django從mongo讀取數據和圖片展示在html

  • 簡述:之前簡單筆記了抓取30條某房產中介房源信息和圖片存儲在mongo:https://blog.csdn.net/qq284489030/article/details/80840994,

  • 目標:現在要實現python+django從mongo讀取信息和圖片,展示在html頁面

  • 版本:python(3.6)+django(2.0)+mongoengine( 0.15.0)

  • 特別說明:只是簡單實現目標所述,代碼不規範、更好的思路,還請高手指點江山。
  • 思路:
  1. models中建模,對應創建房屋信息collection;
  2. views中獲取房屋信息;
  3. views中使用獲取該房屋信息對應的圖片,將圖片保存在本地,並將圖片路徑添加到房屋信息中;
  4. 使用paginator分頁,render傳給html
  5. 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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章