How do I seed a flask sql-alchemy database

后端 未结 2 1608
旧巷少年郎
旧巷少年郎 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:58

    I had a similar question and did some research, found something that worked.

    The pattern I am seeing is based on registering a Flask CLI custom command, something like: flask seed.

    This would look like this given your example. First, import the following into your api code file (let's say you have it named server.py):

    from flask.cli import with_appcontext
    

    (I see you do import flask but I would just add you should change these to from flask import what_you_need)

    Next, create a function that does the seeding for your project:

    @with_appcontext
    def seed():
       """Seed the database."""
       todo1 = TodoItem(...).save()
       todo2 = TodoItem(...).save()
       todo3 = TodoItem(...).save()
    

    Finally, register these command with your flask application:

    def register_commands(app):
        """Register CLI commands."""
        app.cli.add_command(seed)
    

    After you've configured you're application, make sure you call register_commands to register the commands:

    register_commands(app)
    

    At this point, you should be able to run: flask seed. You can add more functions (maybe a flask reset) using the same pattern.

提交回复
热议问题