init_session.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. from flask import session as builtin_flask_session
  19. from airflow.configuration import conf
  20. from airflow.exceptions import AirflowConfigException
  21. from airflow.www.session import AirflowDatabaseSessionInterface, AirflowSecureCookieSessionInterface
  22. def init_airflow_session_interface(app):
  23. """Set airflow session interface."""
  24. config = app.config.copy()
  25. selected_backend = conf.get("webserver", "SESSION_BACKEND")
  26. # A bit of a misnomer - normally cookies expire whenever the browser is closed
  27. # or when they hit their expiry datetime, whichever comes first. "Permanent"
  28. # cookies only expire when they hit their expiry datetime, and can outlive
  29. # the browser being closed.
  30. permanent_cookie = config.get("SESSION_PERMANENT", True)
  31. if selected_backend == "securecookie":
  32. app.session_interface = AirflowSecureCookieSessionInterface()
  33. if permanent_cookie:
  34. def make_session_permanent():
  35. builtin_flask_session.permanent = True
  36. app.before_request(make_session_permanent)
  37. elif selected_backend == "database":
  38. app.session_interface = AirflowDatabaseSessionInterface(
  39. app=app,
  40. db=None,
  41. permanent=permanent_cookie,
  42. # Typically these would be configurable with Flask-Session,
  43. # but we will set them explicitly instead as they don't make
  44. # sense to have configurable in Airflow's use case
  45. table="session",
  46. key_prefix="",
  47. use_signer=True,
  48. )
  49. else:
  50. raise AirflowConfigException(
  51. "Unrecognized session backend specified in "
  52. f"web_server_session_backend: '{selected_backend}'. Please set "
  53. "this to either 'database' or 'securecookie'."
  54. )