📜  Flask SQLAlchemy(1)

📅  最后修改于: 2023-12-03 15:15:05.776000             🧑  作者: Mango

Flask SQLAlchemy

Flask SQLAlchemy is a Python tool that serves as a bridge between Flask and SQLAlchemy. Flask is a micro-framework web application development tool, while SQLAlchemy is an Object Relational Mapping (ORM) and database toolkit. With Flask SQLAlchemy, you can create systems using Flask and leverage the power of SQLAlchemy.

Features
  • Easy database schema creation
  • Raw SQL statement support
  • Efficient SQL connections
  • Automatic handling of connections and transactions
Installation

You can install Flask SQLAlchemy using pip:

pip install flask_sqlalchemy
Usage

To use Flask SQLAlchemy, you need to create an instance of it and pass in the Flask application object. Here's an example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/mydatabase'
db = SQLAlchemy(app)

With this code, we create a new Flask application and configure it to use PostgreSQL as its database. We also create a new instance of SQLAlchemy and pass the Flask application object to it.

Here's how you create a new database schema using Flask SQLAlchemy:

class User(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)

    def __repr__(self):
        return '<User %r>' % self.username

The User class inherits from db.Model, which is a base model class provided by Flask SQLAlchemy. We define the fields we want for our schema as attributes in this class. We can then use this class to create new entries in our database.

Here's how we can use Flask SQLAlchemy to create a new user:

new_user = User(username='foo', email='foo@example.com')
db.session.add(new_user)
db.session.commit()

First, we create a new User instance with the required fields. We then add this instance to the session and commit the changes to the database. Flask SQLAlchemy takes care of creating the necessary SQL statements and handling the database connection.

Conclusion

Flask SQLAlchemy makes it easy to use the powerful SQLAlchemy toolkit with Flask. It simplifies the process of creating database schemas, executing raw SQL statements, and managing database connections, making it a valuable tool for any Flask developer.