Repository: apache/airflow

Issue:
is not bound to a Session; lazy load operation of attribute 'dag_model' 
### Apache Airflow version

2.2.3 (latest released)

### What happened

 An error occurred while browsing the page (/rendered-k8s?dag_id=xxx&task_id=yyy&execution_date=zzz):
```
Parent instance <TaskInstance at 0x7fb0b01df940> is not bound to a Session; lazy load operation of attribute 'dag_model' cannot proceed (Background on this error at: http://sqlalche.me/e/13/bhk3) Traceback (most recent call last):
    args=self.command_as_list(),
  File "/home/airflow/.local/lib/python3.9/site-packages/airflow/models/taskinstance.py", line 527, in command_as_list
    dag = self.dag_model
  File "/home/airflow/.local/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 294, in __get__
    return self.impl.get(instance_state(instance), dict_)
  File "/home/airflow/.local/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 730, in get
    value = self.callable_(state, passive)
  File "/home/airflow/.local/lib/python3.9/site-packages/sqlalchemy/orm/strategies.py", line 717, in _load_for_state
    raise orm_exc.DetachedInstanceError(
sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <TaskInstance at 0x7fb0b01df940> is not bound to a Session; lazy load operation of attribute 'dag_model' cannot proceed (Background on this error at: http://sqlalche.me/e/13/bhk3)
```


### What you expected to happen

_No response_

### How to reproduce

_No response_

### Operating System

NAME="CentOS Stream" VERSION="8"

### Versions of Apache Airflow Providers

```
apache-airflow-providers-cncf-kubernetes==2.2.0
apache-airflow-providers-elasticsearch==2.0.3
apache-airflow-providers-ftp==2.0.1
apache-airflow-providers-http==2.0.1
apache-airflow-providers-imap==2.0.1
apache-airflow-providers-mysql==2.1.1
apache-airflow-providers-postgres==2.3.0
apache-airflow-providers-sftp==2.1.1
apache-airflow-providers-sqlite==2.0.1
apache-airflow-providers-ssh==2.2.0
```

### Deployment

Other 3rd-party Helm chart

### Deployment details

_No response_

### Anything else

_No response_

### Are you willing to submit PR?

- [X] Yes I am willing to submit a PR!

### Code of Conduct

- [X] I agree to follow this project's [Code of Conduct](https://github.com/apache/airflow/blob/main/CODE_OF_CONDUCT.md)



Discussion:
I am seeing this issue too: 
![image](https://user-images.githubusercontent.com/42754983/149021907-bad97e01-4ec9-447e-abce-6c37df0287c5.png)


Resolving patch:
diff --git a/airflow/www/views.py b/airflow/www/views.py
--- a/airflow/www/views.py
+++ b/airflow/www/views.py
@@ -84,7 +84,7 @@
 from pygments.formatters import HtmlFormatter
 from sqlalchemy import Date, and_, desc, func, inspect, union_all
 from sqlalchemy.exc import IntegrityError
-from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import Session, joinedload
 from wtforms import SelectField, validators
 from wtforms.validators import InputRequired
 
@@ -114,7 +114,7 @@
 from airflow.utils.helpers import alchemy_to_dict
 from airflow.utils.log import secrets_masker
 from airflow.utils.log.log_reader import TaskLogReader
-from airflow.utils.session import create_session, provide_session
+from airflow.utils.session import NEW_SESSION, create_session, provide_session
 from airflow.utils.state import State, TaskInstanceState
 from airflow.utils.strings import to_boolean
 from airflow.utils.timezone import td_format, utcnow
@@ -1228,7 +1228,8 @@ def rendered_templates(self, session):
         ]
     )
     @action_logging
-    def rendered_k8s(self):
+    @provide_session
+    def rendered_k8s(self, session: Session = NEW_SESSION):
         """Get rendered k8s yaml."""
         if not settings.IS_K8S_OR_K8SCELERY_EXECUTOR:
             abort(404)
@@ -1239,14 +1240,15 @@ def rendered_k8s(self):
         form = DateTimeForm(data={'execution_date': dttm})
         root = request.args.get('root', '')
         logging.info("Retrieving rendered templates.")
-        dag = current_app.dag_bag.get_dag(dag_id)
+
+        dag: DAG = current_app.dag_bag.get_dag(dag_id)
         task = dag.get_task(task_id)
-        dag_run = dag.get_dagrun(execution_date=dttm)
-        ti = dag_run.get_task_instance(task_id=task.task_id)
+        dag_run = dag.get_dagrun(execution_date=dttm, session=session)
+        ti = dag_run.get_task_instance(task_id=task.task_id, session=session)
 
         pod_spec = None
         try:
-            pod_spec = ti.get_rendered_k8s_spec()
+            pod_spec = ti.get_rendered_k8s_spec(session=session)
         except AirflowException as e:
             msg = "Error rendering Kubernetes POD Spec: " + escape(e)
             if e.__cause__:


Test patch: