flask-sqlalchemy-qs


Nameflask-sqlalchemy-qs JSON
Version 1.1.5 PyPI version JSON
download
home_pagehttps://github.com/marcogil93/flask-sqlalchemy-qs
SummaryGenerate and manipulate SQLAlchemy filters and sorts from query strings in the URL
upload_time2024-08-03 00:57:58
maintainerNone
docs_urlNone
authorMarco Gil
requires_python>=3.7
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # flask-sqlalchemy-qs

flask-sqlalchemy-qs is a Python library that enables processing of query strings and its usage in conjunction with Flask and SQLAlchemy. The library provides tools for generating and manipulating SQLAlchemy filters and sorts from query strings in the URL, making it easier to build robust and flexible RESTful APIs. 

A User model has a username column attribute to filter:

`/users?filters[username][eq]=awesomeuser@example.com`


A User model has a person relationship attribute, and a list of users has to be filtered and sorted by an attribute of that relationship:

`/users?filters[person][age][gte]=22&sorts[0][person][age]=DESC&limit=10&offset=0`

## Installation

Install flask-sqlalchemy-qs with pip:

```bash
pip install flask-sqlalchemy-qs
```

## Usage

To get the filters, sorts, limit, and offset from the query string is necesarry to follow the next syntaxis: 


### For the "filters" parameter
Filter your list result by column and relationship model properties.

`GET /api/endpoint?filters[field][operator]=value`

The following operators are available:

| Operator    | Description                        |
| ----------- | ---------------------------------- |
| eq          | Equal                              |
| ne          | Not equal                          |
| is          | Is                                 |
| is_not      | Is not                             |
| lt          | Less than                          |
| lte         | Less than or equal to              |
| gt          | Greater than                       |
| gte         | Greater than or equal to           |
| in          | Included in an array               |
| nin         | Not included in an array           |
| contains    | Contains                           |
| ncontains   | Does not contain                   |
| icontains   | Contains (case-insensitive)        |
| like        | Like                               |
| ilike       | Like (case-insensitive)            |
| not_like    | Not Like                           |
| not_ilike   | Not Like (case-insensitive)        |
| nicontains  | Does not contain (case-insensitive)|
| startswith  | Starts with                        |
| istartswith | Starts with (case-insensitive)     |
| endswith    | Ends with                          |
| iendswith   | Ends with (case-insensitive)       |
| or          | Joins the filters in an "or" expression  |
| and         | Joins the filters in an "and" expression |
| not         | Joins the filters in an "not" expression |

#### Examples:

1) Simple usage

`/users?filters[username][eq]=username@example.com`  

2) Relationship usage (User has a person)

`/users?filters[person][name][eq]=Marco`

3) Multiple usage

`/users?filters[username][contains]=awesome.com&filters[person][age][gte]=25`

4) In and nin usage

`/users?filters[person][age][in][0]=20&filters[person][age][in][1]=25&filters[person][age][in][2]=30`

5) Boolean usage

`/users?filters[or][0][username][eq]=username1&filters[or][1][username][eq]=username2`

6) Complex boolean usage

`/users?filters[or][0][username][contains]=awesome.com&filters[or][1][not][0][and][0][person][age][gte]=20&filters[or][1][not][0][and][1][person][age][lte]=30`

7) JSON support followed by dot notation

`/users?filters[json_column.foo][eq]=bar`

<!-- blank line -->  

<!-- blank line -->  


### For the "sorts" parameter
Sort your list result by column and relationship model properties.

`GET /api/endpoint?sorts[priority_index][field]=order`

#### Examples:

1) Single sort usage

`/users?sorts[0][username]=DESC`

2) Multiple order priority and relationship usage

`/users?sorts[0][username]=DESC&sorts[1][person][age]=ASC`

### For the "limit" and "offset" parameter 
Limt (amount of elements) and offset (amount of skipped elements) for your list result. 

`GET /api/endpoint?limit=10&offset=2`

#### Examples:

`/users?limit=100&offset=5`


## Implementation 
In order to use it in the sqlalchemy query object. The BaseQuery needs to be imported and set as the query_class in the model

```python
from typing import Dict, List, Tuple, Union
from flask_sqlalchemy_qs import get_url_query_ctx, BaseQuery

...

db = SQLAlchemy(app)

# In this case, a Base Model is defined with its query_class attribute set to BaseQuery
class Base(db.Model):
  __abstract__ = True
  query_class = BaseQuery

class User(Base):
  id       = db.Column(db.Integer, primary_key=True)
  ...

...

#Types
FilterType = Dict[str, Union[bool, str, Dict]]
SortType = Dict[str, Union[str, Dict]]

...

@myblueprint.route('/users', methods=['GET'])
def get_all_users():
  #Get the query string in the correct format
  ctx: Dict[str, Union[FilterType, List[SortType], int]] = get_url_query_ctx()

  filters:FilterType   = ctx["filters"]
  sorts:List[SortType] = ctx["sorts"]
  limit:int            = ctx["limit"]
  offset:int           = ctx["offset"]


  #Query the model with the extended methods
  query = User.query.filter_by_ctx(filters=filters) \
                    .sort_by_ctx(sorts=sorts) \
                    .offset(offset) \
                    .limit(limit)
  
  ...

  results = query.all()

  ...
```

## Version
1.1.5

## Requirements 
SQLALCHEMYSQLAlchemy~=2.0

flask~=2.2

flask-sqlalchemy~=3.0

## Contribution
Contributions to this project are welcome. Please open an issue or make a pull request.

## License
This project is licensed under the terms of the MIT license.

## Support
If you have any issues or suggestions, please open an issue on this repository.

## Authors
Marco Gil, marcogil93@gmail.com

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/marcogil93/flask-sqlalchemy-qs",
    "name": "flask-sqlalchemy-qs",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": null,
    "author": "Marco Gil",
    "author_email": "marcogil93@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/82/30/dcf198982cd667142ab82b47e69dcd8c5757be5f28c4f60fcabc3b8b32e5/flask_sqlalchemy_qs-1.1.5.tar.gz",
    "platform": null,
    "description": "# flask-sqlalchemy-qs\n\nflask-sqlalchemy-qs is a Python library that enables processing of query strings and its usage in conjunction with Flask and SQLAlchemy. The library provides tools for generating and manipulating SQLAlchemy filters and sorts from query strings in the URL, making it easier to build robust and flexible RESTful APIs. \n\nA User model has a username column attribute to filter:\n\n`/users?filters[username][eq]=awesomeuser@example.com`\n\n\nA User model has a person relationship attribute, and a list of users has to be filtered and sorted by an attribute of that relationship:\n\n`/users?filters[person][age][gte]=22&sorts[0][person][age]=DESC&limit=10&offset=0`\n\n## Installation\n\nInstall flask-sqlalchemy-qs with pip:\n\n```bash\npip install flask-sqlalchemy-qs\n```\n\n## Usage\n\nTo get the filters, sorts, limit, and offset from the query string is necesarry to follow the next syntaxis: \n\n\n### For the \"filters\" parameter\nFilter your list result by column and relationship model properties.\n\n`GET /api/endpoint?filters[field][operator]=value`\n\nThe following operators are available:\n\n| Operator    | Description                        |\n| ----------- | ---------------------------------- |\n| eq          | Equal                              |\n| ne          | Not equal                          |\n| is          | Is                                 |\n| is_not      | Is not                             |\n| lt          | Less than                          |\n| lte         | Less than or equal to              |\n| gt          | Greater than                       |\n| gte         | Greater than or equal to           |\n| in          | Included in an array               |\n| nin         | Not included in an array           |\n| contains    | Contains                           |\n| ncontains   | Does not contain                   |\n| icontains   | Contains (case-insensitive)        |\n| like        | Like                               |\n| ilike       | Like (case-insensitive)            |\n| not_like    | Not Like                           |\n| not_ilike   | Not Like (case-insensitive)        |\n| nicontains  | Does not contain (case-insensitive)|\n| startswith  | Starts with                        |\n| istartswith | Starts with (case-insensitive)     |\n| endswith    | Ends with                          |\n| iendswith   | Ends with (case-insensitive)       |\n| or          | Joins the filters in an \"or\" expression  |\n| and         | Joins the filters in an \"and\" expression |\n| not         | Joins the filters in an \"not\" expression |\n\n#### Examples:\n\n1) Simple usage\n\n`/users?filters[username][eq]=username@example.com`  \n\n2) Relationship usage (User has a person)\n\n`/users?filters[person][name][eq]=Marco`\n\n3) Multiple usage\n\n`/users?filters[username][contains]=awesome.com&filters[person][age][gte]=25`\n\n4) In and nin usage\n\n`/users?filters[person][age][in][0]=20&filters[person][age][in][1]=25&filters[person][age][in][2]=30`\n\n5) Boolean usage\n\n`/users?filters[or][0][username][eq]=username1&filters[or][1][username][eq]=username2`\n\n6) Complex boolean usage\n\n`/users?filters[or][0][username][contains]=awesome.com&filters[or][1][not][0][and][0][person][age][gte]=20&filters[or][1][not][0][and][1][person][age][lte]=30`\n\n7) JSON support followed by dot notation\n\n`/users?filters[json_column.foo][eq]=bar`\n\n<!-- blank line -->  \n\n<!-- blank line -->  \n\n\n### For the \"sorts\" parameter\nSort your list result by column and relationship model properties.\n\n`GET /api/endpoint?sorts[priority_index][field]=order`\n\n#### Examples:\n\n1) Single sort usage\n\n`/users?sorts[0][username]=DESC`\n\n2) Multiple order priority and relationship usage\n\n`/users?sorts[0][username]=DESC&sorts[1][person][age]=ASC`\n\n### For the \"limit\" and \"offset\" parameter \nLimt (amount of elements) and offset (amount of skipped elements) for your list result. \n\n`GET /api/endpoint?limit=10&offset=2`\n\n#### Examples:\n\n`/users?limit=100&offset=5`\n\n\n## Implementation \nIn order to use it in the sqlalchemy query object. The BaseQuery needs to be imported and set as the query_class in the model\n\n```python\nfrom typing import Dict, List, Tuple, Union\nfrom flask_sqlalchemy_qs import get_url_query_ctx, BaseQuery\n\n...\n\ndb = SQLAlchemy(app)\n\n# In this case, a Base Model is defined with its query_class attribute set to BaseQuery\nclass Base(db.Model):\n  __abstract__ = True\n  query_class = BaseQuery\n\nclass User(Base):\n  id       = db.Column(db.Integer, primary_key=True)\n  ...\n\n...\n\n#Types\nFilterType = Dict[str, Union[bool, str, Dict]]\nSortType = Dict[str, Union[str, Dict]]\n\n...\n\n@myblueprint.route('/users', methods=['GET'])\ndef get_all_users():\n  #Get the query string in the correct format\n  ctx: Dict[str, Union[FilterType, List[SortType], int]] = get_url_query_ctx()\n\n  filters:FilterType   = ctx[\"filters\"]\n  sorts:List[SortType] = ctx[\"sorts\"]\n  limit:int            = ctx[\"limit\"]\n  offset:int           = ctx[\"offset\"]\n\n\n  #Query the model with the extended methods\n  query = User.query.filter_by_ctx(filters=filters) \\\n                    .sort_by_ctx(sorts=sorts) \\\n                    .offset(offset) \\\n                    .limit(limit)\n  \n  ...\n\n  results = query.all()\n\n  ...\n```\n\n## Version\n1.1.5\n\n## Requirements \nSQLALCHEMYSQLAlchemy~=2.0\n\nflask~=2.2\n\nflask-sqlalchemy~=3.0\n\n## Contribution\nContributions to this project are welcome. Please open an issue or make a pull request.\n\n## License\nThis project is licensed under the terms of the MIT license.\n\n## Support\nIf you have any issues or suggestions, please open an issue on this repository.\n\n## Authors\nMarco Gil, marcogil93@gmail.com\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Generate and manipulate SQLAlchemy filters and sorts from query strings in the URL",
    "version": "1.1.5",
    "project_urls": {
        "Homepage": "https://github.com/marcogil93/flask-sqlalchemy-qs"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "05e1b2b3a9382ed3a34614b41cd041ad700fe1a6b105a7f50c8c6d2edc7b428b",
                "md5": "eae74920a623a9df78d53fc96a06f593",
                "sha256": "1e7a4d35b07cc23f7c305c1f82c425c15cb610012ca4c60b2407a87cb16a2c73"
            },
            "downloads": -1,
            "filename": "flask_sqlalchemy_qs-1.1.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "eae74920a623a9df78d53fc96a06f593",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 8638,
            "upload_time": "2024-08-03T00:57:57",
            "upload_time_iso_8601": "2024-08-03T00:57:57.279994Z",
            "url": "https://files.pythonhosted.org/packages/05/e1/b2b3a9382ed3a34614b41cd041ad700fe1a6b105a7f50c8c6d2edc7b428b/flask_sqlalchemy_qs-1.1.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8230dcf198982cd667142ab82b47e69dcd8c5757be5f28c4f60fcabc3b8b32e5",
                "md5": "19ae21714fd710be44b85ae69955d082",
                "sha256": "42da8e8be76241332896188c52817fbd06f4ce86beb882e34072c95fd349cf77"
            },
            "downloads": -1,
            "filename": "flask_sqlalchemy_qs-1.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "19ae21714fd710be44b85ae69955d082",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 11765,
            "upload_time": "2024-08-03T00:57:58",
            "upload_time_iso_8601": "2024-08-03T00:57:58.757868Z",
            "url": "https://files.pythonhosted.org/packages/82/30/dcf198982cd667142ab82b47e69dcd8c5757be5f28c4f60fcabc3b8b32e5/flask_sqlalchemy_qs-1.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-08-03 00:57:58",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "marcogil93",
    "github_project": "flask-sqlalchemy-qs",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [],
    "lcname": "flask-sqlalchemy-qs"
}
        
Elapsed time: 0.27032s