2

I am about to deploy a very simple flask app on aws Elastic Beanstalk. What ways do I have to put some seed data so that the live instance has some users?

from dateutil import parser
from datetime import datetime
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
ma = Marshmallow(app)


.
.
.

@app.route('/user/<id>', methods=['PUT'])
def update_user(id):
    user = User.query.get(id)
    weight = request.json['weight']
    user.weight = weight
    db.session.commit()
    return user_schema.jsonify(user)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    weight = db.Column(db.Float)
    workouts = db.relationship('Workout', backref='user', lazy=True)

    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

class UserSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'weight')

user_schema = UserSchema(strict=True)
users_schema = UserSchema(many=True, strict=True)

.
.
.

db.create_all()

if __name__ == '__main__':
    app.run(debug=True)

Again, I want the live instance to have some seed data (I know that I can just create some entries using the console locally). I was thinking that I should put include seeds in the block

if __name__ == '__main__':
    user1 = User('Jon',75)
    db.session.add(user1)
    db.session.commit()

But am not sure what the proper way to do this is. Also wouldn't this run every time the application is started? I just need it to run once the very first time

VC.One
  • 14,790
  • 4
  • 25
  • 57
irmaz
  • 51
  • 2
  • 4
  • 1
    Possible duplicate of [How do I seed a flask sql-alchemy database](https://stackoverflow.com/questions/27528627/how-do-i-seed-a-flask-sql-alchemy-database) – realr Jul 28 '19 at 20:32

1 Answers1

3

I had a similar need a time ago for my new Flask app, and I solved it by creating a function with the Faker library to add some initial data, then later called it using a cli command from Click library, as I needed just to run it once. I guess it can work for you as well. Note that both are external libraries.

Here's an example that might work for your case - do the modifications as you need:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

import click
import random

from faker import Faker


app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))

fake = Faker() #initialize faker service

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    weight = db.Column(db.Float)
    workouts = db.relationship('Workout', backref='user', lazy=True)

    def __init__(self, name, weight):
        self.name = name
        self.weight = weight
rest of your code...

This function will be called by the Cli command to do the trick

@click.command()
@click.option('--count', default=20, help='number of users to be generated')
def add_users(count):
    """
    Generate fake users.
    """
    random_usernames = []
    data = []

    click.echo('Working...')

    # Ensure we get the count number of usernames.

    for i in range(0, count):
        random_usernames.append(fake.first_name())

    random_usernames = list(set(random_usernames))

    while True:
        if len(random_usernames) == 0:
            break

        username = random_usernames.pop()
        weight = random.uniform(30.5,260.5)

        user = User(username, weight)
        db.session.add(user)
        db.session.commit()


    return click.echo('{} users were added successfully to the database.'.format(count))

if __name__ == '__main__':
    add_users()

Finally, call the cli command on your command line.

$ python app.py --count=50
Working...
50 users were added successfully to the database.

Click along with Faker are very helpful, hope it suits you nicely.

Kenny Aires
  • 1,338
  • 12
  • 16