flet icon indicating copy to clipboard operation
flet copied to clipboard

add global context for session

Open 50Bytes-dev opened this issue 3 months ago • 4 comments

I was inspired by streamlit library, it has session_state, which is very convenient for me. I made something similar.

# main.py
import flet as ft
from .utils import test_global_context, test_global_context_async

async def main(page: ft.Page):
    print(ft.context.page.session_id)
    test_global_context()
    page.run_thread(test_global_context)
    page.run_task(test_global_context_async)

# utils.py
import flet as ft

async def test_global_context_async():
    print("Work async!", ft.context.page.session_id)

def test_global_context():
    print("Work!", ft.context.page.session_id)

50Bytes-dev avatar Mar 23 '24 18:03 50Bytes-dev

Thanks for your PR!

I've been wondering if your solution is the same as https://flet.dev/docs/guides/python/session-storage/ ?

FeodorFitsner avatar Mar 23 '24 18:03 FeodorFitsner

Thanks for your PR!

I've been wondering if your solution is the same as https://flet.dev/docs/guides/python/session-storage/ ?

No. My solution allows you to access the session without accessing the page variable. I solved the problem when I had to throw the page variable everywhere to access the session. Now you just need to import flet as ft and access ft.context.page from any file in the application.

50Bytes-dev avatar Mar 23 '24 18:03 50Bytes-dev

For example, my application uses the langchain library, which has a huge pile of tools and now instead of throwing a page variable into each tool I can just import flet and access flet.context.page from any tool.

50Bytes-dev avatar Mar 23 '24 18:03 50Bytes-dev

OK, interesting. Never used context vars before - time to learn! :)

FeodorFitsner avatar Mar 23 '24 18:03 FeodorFitsner

@50Bytes-dev, will you mind documenting this addition somewhere in the flet-docs? :)

ndonkoHenri avatar Apr 04 '24 12:04 ndonkoHenri

@50Bytes-dev, will you mind documenting this addition somewhere in the flet-docs? :)

I have no idea how best to do it and in what location. It would be easier for you to do it

50Bytes-dev avatar Apr 04 '24 12:04 50Bytes-dev

🆒

shenzifanhy avatar Apr 16 '24 02:04 shenzifanhy