How do I seed a flask sql-alchemy database

后端 未结 2 1579
旧巷少年郎
旧巷少年郎 2021-01-04 08:19

I am new at python, I just learnt how to create an api using flask restless and flask sql-alchemy. I however would like to seed the database with random values. How do I ach

2条回答
  •  醉梦人生
    2021-01-04 08:59

    From another newbie, the forgerypy and forgerypy3 libraries are available for this purpose (though they look like they haven't been touched in a bit).

    A simple example of how to use them by adding them to your model:

    class TodoItem(db.Model):
    
        ....
    
        @staticmethod
        def generate_fake_data(records=10):
            import forgery_py
            from random import randint
            for record in records:
                todo = TodoItem(todo=forgery_py.lorem_ipsum.word(),
                                due_date=forgery_py.date.date(),
                                priority=randint(1,4))
                db.session.add(todo)
            try:
                db.session.commit()
            except:
                db.session.rollback()
    

    You would then call the generate_fake_data method in a shell session.

    And Miguel Grinberg's Flask Web Development (the O'Reilly book, not blog) chapter 11 is a good resource for this.

提交回复
热议问题