【问题标题】:How to Query mongo database using python bottle framework如何使用 python Bottle 框架查询 mongo 数据库
【发布时间】:2019-01-01 11:26:39
【问题描述】:

我正在尝试创建一个查询表单,允许我查询我的 mongo 数据库并将结果显示在网页上。我正在为此使用带有瓶子框架的python。这是我的代码示例

import bottle
import pymongo


@bottle.route('/')
def home_page():

#connect to mongodb 
connection = pymongo.MongoClient('localhost', 27017)
#connect to mydb database
db = connection.TestCollection
#connect to collection
data = db.TestData
#finding all data
mydata = data.find()

result = []
for i in mydata:
    result.append([i['User'],i['Email'],i['Title']]) 


output = bottle.template('results.tpl', rows=result)

return output

这会使用瓶子模板 results.tpl 将我的 mongo 数据库中的所有数据打印到网页中

    <h1>Results</h1>


    <form action="/" method="GET">
    enter query: <input name="result" type="text" />
    <input type="submit" /><br/>
    </form>



    <table border="1">
    <tbody>
    <tr><th>User</th><th>Email</th><th>Title</th></tr>
    %for row in rows:
    <tr>
    %for col in row:
        <td>{{col}}</td>
    %end
    </tr>
%end
<tbody>
</table>

我的问题是我不希望所有数据只显示搜索到的数据。我希望能够使用表单发出请求,该请求将根据提交的关键字从 mongo 获取数据。如果这种类型的查询网络应用程序可以使用其他框架完成,请告诉我。如果您有任何好的链接来帮助我了解使用请求,我也会很喜欢。

谢谢。

【问题讨论】:

    标签: python mongodb request bottle


    【解决方案1】:

    将搜索作为查询字符串参数传递给您的路线。例如,如果请求是:

    http://www.blah.com/?search=foo
    

    那么你的代码会是这样的:

    import re
    
    from bottle import route, request
    
    @bottle.route('/')
    def home_page():
        search = request.query['search']
        search_re = re.compile(search)
    
        # mongo stuff
    
        my_data = data.find({
          '$or': [
              {'User': {'$regex': search_re}},
              {'Email': {'$regex': search_re}},
              {'Title': {'$regex': search_re}}
          ]
        })
    
        # do stuff with my_data and template
    
        return output
    

    这可能无法完全按原样工作,但应该足以让您顺利上路。

    【讨论】:

      猜你喜欢
      • 2015-07-15
      • 2013-04-16
      • 1970-01-01
      • 2015-10-10
      • 2012-10-14
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多