【问题标题】:Connecting to db and waiting for http request simultaniusly连接db并同时等待http请求
【发布时间】:2016-07-15 14:37:38
【问题描述】:

我刚开始在 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 请求并执行其他操作?这是怎么做到的?

【问题讨论】:

  • 你要做什么操作?
  • 通常,如果您需要彼此独立地做某事,则必须使用线程或进程。有时候也可以使用某种形式的协同多线程,但是不知道bottle run方法是不是这样实现的(可能不是)。

标签: python pymongo bottle


【解决方案1】:

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

要使用数据库,您必须作为请求的结果或在run 方法调用之前的某个位置执行数据库操作。

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

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

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 1970-01-01
    • 2022-11-11
    • 2017-07-30
    • 2011-11-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2016-05-20
    相关资源
    最近更新 更多