简体   繁体   English

Sanic 服务器中的可选参数

[英]Optional Parameters in Sanic Server

I want to take some optional body parameters in sanic server, just like we do in python.我想在 sanic 服务器中获取一些可选的 body 参数,就像我们在 python 中所做的那样。

Example in Python: Python 中的示例:

def func(a, b=1098):
    return a+b

print(func(2, 2))
print(func(1))

The same thing, I would like to do with sanic server request parameters.同样的事情,我想用 sanic 服务器请求参数来做。 For now, I just simply use try block but would like to know a more efficient approach of it.现在,我只是简单地使用 try 块,但想知道一种更有效的方法。

try:
    data = request.form['data'][0]
except Exception:
    data = 5

Thanks:)谢谢:)

Just like you would with any other dict object.就像您使用任何其他字典 object 一样。

data = int(request.form.get("data", 5))

https://sanic.dev/en/guide/basics/request.html#body https://sanic.dev/en/guide/basics/request.html#body

FYI - I wrapped it in int because form data usually will be a string otherwise.仅供参考 - 我将它包装在int中,因为表单数据通常是一个字符串,否则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM