使用bottle.py在浏览器上打印

时间:2016-05-06 17:48:32

标签: python function printing bottle

我是python的新手,特别是在使用模块时。我必须使用bottle.py模块。有没有办法在我的浏览器中打印一些东西,而不必返回它?更具体地说,我想要这样的东西:

import pymysql
from bottle import Bottle,run

app = Bottle()

@app.route('/conn')
def conn():
    **print("Trying to connect to database...")**
    try:
        conn = pymysql.connect(user="X",passwd="X",host="X",port=X,database="X")
    return "Connection succeded"
except:
    return "Oops...connection failed"

run(app, host='localhost',port = 8080)

如何打印类似"试图连接到数据库而不必返回它?

1 个答案:

答案 0 :(得分:3)

print语法/功能只会显示在不在浏览器上的stdout上。使用yield代替return来“逐步显示内容”(缺少更好的词语)。出于这个原因,我过去常常喜欢Bottle over Flask(尽管Flask有不同的做法)。

import pymysql
from bottle import Bottle,run

app = Bottle()

@app.route('/conn')
def conn():
    yield "Trying to connect to database..."
    try:
        conn = pymysql.connect(user="X",passwd="X",host="X",port=X,database="X")
        yield "Connection succeded"
    except:
        yield "Oops...connection failed"

run(app, host='localhost',port = 8080)