FastAPI是否可以使用默认值的方式设置必需的查询参数?

huangapple go评论100阅读模式
英文:

Is it possible to have a required query parameter with a default value on FastAPI?

问题

  1. 我正在尝试使FastAPI中的查询参数成为必需的但给它一个默认值但我在他们的用户指南中找不到任何信息
  2. OpenAPI可以像这样做
  3. ```python
  4. parameters:
  5. - name: "some_name"
  6. in: "query"
  7. description: "a description"
  8. required: true
  9. type: "string"
  10. default: "First"
  11. enum:
  12. - "First"
  13. - "Second"
  14. - "Third"

如您所见,required 被分配为 true,我有一个默认值 ("first")。
使用 FastAPI,我有这个:

  1. class ModelNames(str, Enum):
  2. first = "first"
  3. second = "second"
  4. third = "third"
  5. @app.post("/path")
  6. async def this_function(
  7. modelInstance = Query(
  8. default=Required, # 我希望以某种方式将 "first" 和 Required 分配给 default
  9. description="a description"
  10. )
  11. ):
  12. return None
  1. 这是您的代码部分的翻译。
  2. <details>
  3. <summary>英文:</summary>
  4. I am trying to make a query parameter required but give it a default value on FastAPI, but i am not finding anything on their user guide.
  5. On openapi, it would be something like this:

parameters:
- name: "some_name"
in: "query"
description: "a description"
required: true
type: "string"
default: "First"
enum:
- "First"
- "Second"
- "Third"

  1. as you can see required is assigned to true and i have a default value (&quot;first&quot;)
  2. With fastapi i have this:

class ModelNames(str, Enum):
first = "first"
second = "second"
third = "third"

@app.post("/path")
async def this_function(
modelInstance = Query(
default=Required, # i would like to somehow assign "first" and Required to default
description="a description"
)
):
return None

  1. I&#39;ve tried directly assigning &quot;first&quot; but it makes it optional.
  2. </details>
  3. # 答案1
  4. **得分**: 4
  5. # Required parameter can't get default value by design
  6. 无法。
  7. 如果你想为自定义示例值的副作用定义默认值,请使用 example 参数。
  8. https://fastapi.tiangolo.com/tutorial/schema-extra-example/#example-and-examples-in-openapi
  9. <details>
  10. <summary>英文:</summary>
  11. # Required parameter can&#39;t get default value by design
  12. You can&#39;t.
  13. If you want to define a default value for the side effect of a custom example value, use the example parameter instead.
  14. https://fastapi.tiangolo.com/tutorial/schema-extra-example/#example-and-examples-in-openapi
  15. </details>

huangapple
  • 本文由 发表于 2023年2月14日 21:43:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定