我有一个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"