I am trying to create a query form that allows me to query my mongo database and show the results up on a web page. I am using python with the bottle framework for this. Here a sample of my code
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
This prints out all the data in my mongo database to a web page using a bottle template, results.tpl
<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>
My problem is I don't want all the data showing only the data that is searched for. I want to be able to use the form to make a request that will get the data from mongo based on the keyword that was submitted. If this type of query web app can be done with other frameworks please let me know. If you have any good links to help me get an understanding of using request I'd love that too.
Thank you.
Pass the search to your route as a query string parameter. So for example if the request is:
http://www.blah.com/?search=foo
Then your code would be something like:
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
This may not work exactly as is but should be enough to get you on your way.