带有参数“/api/squareroot/2.0”的路由,其中​​ 2.0 需要提取

Route with parameter "/api/squareroot/2.0" where 2.0 needs extracting

我有一个 Flask 视图,其中路线的最后一段需要是一个浮点值,该值由数学函数(例如平方根)进行运算。

如何在 @app.route 中编码?

#!/usr/bin/python2.7
from flask import Flask, request
#from functools import wraps
from flask.ext.httpauth import HTTPDigestAuth
import math

app = Flask(__name__)

app.config['SECRET_KEY'] = 'secret key here'
auth = HTTPDigestAuth()

users = {
    "robm":"welcome"
}

@auth.get_password
def get_pw(username):
    if username in users:
        return users.get(username)
    return None



@app.route('/api/square_root/<float:num>')
#@auth.login_required
def index():
    try:
        val = float(num) #float(request.args.get('num'))
        return str(math.sqrt(val)) 
    except:
        return "Sorry you need a parameter like /api/square_root?num=2.2" 

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=4567)
    #app.run(debug=True)

你快到了;您的视图函数需要接受参数:

@app.route('/api/square_root/<float:num>')
def index(num):
    #     ^^^
    # do something with num

Flask 已将值转换为浮点数,无需再次调用 float()。您会遇到的唯一异常是 ValueError,我将异常处理程序限制为:

@app.route('/api/square_root/<float:num>')
def index(num):
    try:
        return str(math.sqrt(num))
    except ValueError:
        return "We cannot create the square root of that number"