flask-pgsql


Nameflask-pgsql JSON
Version 0.0.10 PyPI version JSON
download
home_pagehttps://github.com/thefcraft/flask_postgresql
SummaryA PostgreSQL library for Flask inspired by Flask-SQLAlchemy. This library provides an easy-to-use interface for interacting with PostgreSQL databases in Flask applications.
upload_time2024-03-20 16:14:24
maintainerNone
docs_urlNone
authorThefCraft
requires_pythonNone
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Flask PostgreSQL Library

The Flask PostgreSQL library provides a convenient interface for integrating PostgreSQL databases into Flask applications. This library simplifies database interactions by offering an easy-to-use API similar to Flask-SQLAlchemy.

## Installation

DEMO: i made [mediumClone](https://github.com/thefcraft/mediumClone/) using both Flask-SQLAlchemy and flask_postgresql with change of two three line of code.
In this demo i use flask_login library which is also supported by my flask_postgresql library.

You can install the Flask PostgreSQL library using pip:

```
pip install flask-pgsql --user
```

## TODO
- add support flask_login library ✅
    ```python
    from flask_login import UserMixin, LoginManager, ...
    class USERS(UserMixin, db.Model): ...
    ```
- use metaclass because Class properties are deprecated in Python 3.11 and will not be supported in Python 3.13
    ```python
    class BaseModel:
    ...
    @classmethod
    @property # Class properties are deprecated in Python 3.11 and will not be supported in Python 3.13
    def query(cls): ...
    ```
    Do somethig like this.
  
    ```python
    class MetaModel(type): ...
    class BaseModel(metaclass=MetaModel): ...
    ```

## Usage

### Works on existing code

```python
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'database\\database.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app) # Creating an SQLAlchemy instance
...
if __name__ == "__main__":
    if RESET:
        with app.app_context(): db.create_all()
```
replace it by
```python
from flask_postgresql import PostgreSQL
db = PostgreSQL(hostname=hostname, port=port, database=database, username=username, password=password)
...
if __name__ == "__main__":
    if RESET:
        db.create_all() # with app.app_context(): db.create_all() will also work
```
### array support
```python
class Test(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.Integer, array=True)

    def __repr__(self):
        return f"Test({self.id}, {self.data})"
db.create_all()
p = Test(data = [21, 24])
db.session.add(p)
db.session.commit()
Test.query.get(id=1).data #-> [21, 24]    
```

### Initializing the Database Connection

To initialize the PostgreSQL connection, import the `PostgreSQL` class from `flask_postgresql` and provide the necessary connection parameters:

```python
import os
from flask_postgresql import PostgreSQL

# Retrieve database connection parameters from environment variables
hostname = os.getenv("db_hostname")
port = int(os.getenv("db_port"))
database = os.getenv("db_database")
username = os.getenv("db_username")
password = os.getenv("db_password")

# Initialize the PostgreSQL connection
db = PostgreSQL(hostname=hostname, port=port, database=database, username=username, password=password)
```

### Defining Models

Define your database models by subclassing `db.Model`. Here's an example of defining `BLOGS` and `USERS` models:

```python
class BLOGS(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, nullable=False)
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(200), nullable=True)
    data = db.Column(db.Text, nullable=False)

    def __repr__(self):
        return f"{self.id}). Name : {self.user_id}, title: {self.title}, description: {self.description}, data: {self.data}"

class USERS(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    age = db.Column(db.Integer)
    is_active = db.Column(db.Boolean, default=True)
    bio = db.Column(db.Text)
    details = db.Column(db.JSON, nullable=True)
    profile_image = db.Column(db.LargeBinary)
    created_at = db.Column(db.DateTime, default=db.func.now())

    def __repr__(self):
        return f"Test({self.id}, {self.username}, {self.email}, {self.age}, {self.is_active}, {self.bio}, {self.profile_image}, {self.created_at})"
```

### Creating Tables

Create database tables using the `create_all()` method:

```python
db.create_all()
# or you can recreate any special table
# USERS.create()
# BLOGS.create()
```

### Querying Data

You can query data using the `query` attribute of your models:

```python
users = USERS.query.all()
user = USERS.query.get(id=12)
```

### Adding Data

You can add data to the database using the `add()` method:

```python
new_user = USERS(username="example_user")
db.session.add(new_user)
db.session.commit()
```

### Deleting Data

You can delete data from the database using the `delete()` method:

```python
user_to_delete = USERS.query.get(id)
user_to_delete.delete()
db.session.commit()
```

### Compatibility 
While the Flask PostgreSQL library is designed for Flask applications, it can also be used in other frameworks or standalone Python scripts that require PostgreSQL database integration.

## Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, feel free to open an issue or submit a pull request.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/thefcraft/flask_postgresql",
    "name": "flask-pgsql",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": null,
    "author": "ThefCraft",
    "author_email": "sisodiyalaksh@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/19/43/d8a2aed6d5d48232a4a5ed68f3f46d443321aaa2359b1ec64726ab3db68e/flask-pgsql-0.0.10.tar.gz",
    "platform": null,
    "description": "# Flask PostgreSQL Library\n\nThe Flask PostgreSQL library provides a convenient interface for integrating PostgreSQL databases into Flask applications. This library simplifies database interactions by offering an easy-to-use API similar to Flask-SQLAlchemy.\n\n## Installation\n\nDEMO: i made [mediumClone](https://github.com/thefcraft/mediumClone/) using both Flask-SQLAlchemy and flask_postgresql with change of two three line of code.\nIn this demo i use flask_login library which is also supported by my flask_postgresql library.\n\nYou can install the Flask PostgreSQL library using pip:\n\n```\npip install flask-pgsql --user\n```\n\n## TODO\n- add support flask_login library \u2705\n    ```python\n    from flask_login import UserMixin, LoginManager, ...\n    class USERS(UserMixin, db.Model): ...\n    ```\n- use metaclass because Class properties are deprecated in Python 3.11 and will not be supported in Python 3.13\n    ```python\n    class BaseModel:\n    ...\n    @classmethod\n    @property # Class properties are deprecated in Python 3.11 and will not be supported in Python 3.13\n    def query(cls): ...\n    ```\n    Do somethig like this.\n  \n    ```python\n    class MetaModel(type): ...\n    class BaseModel(metaclass=MetaModel): ...\n    ```\n\n## Usage\n\n### Works on existing code\n\n```python\nfrom flask_sqlalchemy import SQLAlchemy\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'database\\\\database.db')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app) # Creating an SQLAlchemy instance\n...\nif __name__ == \"__main__\":\n    if RESET:\n        with app.app_context(): db.create_all()\n```\nreplace it by\n```python\nfrom flask_postgresql import PostgreSQL\ndb = PostgreSQL(hostname=hostname, port=port, database=database, username=username, password=password)\n...\nif __name__ == \"__main__\":\n    if RESET:\n        db.create_all() # with app.app_context(): db.create_all() will also work\n```\n### array support\n```python\nclass Test(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    data = db.Column(db.Integer, array=True)\n\n    def __repr__(self):\n        return f\"Test({self.id}, {self.data})\"\ndb.create_all()\np = Test(data = [21, 24])\ndb.session.add(p)\ndb.session.commit()\nTest.query.get(id=1).data #-> [21, 24]    \n```\n\n### Initializing the Database Connection\n\nTo initialize the PostgreSQL connection, import the `PostgreSQL` class from `flask_postgresql` and provide the necessary connection parameters:\n\n```python\nimport os\nfrom flask_postgresql import PostgreSQL\n\n# Retrieve database connection parameters from environment variables\nhostname = os.getenv(\"db_hostname\")\nport = int(os.getenv(\"db_port\"))\ndatabase = os.getenv(\"db_database\")\nusername = os.getenv(\"db_username\")\npassword = os.getenv(\"db_password\")\n\n# Initialize the PostgreSQL connection\ndb = PostgreSQL(hostname=hostname, port=port, database=database, username=username, password=password)\n```\n\n### Defining Models\n\nDefine your database models by subclassing `db.Model`. Here's an example of defining `BLOGS` and `USERS` models:\n\n```python\nclass BLOGS(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    user_id = db.Column(db.Integer, nullable=False)\n    title = db.Column(db.String(100), nullable=False)\n    description = db.Column(db.String(200), nullable=True)\n    data = db.Column(db.Text, nullable=False)\n\n    def __repr__(self):\n        return f\"{self.id}). Name : {self.user_id}, title: {self.title}, description: {self.description}, data: {self.data}\"\n\nclass USERS(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    username = db.Column(db.String(80), unique=True, nullable=False)\n    email = db.Column(db.String(120), unique=True, nullable=False)\n    age = db.Column(db.Integer)\n    is_active = db.Column(db.Boolean, default=True)\n    bio = db.Column(db.Text)\n    details = db.Column(db.JSON, nullable=True)\n    profile_image = db.Column(db.LargeBinary)\n    created_at = db.Column(db.DateTime, default=db.func.now())\n\n    def __repr__(self):\n        return f\"Test({self.id}, {self.username}, {self.email}, {self.age}, {self.is_active}, {self.bio}, {self.profile_image}, {self.created_at})\"\n```\n\n### Creating Tables\n\nCreate database tables using the `create_all()` method:\n\n```python\ndb.create_all()\n# or you can recreate any special table\n# USERS.create()\n# BLOGS.create()\n```\n\n### Querying Data\n\nYou can query data using the `query` attribute of your models:\n\n```python\nusers = USERS.query.all()\nuser = USERS.query.get(id=12)\n```\n\n### Adding Data\n\nYou can add data to the database using the `add()` method:\n\n```python\nnew_user = USERS(username=\"example_user\")\ndb.session.add(new_user)\ndb.session.commit()\n```\n\n### Deleting Data\n\nYou can delete data from the database using the `delete()` method:\n\n```python\nuser_to_delete = USERS.query.get(id)\nuser_to_delete.delete()\ndb.session.commit()\n```\n\n### Compatibility \nWhile the Flask PostgreSQL library is designed for Flask applications, it can also be used in other frameworks or standalone Python scripts that require PostgreSQL database integration.\n\n## Contributing\n\nContributions are welcome! If you find any issues or have suggestions for improvements, feel free to open an issue or submit a pull request.\n\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A PostgreSQL library for Flask inspired by Flask-SQLAlchemy. This library provides an easy-to-use interface for interacting with PostgreSQL databases in Flask applications.",
    "version": "0.0.10",
    "project_urls": {
        "Homepage": "https://github.com/thefcraft/flask_postgresql"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1943d8a2aed6d5d48232a4a5ed68f3f46d443321aaa2359b1ec64726ab3db68e",
                "md5": "4af04ae4123bae590bc9f0ca7d485116",
                "sha256": "b877254cc97d6fb61f6904447e6fdab32a9f281422e28ee81cf7e0da04419ba3"
            },
            "downloads": -1,
            "filename": "flask-pgsql-0.0.10.tar.gz",
            "has_sig": false,
            "md5_digest": "4af04ae4123bae590bc9f0ca7d485116",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 6197,
            "upload_time": "2024-03-20T16:14:24",
            "upload_time_iso_8601": "2024-03-20T16:14:24.335353Z",
            "url": "https://files.pythonhosted.org/packages/19/43/d8a2aed6d5d48232a4a5ed68f3f46d443321aaa2359b1ec64726ab3db68e/flask-pgsql-0.0.10.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-20 16:14:24",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "thefcraft",
    "github_project": "flask_postgresql",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "flask-pgsql"
}
        
Elapsed time: 0.74898s