How do I sow sql-alchemy database from bulb

I am new to python, I just learned how to create api using jar restless sql-alchemy. However, I would like to seed the database with random values. How do I achieve this? Please help. Here is the api code ...

import flask import flask.ext.sqlalchemy import flask.ext.restless import datetime DATABASE = 'sqlite:///tmp/test.db' #Create the Flask application and the FLask-SQLALchemy object app = flask.Flask(__name__) app.config ['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE db = flask.ext.sqlalchemy.SQLAlchemy(app) #create Flask-SQLAlchemy models class TodoItem(db.Model): id = db.Column(db.Integer, primary_key = True) todo = db.Column(db.Unicode) priority = db.Column(db.SmallInteger) due_date = db.Column(db.Date) #Create database tables db.create_all() #Create Flask restless api manager manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db = db) #Create api end points manager.create_api(TodoItem, methods = ['GET','POST','DELETE','PUT'], results_per_page = 20) #Start flask loop app.run() 
+5
source share
1 answer

From another newbie, forgerypy and the subscription library3 are available for this purpose (although they look as if they weren’t affected a bit).

A simple example of using 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() 

Then you call the generate_fake_data method in the shell session.

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

0
source

Source: https://habr.com/ru/post/1209367/


All Articles