Ask Your Question
1

How do I retrieve information from an already established database using Flask Sqlalchemy?

asked 2023-06-16 09:27:46 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-16 09:52:02 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-16 09:27:46 +0000

Seen: 11 times

Last updated: Jun 16 '23