簡體   English   中英

如何使用python bottle框架查詢mongo數據庫

[英]How to Query mongo database using python bottle framework

我正在嘗試創建一個查詢表單,允許我查詢我的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獲取數據。 如果這種類型的查詢Web應用程序可以使用其他框架,請告訴我。 如果你有任何好的鏈接來幫助我理解使用請求我也會喜歡它。

謝謝。

將搜索作為查詢字符串參數傳遞給您的路徑。 例如,如果請求是:

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

這可能不完全正常,但應該足以讓你繼續前進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM