flask-filealchemy


Nameflask-filealchemy JSON
Version 0.8.0 PyPI version JSON
download
home_pagehttps://github.com/siddhantgoel/flask-filealchemy
SummaryYAML-formatted plain-text file based models for Flask backed by Flask-SQLAlchemy
upload_time2022-12-04 09:39:27
maintainer
docs_urlNone
authorSiddhant Goel
requires_python>=3.7,<4.0
licenseMIT
keywords flask sqlalchemy yaml plaintext web
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Flask-FileAlchemy

![](https://github.com/siddhantgoel/flask-filealchemy/workflows/flask-filealchemy/badge.svg) ![](https://badge.fury.io/py/flask-filealchemy.svg)

`Flask-FileAlchemy` is a [Flask] extension that lets you use Markdown or YAML
formatted plain-text files as the main data store for your apps.

## Installation

```bash
$ pip install flask-filealchemy
```

## Background

The constraints on which data-store to use for applications that only have to
run locally are quite relaxed as compared to the ones that have to serve
production traffic. For such applications, it's normally OK to sacrifice on
performance for ease of use.

One very strong use case here is generating static sites. While you can use
[Frozen-Flask] to "freeze" an entire Flask application to a set of HTML files,
your application still needs to read data from somewhere. This means you'll need
to set up a data store, which (locally) tends to be file based SQLite. While
that does the job extremely well, this also means executing SQL statements to
input data.

Depending on how many data models you have and what types they contain, this can
quickly get out of hand (imagine having to write an `INSERT` statement for a
blog post).

In addition, you can't version control your data. Well, technically you can, but
the diffs won't make any sense to a human.

Flask-FileAlchemy lets you use an alternative data store - plain text files.

Plain text files have the advantage of being much easier to handle for a human.
Plus, you can version control them so your application data and code are both
checked in together and share history.

Flask-FileAlchemy lets you enter your data in Markdown or YAML formatted plain
text files and loads them according to the [SQLAlchemy] models you've defined
using [Flask-SQLAlchemy] This data is then put into whatever data store you're
using (in-memory SQLite works best) and is then ready for your app to query
however it pleases.

This lets you retain the comfort of dynamic sites without compromising on the
simplicity of static sites.

## Usage

### Define data models

Define your data models using the standard (Flask-)SQLAlchemy API. As an
example, a `BlogPost` model can defined as follows.

```python
app = Flask(__name__)

# configure Flask-SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'

db = SQLAlchemy()

db.init_app(app)

class BlogPost(db.Model):
   __tablename__ = 'blog_posts'

   slug = Column(String(255), primary_key=True)
   title = Column(String(255), nullable=False)
   content = Column(Text, nullable=False)
```

### Add some data

Next, create a `data/` directory somewhere on your disk (to keep things simple,
it's recommended to have this directory in the application root). For each model
you've defined, create a directory under this `data/` directory with the same
name as the `__tablename__` attribute.

We currently support three different ways to define data.

#### 1. Multiple YAML files

The first way is to have multiple YAML files inside the `data/<__tablename__>/`
directory, each file corresponding to one record.

In case of the "blog" example, we can define a new `BlogPost` record by creating
the file `data/blog_posts/first-post-ever.yml` with the following content.

```yaml
slug: first-post-ever
title: First post ever!
content: |
  This blog post talks about how it's the first post ever!
```

Adding more such files in the same directory would result in more records.

#### 2. Single YAML file

For "smaller" models which don't have more than 2-3 fields, Flask-FileAlchemy
supports reading from an `_all.yml` file. In such a case, instead of adding one
file for every row, simply add all the rows in the `_all.yml` file inside the
table directory.

For the "blog" example, this would look like the following.

```yaml
- slug: first-post-ever
  title: First post ever!
  content: This blog post talks about how it's the first post ever!

- slug: second-post-ever
  title: second post ever!
  content: This blog post talks about how it's the second post ever!
 ```

#### 3. Markdown/Frontmatter

It's also possible to load data from Jekyll-style Markdown files containing
Frontmatter metadata.

In case of the blog example, it's possible to create a new `BlogPost` record by
defining a `data/blog_posts/first-post-ever.md` file with the following
content.

```markdown
---
slug: first-post-ever
title: First post ever!
---

This blog post talks about how it's the first post ever!
```

Please note that when defining data using markdown, the name of the column
associated with the main markdown body **needs** to be `content`.

#### 4. Configure and load

Finally, configure `Flask-FileAlchemy` with your setup and ask it to load all
your data.

```python
# configure Flask-FileAlchemy
app.config['FILEALCHEMY_DATA_DIR'] = os.path.join(
   os.path.dirname(os.path.realpath(__file__)), 'data'
)
app.config['FILEALCHEMY_MODELS'] = (BlogPost,)

# load tables
FileAlchemy(app, db).load_tables()
```

`Flask-FileAlchemy` then reads your data from the given directory, and stores
them in the data store of your choice that you configured `Flask-FileAlchemy`
with (the preference being `sqlite:///:memory:`).

Please note that it's not possible to write to this database using `db.session`.
Well, technically it's allowed, but the changes your app makes will only be
reflected in the in-memory data store but won't be persisted to disk.

## Contributing

Contributions are most welcome!

Please make sure you have Python 3.7+ and [Poetry] installed.

1. Git clone the repository -
   `git clone https://github.com/siddhantgoel/flask-filealchemy`.

2. Install the packages required for development - `poetry install`.

3. That's basically it. You should now be able to run the test suite -
   `poetry run pytest`.

[Flask]: https://flask.palletsprojects.com/
[Flask-SQLAlchemy]: https://flask-sqlalchemy.palletsprojects.com/
[Frozen-Flask]: https://pythonhosted.org/Frozen-Flask/
[Poetry]: https://python-poetry.org/
[SQLAlchemy]: https://www.sqlalchemy.org/

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/siddhantgoel/flask-filealchemy",
    "name": "flask-filealchemy",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7,<4.0",
    "maintainer_email": "",
    "keywords": "flask,sqlalchemy,yaml,plaintext,web",
    "author": "Siddhant Goel",
    "author_email": "me@sgoel.dev",
    "download_url": "https://files.pythonhosted.org/packages/fe/c5/e8cbf1da93707ca27f65a7dc43affdec4ae097e589359b2e5031e87708e2/flask_filealchemy-0.8.0.tar.gz",
    "platform": null,
    "description": "# Flask-FileAlchemy\n\n![](https://github.com/siddhantgoel/flask-filealchemy/workflows/flask-filealchemy/badge.svg) ![](https://badge.fury.io/py/flask-filealchemy.svg)\n\n`Flask-FileAlchemy` is a [Flask] extension that lets you use Markdown or YAML\nformatted plain-text files as the main data store for your apps.\n\n## Installation\n\n```bash\n$ pip install flask-filealchemy\n```\n\n## Background\n\nThe constraints on which data-store to use for applications that only have to\nrun locally are quite relaxed as compared to the ones that have to serve\nproduction traffic. For such applications, it's normally OK to sacrifice on\nperformance for ease of use.\n\nOne very strong use case here is generating static sites. While you can use\n[Frozen-Flask] to \"freeze\" an entire Flask application to a set of HTML files,\nyour application still needs to read data from somewhere. This means you'll need\nto set up a data store, which (locally) tends to be file based SQLite. While\nthat does the job extremely well, this also means executing SQL statements to\ninput data.\n\nDepending on how many data models you have and what types they contain, this can\nquickly get out of hand (imagine having to write an `INSERT` statement for a\nblog post).\n\nIn addition, you can't version control your data. Well, technically you can, but\nthe diffs won't make any sense to a human.\n\nFlask-FileAlchemy lets you use an alternative data store - plain text files.\n\nPlain text files have the advantage of being much easier to handle for a human.\nPlus, you can version control them so your application data and code are both\nchecked in together and share history.\n\nFlask-FileAlchemy lets you enter your data in Markdown or YAML formatted plain\ntext files and loads them according to the [SQLAlchemy] models you've defined\nusing [Flask-SQLAlchemy] This data is then put into whatever data store you're\nusing (in-memory SQLite works best) and is then ready for your app to query\nhowever it pleases.\n\nThis lets you retain the comfort of dynamic sites without compromising on the\nsimplicity of static sites.\n\n## Usage\n\n### Define data models\n\nDefine your data models using the standard (Flask-)SQLAlchemy API. As an\nexample, a `BlogPost` model can defined as follows.\n\n```python\napp = Flask(__name__)\n\n# configure Flask-SQLAlchemy\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'\n\ndb = SQLAlchemy()\n\ndb.init_app(app)\n\nclass BlogPost(db.Model):\n   __tablename__ = 'blog_posts'\n\n   slug = Column(String(255), primary_key=True)\n   title = Column(String(255), nullable=False)\n   content = Column(Text, nullable=False)\n```\n\n### Add some data\n\nNext, create a `data/` directory somewhere on your disk (to keep things simple,\nit's recommended to have this directory in the application root). For each model\nyou've defined, create a directory under this `data/` directory with the same\nname as the `__tablename__` attribute.\n\nWe currently support three different ways to define data.\n\n#### 1. Multiple YAML files\n\nThe first way is to have multiple YAML files inside the `data/<__tablename__>/`\ndirectory, each file corresponding to one record.\n\nIn case of the \"blog\" example, we can define a new `BlogPost` record by creating\nthe file `data/blog_posts/first-post-ever.yml` with the following content.\n\n```yaml\nslug: first-post-ever\ntitle: First post ever!\ncontent: |\n  This blog post talks about how it's the first post ever!\n```\n\nAdding more such files in the same directory would result in more records.\n\n#### 2. Single YAML file\n\nFor \"smaller\" models which don't have more than 2-3 fields, Flask-FileAlchemy\nsupports reading from an `_all.yml` file. In such a case, instead of adding one\nfile for every row, simply add all the rows in the `_all.yml` file inside the\ntable directory.\n\nFor the \"blog\" example, this would look like the following.\n\n```yaml\n- slug: first-post-ever\n  title: First post ever!\n  content: This blog post talks about how it's the first post ever!\n\n- slug: second-post-ever\n  title: second post ever!\n  content: This blog post talks about how it's the second post ever!\n ```\n\n#### 3. Markdown/Frontmatter\n\nIt's also possible to load data from Jekyll-style Markdown files containing\nFrontmatter metadata.\n\nIn case of the blog example, it's possible to create a new `BlogPost` record by\ndefining a `data/blog_posts/first-post-ever.md` file with the following\ncontent.\n\n```markdown\n---\nslug: first-post-ever\ntitle: First post ever!\n---\n\nThis blog post talks about how it's the first post ever!\n```\n\nPlease note that when defining data using markdown, the name of the column\nassociated with the main markdown body **needs** to be `content`.\n\n#### 4. Configure and load\n\nFinally, configure `Flask-FileAlchemy` with your setup and ask it to load all\nyour data.\n\n```python\n# configure Flask-FileAlchemy\napp.config['FILEALCHEMY_DATA_DIR'] = os.path.join(\n   os.path.dirname(os.path.realpath(__file__)), 'data'\n)\napp.config['FILEALCHEMY_MODELS'] = (BlogPost,)\n\n# load tables\nFileAlchemy(app, db).load_tables()\n```\n\n`Flask-FileAlchemy` then reads your data from the given directory, and stores\nthem in the data store of your choice that you configured `Flask-FileAlchemy`\nwith (the preference being `sqlite:///:memory:`).\n\nPlease note that it's not possible to write to this database using `db.session`.\nWell, technically it's allowed, but the changes your app makes will only be\nreflected in the in-memory data store but won't be persisted to disk.\n\n## Contributing\n\nContributions are most welcome!\n\nPlease make sure you have Python 3.7+ and [Poetry] installed.\n\n1. Git clone the repository -\n   `git clone https://github.com/siddhantgoel/flask-filealchemy`.\n\n2. Install the packages required for development - `poetry install`.\n\n3. That's basically it. You should now be able to run the test suite -\n   `poetry run pytest`.\n\n[Flask]: https://flask.palletsprojects.com/\n[Flask-SQLAlchemy]: https://flask-sqlalchemy.palletsprojects.com/\n[Frozen-Flask]: https://pythonhosted.org/Frozen-Flask/\n[Poetry]: https://python-poetry.org/\n[SQLAlchemy]: https://www.sqlalchemy.org/\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "YAML-formatted plain-text file based models for Flask backed by Flask-SQLAlchemy",
    "version": "0.8.0",
    "split_keywords": [
        "flask",
        "sqlalchemy",
        "yaml",
        "plaintext",
        "web"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "84d2c7001227537ba673266dc7fd299c",
                "sha256": "0baef54d6b09afd68be41b0b6d22dde0928f368cf2b662aa0a2d3b44da28ac39"
            },
            "downloads": -1,
            "filename": "flask_filealchemy-0.8.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "84d2c7001227537ba673266dc7fd299c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7,<4.0",
            "size": 7368,
            "upload_time": "2022-12-04T09:39:25",
            "upload_time_iso_8601": "2022-12-04T09:39:25.398614Z",
            "url": "https://files.pythonhosted.org/packages/f7/94/f7be017f27ba9414b4f633d7c4c76519a8a1343225ddab3ceef546543a7e/flask_filealchemy-0.8.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "413de2497b29817f19ea871bc678c44c",
                "sha256": "0adcc1d209973c3ee3d816b699e234cabbab744de9188bf845add40ff21eecd6"
            },
            "downloads": -1,
            "filename": "flask_filealchemy-0.8.0.tar.gz",
            "has_sig": false,
            "md5_digest": "413de2497b29817f19ea871bc678c44c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7,<4.0",
            "size": 7845,
            "upload_time": "2022-12-04T09:39:27",
            "upload_time_iso_8601": "2022-12-04T09:39:27.240213Z",
            "url": "https://files.pythonhosted.org/packages/fe/c5/e8cbf1da93707ca27f65a7dc43affdec4ae097e589359b2e5031e87708e2/flask_filealchemy-0.8.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-12-04 09:39:27",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "siddhantgoel",
    "github_project": "flask-filealchemy",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "flask-filealchemy"
}
        
Elapsed time: 0.26998s