Member-only story
In my previous article, “Python Flask — Database Modeling, Part One”. I introduced Python Flask database modeling between SQL and NoSQL, and demoed with a simple Flask app using SQLAlchemy. In this article, let’s continue our database modeling journey and add more endpoints to our simple Flask app.
A quick recap of our Flask app:
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
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
@app.route('/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([{'id': user.id, 'username': user.username, 'email': user.email} for user in users])
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
In the above app.py
, we define a User
model with id
, name
, and summary
fields, representing a table in a SQLite database located at /tmp/test.db
. The User
model includes an initializer for setting its attributes and a representation method.