简体   繁体   English

有哪些方法可以播种 Flask 应用程序?

[英]What ways are there for seeding a Flask app?

I am about to deploy a very simple flask app on aws Elastic Beanstalk.我即将在 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我只需要它第一次运行一次

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.前段时间我对我的新 Flask 应用程序有类似的需求,我通过使用Faker库创建一个函数来添加一些初始数据来解决它,然后使用Click库中的 cli 命令调用它,因为我只需要运行它一次。 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这个函数将被 Cli 命令调用来完成这个技巧

@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.最后,在命令行上调用 cli 命令。

$ 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.和 Faker 一起点击非常有帮助,希望它很适合你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM