使用AJAX从Bottlepy服务器获取数据

0 投票
1 回答
720 浏览
提问于 2025-04-18 10:45

我正在尝试从一个使用Bottle框架的服务器获取json数据,并把它显示在网页上。我想先实现一个简单的版本,所以一开始只用了字符串。但是似乎没有任何反应。以下是我的代码 -

HTML(包括js) -

<!DOCTYPE>
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<body>
<script>
function print()
{
    $(document).ready(function(){
        $.get('http://localhost:8080/check', function(result){
            alert('success');
            $('#main').html(result);
        });
    });
}

print();
</script></body>
</html>

Python代码 -

from bottle import Bottle, route, get,request, response, run, template

app = Bottle()

@app.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'

# a simple json test main page
str = "Hello"
@route('/')                   #irrelevant to this question. Used this to check server...
def test():
    return template('file', str)

@app.get('/check')
def showAll():
    return str

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

我需要做些什么才能访问服务器上的数据? 注意:HTML是一个单独的文件,我希望这个代码能在任何位置都能正常工作。

另外,如果这样做不行,我该如何借助模板来实现呢?

1 个回答

0

你的问题来源于对Bottle应用的一些误解。

每当你使用 @route 时,Bottle会为你创建一个默认的应用程序 (更多信息),并在后续的调用中隐式地重用这个默认应用。这种默认应用的行为在很多功能中都存在(包括 hookrun)。

关键是:

app = Bottle() # creates an explicit app

@route('/')    # adds the route to the default app

@app.hook('after-request')  # adds the hook to the explicit app

run(...) # runs the default app, the hook is not used

要解决你的问题,你有两个选择:

  • 去掉对显式应用的任何提及;
  • 始终显式使用应用。

我发现显式使用应用让创建子应用变得更简单,而且整体上更清楚发生了什么。

新代码:

import bottle
from bottle import response, template, run

app = bottle.Bottle()

@app.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'

# a simple json test main page
str = "Hello"
@app.route('/')                   #irrelevant to this question. Used this to check server...
def test():
    return template('file', str)

@app.get('/check')
def showAll():
    return str

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

撰写回答