我正在尝试学习webpy,所以我可以在运行Javascript的浏览器窗口中调用一些使用pymongo编写的python程序。我对Web编程一般都很陌生。现在,我试图通过简单地调整此处的示例教程文件来开始:http://kooneiform.wordpress.com/2010/02/28/python-and-ajax-for-beginners-with-webpy-and-jquery/
我已经在浏览器窗口中成功运行了示例文件。然后我调整app.py看起来像这样:
import web
import datetime
import time
from collections import OrderedDict
from math import *
import sys
import operator
import pymongo
def make_text(string):
return string
urls = ('/', 'tutorial')
render = web.template.render('templates/')
app = web.application(urls, globals())
my_form = web.form.Form(
web.form.Textbox('', class_='textfield', id='textfield'),
)
def check_users(user_ids):
""" helper function for user_id-based queries """
connection = MongoClient()
db = connection.test
if user_ids == "all":
user_list = []
for user_id in db.user_ids.find():
user_list.append(user_id["user_id"])
user_ids = user_list
return user_ids
class tutorial:
def GET(self):
form = my_form()
return render.tutorial(form, "Your text goes here.")
def POST(self):
form = my_form()
form.validates()
s = form.value['textfield']
users = check_users(s)
return make_text(users)
if __name__ == '__main__':
app.run()
当我运行它时,我得到"名称错误:没有定义MongoClient。"
如何让webpy打开Mongo连接,以便我可以从浏览器运行查询?
答案 0 :(得分:0)
您需要导入您打算使用的任何模块/类。在这种情况下,替换
import pymongo
与
from pymongo import MongoClient
或者,因为您已经导入了pymongo
模块,所以您只需执行
connection = pymongo.MongoClient()