muffin-session


Namemuffin-session JSON
Version 2.4.1 PyPI version JSON
download
home_pagehttps://github.com/klen/muffin-session
SummarySigned Cookie-Based HTTP sessions for the Muffin framework
upload_time2023-06-21 06:41:45
maintainer
docs_urlNone
authorKirill Klenov
requires_python>=3.8,<4.0
licenseMIT
keywords asyncio trio asgi muffin web cookie sessions session
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Muffin-Session
##############

.. _description:

**Muffin-Session** -- Cookie-Based HTTP sessions for Muffin_ framework

.. _badges:

.. image:: https://github.com/klen/muffin-session/workflows/tests/badge.svg
    :target: https://github.com/klen/muffin-session/actions
    :alt: Tests Status

.. image:: https://img.shields.io/pypi/v/muffin-session
    :target: https://pypi.org/project/muffin-session/
    :alt: PYPI Version

.. image:: https://img.shields.io/pypi/pyversions/muffin-session
    :target: https://pypi.org/project/muffin-session/
    :alt: Python Versions

.. _contents:

.. contents::

Features
========

* Supports base64 sessions
* Supports ``JWT`` signed sessions
* Supports ``Fernet`` encrypted sessions

.. _requirements:

Requirements
=============

- python >= 3.8

.. _installation:

Installation
=============

**Muffin-Session** should be installed using pip: ::

    pip install muffin-session

    # Optional extras
    pip install muffin-session[fernet]

.. _usage:

Usage
=====

1. Use it manually

.. code-block:: python

    from muffin import Application, ResponseHTML
    from muffin_session import Plugin as Session

    # Create Muffin Application
    app = Application('example')

    # Initialize the plugin
    # As alternative: session = Session(app, **options)
    session = Session()
    session.setup(app, secret_key='REALLY_SECRET_KEY_FOR_SIGN_YOUR_SESSIONS')

    # Use it inside your handlers
    @app.route('/update')
    async def update_session(request):
        ses = session.load_from_request(request)
        ses['var'] = 'value'
        response = ResponseHTML('Session has been updated')
        session.save_to_response(ses, response)
        return res

    @app.route('/load')
    async def load_session(request):
        ses = session.load_from_request(request)
        return ses.get('var')

2. Auto manage sessions (with middleware)

.. code-block:: python

    from muffin import Application, ResponseHTML
    from muffin_session import Plugin as Session

    # Create Muffin Application
    app = Application('example')

    # Initialize the plugin
    # As alternative: session = Session(app, **options)
    session = Session()
    session.setup(app, secret_key='REALLY_SECRET_KEY_FOR_SIGN_YOUR_SESSIONS', auto_manage=True)

    # Use it inside your handlers
    @app.route('/update')
    async def update_session(request):
        request.session['var'] = 'value'
        return 'Session has been updated'

    @app.route('/load')
    async def load_session(request):
        return request.session.get('var')


Options
-------

=========================== =========================== ===========================
Name                        Default value               Description
--------------------------- --------------------------- ---------------------------
**session_type**            ``"jwt"``                   Session type (``base64|jwt|fernet``)
**secret_key**              ``"InsecureSecret"``        A secret code to sign sessions
**auto_manage**             ``False``                   Load/Save sessions automatically. Session will be loaded into ``request.session``
**cookie_name**             ``"session"``               Sessions's cookie name (``session``)
**cookie_params**                                       Sessions's cookie params (``{'path': '/', 'max-age': None, 'samesite': 'lax', 'secure': False}``)
**default_user_checker**    ``lambda x: True``          A function to check a logged user
**login_url**               ``"/login"``                An URL to redirect anonymous users (it may be a function which accept ``Request`` and returns a string)
=========================== =========================== ===========================


You are able to provide the options when you are initiliazing the plugin:

.. code-block:: python

    session.setup(app, secret_key='123455', cookie_name='info')


Or setup it inside ``Muffin.Application`` config using the ``SESSION_`` prefix:

.. code-block:: python

   SESSION_SECRET_KEY = '123455'

   SESSION_COOKIE_NAME = 'info'

``Muffin.Application`` configuration options are case insensitive


Examples
--------

.. code-block:: python

    from muffin import Application, ResponseHTML
    from muffin_session import Plugin as Session

    # Create Muffin Application
    app = Application('example')

    # Initialize the plugin
    # As alternative: session = Session(app, **options)
    session = Session()
    session.setup(app, secret_key='REALLY_SECRET_KEY_FOR_SIGN_YOUR_SESSIONS', auto_manage=True)

    @session.user_loader
    async def load_user(ident):
        """Define your own user loader. """
        return await my_database_load_user_by_id(ident)

    @app.register('/session')
    async def get_session(request):
        """ Load session and return it as JSON. """
        return dict(request.session)

    @app.register('/admin')
    @session.user_pass(lambda user: user.is_admin)
    async def admin(request):
        """Awailable for admins only. """
        return 'TOP SECRET'

    @app.register('/login')
    async def login(request):
        """Save user id into the current session. """
        # ...
        session.login(request, current_user.pk)
        return 'OK'

    @app.register('/logout')
    async def logout(request):
        """ Logout user. """
        # ...
        session.logout(request)
        return 'OK'

    @app.register('/somewhere')
    async def somewhere(request):
        """ Do something and leave a flash message """
        # ...
        request.session.clear()
        return 'OK'


