Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To retrieve data from an already established database using Flask Sqlalchemy, you can follow the following steps:

  1. Import the necessary modules:
from flask import Flask from flask_sqlalchemy import SQLAlchemy 
  1. Initialize the Flask app and the Sqlalchemy object:
app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'database_connection_string' db = SQLAlchemy(app) 
  1. Define the database model:
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) password = db.Column(db.String(80), nullable=False) 
  1. Query the database to retrieve the data:
# Retrieve all users users = User.query.all() # Retrieve a specific user by id user = User.query.get(id) # Retrieve a specific user by username user = User.query.filter_by(username='username').first() 
  1. Use the retrieved data as needed in your application.

Note: Make sure to replace 'databaseconnectionstring' with the actual connection string for your database.