如何验证Flask应用程序中的URL参数? [英] How to validate URL parameters in Flask app?

查看:173
本文介绍了如何验证Flask应用程序中的URL参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Flask中编写了一个RESTful API。我可以通过请求对象访问URL参数。验证给定URL参数的最佳方法是什么?



例如:

  / places?zip = 97239#This是一个有效的过滤器
/ places?foo = bar#这不是一个有效的过滤器,404响应?

一个解决方案是搜索 request.args 并将每个条目与一组有效的URL参数进行比较。有没有更好的办法?



谢谢! 在字典中获取参数并使用性感来验证它。


$ b例如:

$ $ p $ parameters = Schema({
必需('zip'):Coerce int),
))

将会接受带有zip一个值可以强制为一个整数(所以1或1取决于你如何得到的值)。您可以使用以下方式进行验证:

 参数(my_get_params)#不应引发异常


I'm writing a RESTful API in Flask. I can access URL parameters via the Request Object. What is the best way to validate the given URL parameters?

For example:

/places?zip=97239 # This is a valid filter
/places?foo=bar   # This is not a valid filter, 404 response?

One solution is to search through request.args and compare each entry against a set of valid URL parameters. Is there a better way?

Thanks!

解决方案

Put the GET parameters in a dictionary and validate it using voluptuous.

For example:

parameters = Schema({
    Required('zip'): Coerce(int),
})

will accept any dictionary with a "zip" key that has a value that can be coerced to an integer (so either 1 or "1" depending on how you get the values). You can then validate it using:

parameters(my_get_params)  # should not raise an exception

这篇关于如何验证Flask应用程序中的URL参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