-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd_data.py
45 lines (36 loc) · 1.33 KB
/
add_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import random as rand
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc
import resources.sample_data as data
from models.accounts import AccountsModel
# import models here
from models.products import ProductsModel
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
db.init_app(app)
products = []
accounts = []
for product in data.products:
productModel = ProductsModel(name=product['name'], category=product['category'], description=product['description'],
price=product['price'], condition=product['condition'])
products.append(productModel)
for account in data.accounts:
accountModel = AccountsModel(email=account['email'], username=account['username'], confirmed=account['confirmed'])
accountModel.hash_password(account['password'])
accounts.append(accountModel)
# Relationship between products and user
for product in products:
user = rand.choice(accounts)
i = accounts.index(user)
product.user_id = accounts[i].email
try:
db.session.add_all(products)
db.session.add_all(accounts)
db.session.commit()
print('Data added successfully')
except exc.SQLAlchemyError:
print('Error while adding data')
db.session.rollback()