Skip to main content
 首页 » 编程设计

python之我在从 mongodb 查询数据并渲染到 Flask 时遇到问题

2024年10月01日8myhome

我在 MongoDB 中有我知道存在的数据,因为我可以从外部查询我的 Flask 应用程序。

查询:

from pymongo import MongoClient 
import pprint 
client = MongoClient() 
db = client.reqdata 
 
cursor = db.req_data.find() 
 
for document in cursor: 
    pprint.pprint(document) 

示例结果

{'_id': ObjectId('5a0f3abf2d6a8810fbc8e352'), 
 'req': {'HiringManagerEmailId': 'Fred.Smith@company.com', 
         'HiringManagerEmployeeId': 353585, 
         'HiringManagerName': 'Fred Smith', 
         'HiringManagerSystemId': 146472, 
         'HotJob': 'No', 
         'JobDescription': 'You will collaborate with colleagues from ' 
                           'North America and/or The Company ' 
                           'on national and international ' 
                           'client projects.<br> <br>Together with our ' 
                           'clients, you will develop superior IT concepts ' 
                           'and architecture solutions as well as support ' 
                           'technical implementations actively and on site, ' 
                           'applying your sound technical know-how, your ' 
                           'understanding of business contexts, and your ' 
                           'analytical and conceptual ' 
                           'skills.<br><br>Company provides technology ' 
                           'consulting services to clients on the following ' 
                           'topics:<br> <ul dir="ltr"><li> Management of ' 
                           'large-scale projects</li><li> Restructuring of ' 
                           'IT processes and organization</li><li> ' 
                           'Functional and technical support of mergers and ' 
                           'acquisitions</li><li> Analysis of IT and ' 
                           'software architecture weaknesses</li><li> ' 
                           'Specification and implementation of IT ' 
                           'architectures</li><li> Product evaluation, such ' 
                           'as core systems</li><li> Technical concept ' 
                           'development and design of software ' 
                           'solutions</li><li> Quality assurance for IT ' 
                           'implementation</li><li> Design and ' 
                           'implementation of feasibility studies</li><li> ' 
                           'Load and performance tests</li></ul>', 
         'JobDetailLink': 'https://someurl.foo.com/', 
         'LastUpdated': '16-Nov-2017', 
         'Question': ['Senior Consultant', 
                      'Core Technology', 
                      'North America', 
                      'United States', 
                      'New York', 
                      'Full time', 
                      '5390BR'], 
         'RecruiterEmailId': 'Fred.Smith@company.com', 
         'RecruiterEmployeeId': 353585, 
         'RecruiterName': 'Fred Smith', 
         'RecruiterSystemId': 146472}, 
 'timestamp': '2017-17-17 14:38:37'} 

当我尝试将相同的代码插入到我的 Flask 应用程序中时,我可以获得呈现到 ~/index 页面的文档的准确计数,但似乎无法获取要呈现到 ~/mongoreqs 页面的数据。

flask 代码

from flask import Flask, render_template,request,redirect,url_for # For flask implementation 
from pymongo import MongoClient # Database connector 
from bson.objectid import ObjectId # For ObjectId to work 
 
client = MongoClient()    #Configure the connection to the database 
db = client.reqdata    #Select the database 
##reqs = db.req_data.find() 
 
app = Flask(__name__) 
title = "Req Search with Flask" 
heading = "Req Search" 
 
 
 
@app.route('/') 
@app.route('/index') 
 
def index(): 
##    reqdb = db.req_data 
    reqcount = db.req_data.count() 
    return render_template('index.html', 
                          title='Home', 
                           reqcount = reqcount) 
 
@app.route('/mongoreqs', methods=['GET']) 
def mongo_reqs(): 
##    reqdb = db.req_data #Select the collection 
##    client = MongoClient()    #Configure the connection to the database 
##    db = client.reqdata  
    reqs = db.req_data.find({}) 
    return render_template('mongoreqs.html', 
                           title="Reqs in Mongo DB", 
                           reqs=reqs) 
 
 
if __name__ == "__main__": 
    app.run(debug=True) 

mongoreqs.html

<!-- extend from base layout --> 
 
{% extends "base.html" %} 
 
 
{% block content %} 
 
    <h2>Open Requisitions MONGO DB </h2> 
    <table> 
    <th><strong>Question</strong></th> 
    <th><strong>URL </strong></th> 
    <th><strong>Job Description</strong></th> 
 
    {% for req in reqs %} 
            <tr> 
            <td>{{ req["Question"] }}</td> 
            <td><a href="{{ req['JobDetailLink'] }}" target="blank">Job Apply Link</a></td> 
            </th><td>{{ req['JobDescription']|safe }}</td> 
 
        </tr> 
    {% endfor %} 
    </table> 
{% endblock %} 

任何想法或帮助将不胜感激。

请您参考如下方法:

从您的文档的 pretty-print 来看,信息嵌套在 req 中。

在您的模板中,使用:

{{ req.req.Question }} 
 
{{ req.req.JobDetailLink }}     
 
{{ req.req.JobDescription }} 

或者更好的办法是编写一个投影来取消嵌套这些属性,然后您就可以按原样使用当前模板。

projection = { 
    'Question': '$req.Question', 
    'JobDetailLink': '$req.JobDetailLink', 
    'JobDescription': '$req.JobDescription', 
} 
cursor = db.find({}, projection)