flask-dictabase


Nameflask-dictabase JSON
Version 1.2.5 PyPI version JSON
download
home_pagehttps://github.com/GrantGMiller/flask_dictabase
SummaryA dict() like interface to your database.
upload_time2023-11-17 19:45:11
maintainer
docs_urlNone
authorGrant miller
requires_python
licensePSF
keywords grant miller flask database
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Flask-Dictabase
===============
A dict() like interface to your database.

Install
=======
::

    pip install flask_dictabase

Here is a simple flask app implementation.
::

    import random
    import string

    from flask import (
        Flask,
        render_template,
        redirect
    )
    import flask_dictabase

    app = Flask('User Management')
    # if you would like to specify the SQLAlchemy database then you can do:
    # app.config['DATABASE_URL'] = 'sqlite:///my.db'
    db = flask_dictabase.Dictabase(app)


    class UserClass(flask_dictabase.BaseTable):
        def CustomMethod(self):
            # You can access the db from within a BaseTable object.
            allUsers = self.db.FindAll(UserClass)
            numOfUsers = len(allUsers)
            print('There are {} total users in the database.'.format(numOfUsers)

            # You can also access the app from within a BaseTable object
            if self.app.config.get('SECRET_KEY', None) is None:
                print('This app has no secret key')

    @app.route('/')
    def Index():
        return render_template(
            'users.html',
            users=db.FindAll(UserClass),
        )


    @app.route('/update_user_uption/<userID>/<state>')
    def UpdateUser(userID, state):
        newState = {'true': True, 'false': False}.get(state.lower(), None)
        user = db.FindOne(UserClass, id=int(userID))
        user['state'] = newState # This is immediately saved to the database.
        return redirect('/')


    @app.route('/new')
    def NewUser():
        email = ''.join([random.choice(string.ascii_letters) for i in range(10)])
        email += '@'
        email += ''.join([random.choice(string.ascii_letters) for i in range(5)])
        email += '.com'

        newUser = db.New(UserClass, email=email, state=bool(random.randint(0, 1)))
        print('newUser=', newUser) # This is now immediately saved to the database.
        return redirect('/')


    @app.route('/delete/<userID>')
    def Delete(userID):
        user = db.FindOne(UserClass, id=int(userID))
        print('user=', user)
        if user:
            db.Delete(user) # User is now removed from the database.
        return redirect('/')


    if __name__ == '__main__':
        app.run(
            debug=True,
            threaded=True,
        )

Unsupported Types / Advanced Usage
==================================
If you want to store more complex information like list() and dict(), you can use the .Set() and .Get() helper methods.
These convert your values to/from json to be stored in the db as a string.

::

    myList = [1,2,3,4,5] #
    user = db.FindOne(UserClass, id=1)
    if user:
        user.Set('myList', myList)

    user2 = db.FindOne(UserClass, id=1)
    print('user2.Get('myList')=', user2.Get('myList'))

Output
::

    >>> user2.Get('myList')= [1, 2, 3, 4, 5]

You can use the helper methods .Append() and .SetItem() to easliy save list() and dict()
::

    user.Append('myList', 9)
    print('user2.Get('myList')=', user2.Get('myList'))

Output
::

    >>> user2.Get('myList')= [1, 2, 3, 4, 5, 9]

You can also use a different function to load/dump the values. Like python's pickle module.
::

    import pickle
    myList = [1,2,3,4,5] #
    user = db.FindOne(UserClass, id=1)
    if user:
        user.Set('myList', myList, dumper=pickle.dumps, dumperKwargs={})

    user2 = db.FindOne(UserClass, id=1)
    print('user2.Get('myList')=', user2.Get('myList', loader=pickle.loads))

You can also provide a default argument to .Get()
::

    user = db.FindOne(UserClass, id=1)
    user.Get('missingKey', None) # return None if key is missing, else return the dumped value

You can also use the methods .Append() .Remove() and .SetItem() and .PopItem() to easily manipulate the info stored as JSON
::

    user = db.FindOne(UserClass, id=1)
    user.Set('animals', ['cat', 'dog', 'bird'])

    print('user.Get("animals")=', user.Get('animals'))
    >>> user.Get("animals")= ['cat', 'dog', 'bird']

    user.Append('animals', 'tiger')
    print('user.Get("animals")=', user.Get('animals'))
    >>> user.Get("animals")= ['cat', 'dog', 'bird', 'tiger']

    user.Remove('animals', 'cat')
    print('user.Get("animals")=', user.Get('animals'))
    >>> user.Get("animals")= ['dog', 'bird', 'tiger']

    user.Set('numOfPets', {'cats': 1, 'dog': 1})
    print('user.Get("numOfPets")=', user.Get('numOfPets'))
    >>> user.Get("numOfPets")= {'cats': 1, 'dog': 1}

    user.SetItem('numOfPets', 'cats', 3)
    print('user.Get("numOfPets")=', user.Get('numOfPets'))
    >>> user.Get("numOfPets")= {'cats': 3, 'dog': 1}

    user.PopItem('numOfPets', 'cats')
    print('user.Get("numOfPets")=', user.Get('numOfPets'))
    >>> user.Get("numOfPets")= {'dog': 1}

Variables
=========
Kind of like Global Variables but stored in the database.
Example::

    db.var.Set('nameOfTheVariable', 'valueOfTheVariable')

    # set/get generic variables
    @app.route('/set/<key>/<value>')
    def Set(key, value):
        db.var.Set(key, value)
        return f'Set {key}={value}'


    @app.route('/get/<key>')
    def Get(key):
        return db.var.Get(key)

Database Relationships
======================

You can link database objects together to easily reference one object from another.
Use the `BaseTable.Link()` and `BaseTable.Unlink()` to create/delete the relationships.
Use `BaseTable.Links()` to iterate through the relationships.

::

    class Player(flask_dictabase.BaseTable):
        pass

    player = app.db.NewOrFind(Player, name='Grant')
    print('player=', player)

    class Card(flask_dictabase.BaseTable):
        pass

    SUITS = ['club', 'spade', 'heart', 'diamond']
    VALUES = ['ace', 'jack', 'queen', 'king'] + [i for i in range(2, 10 + 1)]

    # create all the cards in the database
    for suit in SUITS:
        for value in VALUES:
            # note: NewOrFind() will look in the database for the object,
            # if it doesnt find any, it will create a new object.
            app.db.NewOrFind(Card, suit=suit, value=value)

    # give the player some cards
    for i in range(5):
        suit = random.choice(SUITS)
        value = random.choice(VALUES)

        player.Link(
            app.db.NewOrFind(Card, suit=suit, value=value)
        )

    print('The cards in the players hand are:')
    for card in player.Links(Card):
        print('card=', card)

    print('the player is holding the following cards that are hearts')
    for card in player.Links(Card, suit='heart'):
        print('card=', card)

    for index, obj in enumerate(player.Links(Card)):
        if index % 3 == 0:
            player.Unlink(obj)
            print('player discarded the card=', obj)

    card = app.db.NewOrFind(Card, suit='heart', value='queen')
    for obj in card.Links():
        print('the queen of hearts is held by player=', obj)

    >>>
    player= <Player: id=1(type=int), name=Grant(type=str)>
    The cards in the players hand are:
    card= <Card: id=50(type=int), suit=diamond(type=str), value=8(type=str)>
    card= <Card: id=44(type=int), suit=diamond(type=str), value=2(type=str)>
    card= <Card: id=10(type=int), suit=club(type=str), value=7(type=str)>
    card= <Card: id=24(type=int), suit=spade(type=str), value=8(type=str)>
    card= <Card: id=39(type=int), suit=heart(type=str), value=10(type=str)>
    the player is holding the following cards that are hearts
    card= <Card: id=39(type=int), suit=heart(type=str), value=10(type=str)>
    player discarded the card= <Card: id=50(type=int), suit=diamond(type=str), value=8(type=str)>

Find Rows By Range
==================
You can use the '_where' keyword with '_greaterThan', '_lessThan', '_lessThanOrEqualTo', '_greaterThanOrEqualTo', '_equals'.

::

    users = app.db.FindAll(User, _where='age', _greaterThan=18)
    print('These are the users over age 18:')
    for user in users:
        print(user)

    users = app.db.FindAll(User, _where='age', _greaterThanOrEqualTo=18, _lessThanOrEqualTo=25)
    print('These are the users between age 18 and 25:')
    for user in users:
        print(user)

Gunicorn
========

Supports multiple workers (-w config option).
Example::

    gunicorn main:app -w 4 -b localhost:8080

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/GrantGMiller/flask_dictabase",
    "name": "flask-dictabase",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "grant miller flask database",
    "author": "Grant miller",
    "author_email": "grant@grant-miller.com",
    "download_url": "https://files.pythonhosted.org/packages/d9/83/21161be0cbd82c223234c2ca52cd6e6e98535bc29a419947e8fceec2a082/flask_dictabase-1.2.5.tar.gz",
    "platform": null,
    "description": "Flask-Dictabase\n===============\nA dict() like interface to your database.\n\nInstall\n=======\n::\n\n    pip install flask_dictabase\n\nHere is a simple flask app implementation.\n::\n\n    import random\n    import string\n\n    from flask import (\n        Flask,\n        render_template,\n        redirect\n    )\n    import flask_dictabase\n\n    app = Flask('User Management')\n    # if you would like to specify the SQLAlchemy database then you can do:\n    # app.config['DATABASE_URL'] = 'sqlite:///my.db'\n    db = flask_dictabase.Dictabase(app)\n\n\n    class UserClass(flask_dictabase.BaseTable):\n        def CustomMethod(self):\n            # You can access the db from within a BaseTable object.\n            allUsers = self.db.FindAll(UserClass)\n            numOfUsers = len(allUsers)\n            print('There are {} total users in the database.'.format(numOfUsers)\n\n            # You can also access the app from within a BaseTable object\n            if self.app.config.get('SECRET_KEY', None) is None:\n                print('This app has no secret key')\n\n    @app.route('/')\n    def Index():\n        return render_template(\n            'users.html',\n            users=db.FindAll(UserClass),\n        )\n\n\n    @app.route('/update_user_uption/<userID>/<state>')\n    def UpdateUser(userID, state):\n        newState = {'true': True, 'false': False}.get(state.lower(), None)\n        user = db.FindOne(UserClass, id=int(userID))\n        user['state'] = newState # This is immediately saved to the database.\n        return redirect('/')\n\n\n    @app.route('/new')\n    def NewUser():\n        email = ''.join([random.choice(string.ascii_letters) for i in range(10)])\n        email += '@'\n        email += ''.join([random.choice(string.ascii_letters) for i in range(5)])\n        email += '.com'\n\n        newUser = db.New(UserClass, email=email, state=bool(random.randint(0, 1)))\n        print('newUser=', newUser) # This is now immediately saved to the database.\n        return redirect('/')\n\n\n    @app.route('/delete/<userID>')\n    def Delete(userID):\n        user = db.FindOne(UserClass, id=int(userID))\n        print('user=', user)\n        if user:\n            db.Delete(user) # User is now removed from the database.\n        return redirect('/')\n\n\n    if __name__ == '__main__':\n        app.run(\n            debug=True,\n            threaded=True,\n        )\n\nUnsupported Types / Advanced Usage\n==================================\nIf you want to store more complex information like list() and dict(), you can use the .Set() and .Get() helper methods.\nThese convert your values to/from json to be stored in the db as a string.\n\n::\n\n    myList = [1,2,3,4,5] #\n    user = db.FindOne(UserClass, id=1)\n    if user:\n        user.Set('myList', myList)\n\n    user2 = db.FindOne(UserClass, id=1)\n    print('user2.Get('myList')=', user2.Get('myList'))\n\nOutput\n::\n\n    >>> user2.Get('myList')= [1, 2, 3, 4, 5]\n\nYou can use the helper methods .Append() and .SetItem() to easliy save list() and dict()\n::\n\n    user.Append('myList', 9)\n    print('user2.Get('myList')=', user2.Get('myList'))\n\nOutput\n::\n\n    >>> user2.Get('myList')= [1, 2, 3, 4, 5, 9]\n\nYou can also use a different function to load/dump the values. Like python's pickle module.\n::\n\n    import pickle\n    myList = [1,2,3,4,5] #\n    user = db.FindOne(UserClass, id=1)\n    if user:\n        user.Set('myList', myList, dumper=pickle.dumps, dumperKwargs={})\n\n    user2 = db.FindOne(UserClass, id=1)\n    print('user2.Get('myList')=', user2.Get('myList', loader=pickle.loads))\n\nYou can also provide a default argument to .Get()\n::\n\n    user = db.FindOne(UserClass, id=1)\n    user.Get('missingKey', None) # return None if key is missing, else return the dumped value\n\nYou can also use the methods .Append() .Remove() and .SetItem() and .PopItem() to easily manipulate the info stored as JSON\n::\n\n    user = db.FindOne(UserClass, id=1)\n    user.Set('animals', ['cat', 'dog', 'bird'])\n\n    print('user.Get(\"animals\")=', user.Get('animals'))\n    >>> user.Get(\"animals\")= ['cat', 'dog', 'bird']\n\n    user.Append('animals', 'tiger')\n    print('user.Get(\"animals\")=', user.Get('animals'))\n    >>> user.Get(\"animals\")= ['cat', 'dog', 'bird', 'tiger']\n\n    user.Remove('animals', 'cat')\n    print('user.Get(\"animals\")=', user.Get('animals'))\n    >>> user.Get(\"animals\")= ['dog', 'bird', 'tiger']\n\n    user.Set('numOfPets', {'cats': 1, 'dog': 1})\n    print('user.Get(\"numOfPets\")=', user.Get('numOfPets'))\n    >>> user.Get(\"numOfPets\")= {'cats': 1, 'dog': 1}\n\n    user.SetItem('numOfPets', 'cats', 3)\n    print('user.Get(\"numOfPets\")=', user.Get('numOfPets'))\n    >>> user.Get(\"numOfPets\")= {'cats': 3, 'dog': 1}\n\n    user.PopItem('numOfPets', 'cats')\n    print('user.Get(\"numOfPets\")=', user.Get('numOfPets'))\n    >>> user.Get(\"numOfPets\")= {'dog': 1}\n\nVariables\n=========\nKind of like Global Variables but stored in the database.\nExample::\n\n    db.var.Set('nameOfTheVariable', 'valueOfTheVariable')\n\n    # set/get generic variables\n    @app.route('/set/<key>/<value>')\n    def Set(key, value):\n        db.var.Set(key, value)\n        return f'Set {key}={value}'\n\n\n    @app.route('/get/<key>')\n    def Get(key):\n        return db.var.Get(key)\n\nDatabase Relationships\n======================\n\nYou can link database objects together to easily reference one object from another.\nUse the `BaseTable.Link()` and `BaseTable.Unlink()` to create/delete the relationships.\nUse `BaseTable.Links()` to iterate through the relationships.\n\n::\n\n    class Player(flask_dictabase.BaseTable):\n        pass\n\n    player = app.db.NewOrFind(Player, name='Grant')\n    print('player=', player)\n\n    class Card(flask_dictabase.BaseTable):\n        pass\n\n    SUITS = ['club', 'spade', 'heart', 'diamond']\n    VALUES = ['ace', 'jack', 'queen', 'king'] + [i for i in range(2, 10 + 1)]\n\n    # create all the cards in the database\n    for suit in SUITS:\n        for value in VALUES:\n            # note: NewOrFind() will look in the database for the object,\n            # if it doesnt find any, it will create a new object.\n            app.db.NewOrFind(Card, suit=suit, value=value)\n\n    # give the player some cards\n    for i in range(5):\n        suit = random.choice(SUITS)\n        value = random.choice(VALUES)\n\n        player.Link(\n            app.db.NewOrFind(Card, suit=suit, value=value)\n        )\n\n    print('The cards in the players hand are:')\n    for card in player.Links(Card):\n        print('card=', card)\n\n    print('the player is holding the following cards that are hearts')\n    for card in player.Links(Card, suit='heart'):\n        print('card=', card)\n\n    for index, obj in enumerate(player.Links(Card)):\n        if index % 3 == 0:\n            player.Unlink(obj)\n            print('player discarded the card=', obj)\n\n    card = app.db.NewOrFind(Card, suit='heart', value='queen')\n    for obj in card.Links():\n        print('the queen of hearts is held by player=', obj)\n\n    >>>\n    player= <Player: id=1(type=int), name=Grant(type=str)>\n    The cards in the players hand are:\n    card= <Card: id=50(type=int), suit=diamond(type=str), value=8(type=str)>\n    card= <Card: id=44(type=int), suit=diamond(type=str), value=2(type=str)>\n    card= <Card: id=10(type=int), suit=club(type=str), value=7(type=str)>\n    card= <Card: id=24(type=int), suit=spade(type=str), value=8(type=str)>\n    card= <Card: id=39(type=int), suit=heart(type=str), value=10(type=str)>\n    the player is holding the following cards that are hearts\n    card= <Card: id=39(type=int), suit=heart(type=str), value=10(type=str)>\n    player discarded the card= <Card: id=50(type=int), suit=diamond(type=str), value=8(type=str)>\n\nFind Rows By Range\n==================\nYou can use the '_where' keyword with '_greaterThan', '_lessThan', '_lessThanOrEqualTo', '_greaterThanOrEqualTo', '_equals'.\n\n::\n\n    users = app.db.FindAll(User, _where='age', _greaterThan=18)\n    print('These are the users over age 18:')\n    for user in users:\n        print(user)\n\n    users = app.db.FindAll(User, _where='age', _greaterThanOrEqualTo=18, _lessThanOrEqualTo=25)\n    print('These are the users between age 18 and 25:')\n    for user in users:\n        print(user)\n\nGunicorn\n========\n\nSupports multiple workers (-w config option).\nExample::\n\n    gunicorn main:app -w 4 -b localhost:8080\n",
    "bugtrack_url": null,
    "license": "PSF",
    "summary": "A dict() like interface to your database.",
    "version": "1.2.5",
    "project_urls": {
        "Homepage": "https://github.com/GrantGMiller/flask_dictabase",
        "Source Code": "https://github.com/GrantGMiller/flask_dictabase"
    },
    "split_keywords": [
        "grant",
        "miller",
        "flask",
        "database"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d1a17d64b36533f6b66317d46d02088082c197de0516b68171a80311537d6db0",
                "md5": "b3f9f9689d018695ed15e384224c0733",
                "sha256": "a4b24b4947f4d21731da23db71d627f86eb267734d3ba7a819e8ff26d379ca4e"
            },
            "downloads": -1,
            "filename": "flask_dictabase-1.2.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b3f9f9689d018695ed15e384224c0733",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 7148,
            "upload_time": "2023-11-17T19:45:10",
            "upload_time_iso_8601": "2023-11-17T19:45:10.016375Z",
            "url": "https://files.pythonhosted.org/packages/d1/a1/7d64b36533f6b66317d46d02088082c197de0516b68171a80311537d6db0/flask_dictabase-1.2.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d98321161be0cbd82c223234c2ca52cd6e6e98535bc29a419947e8fceec2a082",
                "md5": "8444b9f0cfd3e5d91fe7dc57723c0d87",
                "sha256": "f259edb239840bd608f9cdd5058c38aaf60f1a0be7c5142a58211841870b045e"
            },
            "downloads": -1,
            "filename": "flask_dictabase-1.2.5.tar.gz",
            "has_sig": false,
            "md5_digest": "8444b9f0cfd3e5d91fe7dc57723c0d87",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 9123,
            "upload_time": "2023-11-17T19:45:11",
            "upload_time_iso_8601": "2023-11-17T19:45:11.692215Z",
            "url": "https://files.pythonhosted.org/packages/d9/83/21161be0cbd82c223234c2ca52cd6e6e98535bc29a419947e8fceec2a082/flask_dictabase-1.2.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-17 19:45:11",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "GrantGMiller",
    "github_project": "flask_dictabase",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "flask-dictabase"
}
        
Elapsed time: 0.13613s