.. _bugtracker:

Bug tracker
===========

If you have any suggestions, bug reports or
annoyances please report them to the issue tracker
at https://github.com/klen/muffin-session/issues

.. _contributing:

Contributing
============

Development of Muffin-Session happens at: https://github.com/klen/muffin-session


Contributors
=============

* klen_ (Kirill Klenov)

.. _license:

License
========

Licensed under a `MIT license`_.

.. _links:


.. _klen: https://github.com/klen
.. _Muffin: https://github.com/klen/muffin

.. _MIT license: http://opensource.org/licenses/MIT

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/klen/muffin-session",
    "name": "muffin-session",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "asyncio,trio,asgi,muffin,web,cookie,sessions,session",
    "author": "Kirill Klenov",
    "author_email": "horneds@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/ab/6b/4d6b350d77be94737fc55f1f5c5dda93c5acfa5dfa7ac77b07fc853ba330/muffin_session-2.4.1.tar.gz",
    "platform": null,
    "description": "Muffin-Session\n##############\n\n.. _description:\n\n**Muffin-Session** -- Cookie-Based HTTP sessions for Muffin_ framework\n\n.. _badges:\n\n.. image:: https://github.com/klen/muffin-session/workflows/tests/badge.svg\n    :target: https://github.com/klen/muffin-session/actions\n    :alt: Tests Status\n\n.. image:: https://img.shields.io/pypi/v/muffin-session\n    :target: https://pypi.org/project/muffin-session/\n    :alt: PYPI Version\n\n.. image:: https://img.shields.io/pypi/pyversions/muffin-session\n    :target: https://pypi.org/project/muffin-session/\n    :alt: Python Versions\n\n.. _contents:\n\n.. contents::\n\nFeatures\n========\n\n* Supports base64 sessions\n* Supports ``JWT`` signed sessions\n* Supports ``Fernet`` encrypted sessions\n\n.. _requirements:\n\nRequirements\n=============\n\n- python >= 3.8\n\n.. _installation:\n\nInstallation\n=============\n\n**Muffin-Session** should be installed using pip: ::\n\n    pip install muffin-session\n\n    # Optional extras\n    pip install muffin-session[fernet]\n\n.. _usage:\n\nUsage\n=====\n\n1. Use it manually\n\n.. code-block:: python\n\n    from muffin import Application, ResponseHTML\n    from muffin_session import Plugin as Session\n\n    # Create Muffin Application\n    app = Application('example')\n\n    # Initialize the plugin\n    # As alternative: session = Session(app, **options)\n    session = Session()\n    session.setup(app, secret_key='REALLY_SECRET_KEY_FOR_SIGN_YOUR_SESSIONS')\n\n    # Use it inside your handlers\n    @app.route('/update')\n    async def update_session(request):\n        ses = session.load_from_request(request)\n        ses['var'] = 'value'\n        response = ResponseHTML('Session has been updated')\n        session.save_to_response(ses, response)\n        return res\n\n    @app.route('/load')\n    async def load_session(request):\n        ses = session.load_from_request(request)\n        return ses.get('var')\n\n2. Auto manage sessions (with middleware)\n\n.. code-block:: python\n\n    from muffin import Application, ResponseHTML\n    from muffin_session import Plugin as Session\n\n    # Create Muffin Application\n    app = Application('example')\n\n    # Initialize the plugin\n    # As alternative: session = Session(app, **options)\n    session = Session()\n    session.setup(app, secret_key='REALLY_SECRET_KEY_FOR_SIGN_YOUR_SESSIONS', auto_manage=True)\n\n    # Use it inside your handlers\n    @app.route('/update')\n    async def update_session(request):\n        request.session['var'] = 'value'\n        return 'Session has been updated'\n\n    @app.route('/load')\n    async def load_session(request):\n        return request.session.get('var')\n\n\nOptions\n-------\n\n=========================== =========================== ===========================\nName                        Default value               Description\n--------------------------- --------------------------- ---------------------------\n**session_type**            ``\"jwt\"``                   Session type (``base64|jwt|fernet``)\n**secret_key**              ``\"InsecureSecret\"``        A secret code to sign sessions\n**auto_manage**             ``False``                   Load/Save sessions automatically. Session will be loaded into ``request.session``\n**cookie_name**             ``\"session\"``               Sessions's cookie name (``session``)\n**cookie_params**                                       Sessions's cookie params (``{'path': '/', 'max-age': None, 'samesite': 'lax', 'secure': False}``)\n**default_user_checker**    ``lambda x: True``          A function to check a logged user\n**login_url**               ``\"/login\"``                An URL to redirect anonymous users (it may be a function which accept ``Request`` and returns a string)\n=========================== =========================== ===========================\n\n\nYou are able to provide the options when you are initiliazing the plugin:\n\n.. code-block:: python\n\n    session.setup(app, secret_key='123455', cookie_name='info')\n\n\nOr setup it inside ``Muffin.Application`` config using the ``SESSION_`` prefix:\n\n.. code-block:: python\n\n   SESSION_SECRET_KEY = '123455'\n\n   SESSION_COOKIE_NAME = 'info'\n\n``Muffin.Application`` configuration options are case insensitive\n\n\nExamples\n--------\n\n.. code-block:: python\n\n    from muffin import Application, ResponseHTML\n    from muffin_session import Plugin as Session\n\n    # Create Muffin Application\n    app = Application('example')\n\n    # Initialize the plugin\n    # As alternative: session = Session(app, **options)\n    session = Session()\n    session.setup(app, secret_key='REALLY_SECRET_KEY_FOR_SIGN_YOUR_SESSIONS', auto_manage=True)\n\n    @session.user_loader\n    async def load_user(ident):\n        \"\"\"Define your own user loader. \"\"\"\n        return await my_database_load_user_by_id(ident)\n\n    @app.register('/session')\n    async def get_session(request):\n        \"\"\" Load session and return it as JSON. \"\"\"\n        return dict(request.session)\n\n    @app.register('/admin')\n    @session.user_pass(lambda user: user.is_admin)\n    async def admin(request):\n        \"\"\"Awailable for admins only. \"\"\"\n        return 'TOP SECRET'\n\n    @app.register('/login')\n    async def login(request):\n        \"\"\"Save user id into the current session. \"\"\"\n        # ...\n        session.login(request, current_user.pk)\n        return 'OK'\n\n    @app.register('/logout')\n    async def logout(request):\n        \"\"\" Logout user. \"\"\"\n        # ...\n        session.logout(request)\n        return 'OK'\n\n    @app.register('/somewhere')\n    async def somewhere(request):\n        \"\"\" Do something and leave a flash message \"\"\"\n        # ...\n        request.session.clear()\n        return 'OK'\n\n\n.. _bugtracker:\n\nBug tracker\n===========\n\nIf you have any suggestions, bug reports or\nannoyances please report them to the issue tracker\nat https://github.com/klen/muffin-session/issues\n\n.. _contributing:\n\nContributing\n============\n\nDevelopment of Muffin-Session happens at: https://github.com/klen/muffin-session\n\n\nContributors\n=============\n\n* klen_ (Kirill Klenov)\n\n.. _license:\n\nLicense\n========\n\nLicensed under a `MIT license`_.\n\n.. _links:\n\n\n.. _klen: https://github.com/klen\n.. _Muffin: https://github.com/klen/muffin\n\n.. _MIT license: http://opensource.org/licenses/MIT\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Signed Cookie-Based HTTP sessions for the Muffin framework",
    "version": "2.4.1",
    "project_urls": {
        "Homepage": "https://github.com/klen/muffin-session",
        "Repository": "https://github.com/klen/muffin-session"
    },
    "split_keywords": [
        "asyncio",
        "trio",
        "asgi",
        "muffin",
        "web",
        "cookie",
        "sessions",
        "session"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "288d81432cdbc53ce4a8ffd3b5810eb5b2b00ca88d3e3f0239ea59efa43b9f82",
                "md5": "1ccccbbdb610ecbd324afb9be3dc656a",
                "sha256": "c7463137dcbe34089c352f23aff51763f0c3bc03655cf1d221a67e954b0f9bac"
            },
            "downloads": -1,
            "filename": "muffin_session-2.4.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1ccccbbdb610ecbd324afb9be3dc656a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 5740,
            "upload_time": "2023-06-21T06:41:43",
            "upload_time_iso_8601": "2023-06-21T06:41:43.411835Z",
            "url": "https://files.pythonhosted.org/packages/28/8d/81432cdbc53ce4a8ffd3b5810eb5b2b00ca88d3e3f0239ea59efa43b9f82/muffin_session-2.4.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ab6b4d6b350d77be94737fc55f1f5c5dda93c5acfa5dfa7ac77b07fc853ba330",
                "md5": "747bbb685d6b322fae5c593a76c178c3",
                "sha256": "3efa0cef67f068033463decd7c0d2d2b0a9a2085f3dc0d269b8587a875d0c3ea"
            },
            "downloads": -1,
            "filename": "muffin_session-2.4.1.tar.gz",
            "has_sig": false,
            "md5_digest": "747bbb685d6b322fae5c593a76c178c3",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 5616,
            "upload_time": "2023-06-21T06:41:45",
            "upload_time_iso_8601": "2023-06-21T06:41:45.136849Z",
            "url": "https://files.pythonhosted.org/packages/ab/6b/4d6b350d77be94737fc55f1f5c5dda93c5acfa5dfa7ac77b07fc853ba330/muffin_session-2.4.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-21 06:41:45",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "klen",
    "github_project": "muffin-session",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "muffin-session"
}
        
Elapsed time: 0.08438s