连接到数据库并同时等待http请求

Connecting to db and waiting for http request simultaniusly

我刚开始在 python 上编程, 并编写了这段代码

from bottle import route, run, template
import pymongo
from pymongo import MongoClient


connection = MongoClient('localhost', 27017)
db = connection.tongler

@route('/hello/<name>')
def index(name):
    return template("Hello {{name}}", name=name)

run(host='localhost', port=8888)

print db

但它只在终止8888 监听器后才打印db 对象,如何在不等待http 服务器终止的情况下监听http 请求并执行其他操作?这是怎么做到的?

执行该文件后,要执行的第一个命令是 run 方法调用,它会启动一个进程,阻止应用程序的其余部分执行,直到它关闭。

要使用数据库,您必须根据请求或在 run 方法调用之前的某处执行数据库操作。

例如,假设您想显示该数据库中的记录,您可以这样做:

@route('/records/<id>')
def show_records(id=None):
    results = db.mycollection.find_one({'id': id})
    return template('Record: {{record}}', record=results)