python: 无法从网络浏览器调用文件中的函数

python: can't call the function in the file from the webbrowser

我想在 python 中使用 Bottle 框架制作一个 RESTful 网络服务。在其中我有一个 CSV 文件,其中包含纬度和局域网的数据。每次有人从该文件中搜索特定邮政编码时,我都必须获取该数据并将其显示在浏览器上。 所以,到目前为止我已经做到了。

 from bottle import route, run, request


@route('/')
def index():
    """ Display welcome & instruction messages """
    return "<p>Welcome to my extra simple bottle.py powered server!</p> \
           <p>The Web service can find a location from csv file \
           The way to invoke is :\
       <ul> \
              <li>http://localhost:8080/getlocation?postcode=xxxx</li>\
       </ul> \
       xxxx are the postcode you want to search."

@route('/getlocation/<postcode>')
def getlocation(postcode):
    csv_file = csv.reader(open('clinic_locations.csv', "r"), delimiter=",")
    #return{clinicname, latitude, longitude, email, state}
    for row in csv_file:
        if postcode == row[6]:
            return{row[3], row[8], row[9], row[7], row[5]}

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

在此我的浏览器出现错误

Sorry, the requested URL 'http://localhost:8080/getlocation?postcode=4000' caused an error:

我不知道我哪里错了。 谁能帮帮我!

您的路线是 /getlocation/<postcode>,而不是 /getlocation?postcode=<postcode>

您似乎是在浏览器中执行此操作:

http://localhost:8080/getlocation?postcode=4000

你试过了吗:

http://localhost:8080/getlocation/4000 

?

下面有两个示例,路由 [1] 中的动态参数和查询参数 [2]:

更新

import json
from bottle import route, request, response, run, template, abort, error

@error(500)
@error(404)
@error(400)
def error_handler(error):
    try:
        error_details =  {"error_code": error.status_code, "message":    error.body}
    except:
        error_details =  {"error_code": 500, "message": error.exception}
    return json.dumps(error_details)

"""
    Example of try catch with bottle abort to handle
    custom error messages in the 'error_handler' above.
"""
@route("/")
def index():
try:
    raise Exception('A generic exception')
except Exception as ex:
    abort(500, ex.args[0])

@route("/greet/<name>")
def greet(name):
    return template("Greetings <b>{{name}}</b>", name=name)

@route("/greet")
def greet():
    if 'name' not in request.query:
        abort(400, "'name' parameter is missing...")    
    return template("Greetings <b>{{name}}</b>", name=request.query['name'])

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

测试上面的代码: