我有一个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)
答案 0 :(得分:1)
你快到了;您的视图函数需要接受参数:
@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"