asked    Joanne     2018-10-22       python       25 view        2 Answers

[SOLVED] Python iterate through object to create tables with Flask-SQLAlchemy

EDITED I've been trying to create an class that will allow me to iterate through a list, or dictionary, and generate tables and rows. The code starts as follows:

from flask_sqlalchemy import SQLAlchemy as sa
from flask import Flask as fl
import pymysql
pymysql.install_as_MySQLdb()

app = fl(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:the_other_stuff'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] =False
DEBUG =True
db = sa(app)

a=['some_stuff','gaaahhhh','lalala','rawr','pizza']

class test(db.Model):
    __tablename__ = 'stuff'
    id = db.Column('id', db.Integer, primary_key = True)
    data = db.Column('data', db.Unicode(50))

    def __init__(self, id, data):
        self.id = id
        self.data = data

def stuff():
    for i in range(len(a)):
        data= a[i]
        i = i + 1
        id = i
        db.session.add(test(id,data))
    db.create_all()
    return db.session.commit()
stuff()

I'm still going to try and structure it so that it can take a dictionary, or list, and then add the key as the table name if it is a dict. If someone has that code, I won't argue with you sharing, but if not I'll post when that is done.

  2 Answers  

        answered    Charlotte     2018-10-22      

use db.session.add / db.session.commit. db object is initialized from flask_sqlalchemy. It is not db.Session.



        answered    Louis     2018-10-22      

The below code auto inserts data into a one-to-many relationship table set. The recursive function acts like a while loop (%timeit showed the same results for both) I just like the way it looks over a while loop. The function will index to a list in a list, I was going 3 deep but modified the loops to simply. This was originally designed to push a list like so: list[a][i][0] each zero value inside every [i] was the same value type, I set it to only do [a][i] to keep it a little more simple, and so it could be used as as base if someone liked it. [a][i][0] was very fast, but [a][i] might be better off as a list of pd.DataFrame, instead of as np.array. If [i] is not going to the same db.Column() you'll have to declare one for each set of [i] and figure out a way of indexing through it.
A table generator involves a class generator with a base class. I don't have a working example, but can upload when I do

import numpy as np
from flask_sqlalchemy import SQLAlchemy as sa
from flask import Flask as fl
import pymysql
pymysql.install_as_MySQLdb()

app = fl(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:the_other_stuff'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] =False
DEBUG =True
db = sa(app)

list=[np.array(np.ones(100)),np.array(np.ones(100)),np.array(np.ones(100)),
      np.array(np.ones(100)),np.array(np.ones(100))]

class Parent(db.Model):

    id = db.Column('id', db.Integer, primary_key=True)
    data= db.Column('data', db.VARCHAR(45))

    _child = db.relationship('child', backref='parent', lazy=True)

    def __init__(self, data):
        self.data = data

    def __repr__(self):
        return '<Parent %r>' % self.id

class Child(db.Model):

    id = db.Column('id', db.Integer, primary_key = True)
    data = db.Column('data', db.VARCHAR(45))
    parent_id = db.Column(db.Integer, db.ForeignKey('Parent.id'))
    parent = db.relationship('Parent')

    def __init__(self,data):
        self.data = data

    def __repr__(self):
        return '<Child %r>' % self.id


def child_loop(i = 0):
    for a in range(len(list)):
        with db.session.no_autoflush:
            try:
                p = Parent(symbol_col=data[a])
                c = child(data = list[a][i])
                s.c.append(child)
                db.session.add(p)
                db.session.add(c)

            except exc.IntegrityError as e:
                db.session.rollback()

    i = i + 1
    if a < len(list[0]):
        child_loop(i = i)
    return print('inserted open_close')
child_loop(i=0)




Your Answer





 2018-10-22         Zara

Nlog Log IP Address from NetCore Library Project

I have a VS 2017 solution with multiple projects, I have a separated project with the NLog methods to use it from other projects for not include NLog in all projects.NetCore Rest APINetCore InfraestructureNetCore Database And persistenceNetCore LoggerOther NetStandard Projects with helpers and ViewModel ClassesI want to Log Client IP Address and user if it's logged in. I have seen that I have to use a template in the NLog.config, but it is not working and the log IPAddress field is empty.What's the correct way to do it?NLog.Config<extensions> <add assembly="NL...
 c#                     1 answers                     104 view
 2018-10-22         Maureen

ASP.NET Core 2.0 request failed

I have the following API controller: [HttpPost] public async Task Post([FromBody]Statistics value) { if(_user == null) _user = await _userManager.GetUserAsync(HttpContext.User); if(_user.Statistics == null) _user.Statistics = new List<Statistics>(); _user.Statistics.Add(value); Context.SaveChanges(); }I'm trying to send some data:$("#submit-button-clicked").click(function () { $.ajax({ url: 'api/Statistics ', type: 'POST', dataType: "json", ...
 c#                     2 answers                     105 view
 2018-10-22         Olga

User.Identity.Name is null in Asp.Net Core 2.x web application using Windows Authentication

ProblemWhen hosting an Asp.Net Core 2.0 or 2.1 Web Application behind IIS with Windows Authentication set to true, and Anonymous Authentication set to false, the User.Identity.Name property is null and User.Identity.IsAuthenticated is false.According to the documentation here, Windows Authentication should just work in Asp.Net Core 2.x when hosting with IIS.BackgroundI'm in the process of migrating an Asp.Net 4.x MVC application over to Asp.Net Core following the Migrate from ASP.NET MVC to ASP.NET Core MVC guide.I'm testing the site on a server that is currently hosting As...
 asp.net-core-2.0                     1 answers                     103 view