Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
¿Cuál es la anotación de tipo para una vista Flask?

Quiero agregar anotaciones de tipo a una función de vista que devuelve una llamada para redirect . ¿Qué redirect el retorno y cómo agrego una anotación para eso a mi función de vista?

Pensé que podría ser str , o la función de redirect , pero no estoy seguro.

 def setalarm() -> redirect: # Retrieves the information to create new alarms. return redirect("/")
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

La respuesta directa es anotar su vista con lo que sea que esté escribiendo para devolver. En su ejemplo específico, la redirect devuelve una instancia de werkzeug.wrappers.Response .

 from werkzeug.wrappers import Response def set_alarm() -> Response: return redirect()

En lugar de averiguar qué devuelve una función dada para anotar su vista, puede parecer más fácil crear una anotación de Union que represente cualquier cosa que una vista de Flask pueda devolver. Sin embargo, Flask no proporciona información de escritura y su naturaleza dinámica dificulta la representación de las posibilidades.

De forma predeterminada, una vista Flask puede devolver:

  • Una str o bytes .
  • Una subclase de werkzeug.wrappers.BaseResponse .
  • Una tupla en uno de estos formularios, donde data son cualquiera de los otros tipos que puede devolver una vista Flask:
    • (data,)
    • (data, status) , donde status puede ser un int o un str o bytes .
    • (data, headers) , donde headers es un dictado, iterable de tuplas (key, value) , o un objeto werkzeug.datastructures.Headers .
    • (data, status, headers)
  • Un dict para convertir a JSON. Los valores deben ser tipos compatibles con app.json_encoder .
  • Un WSGI invocable.

Flask puede admitir más o diferentes tipos de devolución anulando el método Flask.make_response . Los datos que puede serializar a JSON se pueden ampliar anulando Flask.json_encoder . Si ha personalizado el comportamiento de Flask, también deberá personalizar la información de tipo.

Aquí hay un view_return_type que representa los posibles tipos de devolución de una vista de Flask, ignorando la tipificación de JSON . Una vez que defina el tipo, puede anotar cualquier vista con él.

 import typing as t from werkzeug.datastructures import Headers from werkzeug.wrappers import BaseResponse _str_bytes = t.Union[str, bytes] _data_type = t.Union[ _str_bytes, BaseResponse, t.Dict[str, t.Any], t.Callable[ [t.Dict[str, t.Any], t.Callable[[str, t.List[t.Tuple[str, str]]], None]], t.Iterable[bytes] ], ] _status_type = t.Union[int, _str_bytes] _headers_type = t.Union[ Headers, t.Dict[_str_bytes, _str_bytes], t.Iterable[t.Tuple[_str_bytes, _str_bytes]], ] view_return_type = t.Union[ _data_type, t.Tuple[_data_type], t.Tuple[_data_type, _status_type], t.Tuple[_data_type, _headers_type], t.Tuple[_data_type, _status_type, _headers_type], ]
 @app.route("/users/<int:id>/") def user_detail(id: int) -> view_return_type: ...
over 4 years ago · Santiago Trujillo Report

0

En Flask 2 puedes usar flask.typing.ResponseReturnValue .

 from flask.typing import ResponseReturnValue @app.get("/") def index() -> ResponseReturnValue: return "OK"
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!