darkKnight
darkKnight

Reputation: 83

Generate SQLite database in Flask REST API code

I am new to REST API and starting building first REST API app using Flask, SQLAlchemy & Marshmallow. This is my app.py file:

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

# Initialize App
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))

# Database Setup
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init db
db = SQLAlchemy(app)
# Init marshmallow
ma = Marshmallow(app)


# Product Class/Model
class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)
    description = db.Column(db.String(200))
    price = db.Column(db.Float)
    qty = db.Column(db.Integer)

    def __init__(self, name, description, price, qty):
        self.name = name
        self.description = description
        self.price = price
        self.qty = qty


# Product Schema
class ProductSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'description', 'price', 'qty')


# Init Schema
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)


# Create Product
@app.route('/product', methods=['POST'])
def add_product():
    name = request.json['name']
    description = request.json['description']
    price = request.json['price']
    qty = request.json['qty']

    new_product = Product(name, description, price, qty)

    db.session.add(new_product)
    db.session.commit()

    return product_schema.jsonify(new_product)


# Get All Products
@app.route('/receive', methods=['GET'])
def get_products():
    all_products = Product.query.all()
    result = products_schema.dump(all_products)
    return jsonify(result)


# Run the Server
if __name__ == '__main__':
    app.run(debug=True)

For generating SQLite database, I have to open python interactive shell and then there I have to do this:

from app import db
db.create_all()

But I have to genreate database from app.py itself so I am inserting the same commands inside app.py, but it's giving me error:

OperationalError: (sqlite3.OperationalError) no such table: product

How do I generate a database from app.py?

Upvotes: 0

Views: 1213

Answers (1)

MCcodemasher
MCcodemasher

Reputation: 98

Where are you placing your db.create_all()? The error may simply be a result of placement. When I copy and paste your code into PyCharm (running Python 3.7) it creates the DB fine when I place

db.create_all() 

immediately before

# Run the Server
if __name__ == '__main__':
    app.run(debug=True)

If you try to run db.create_all() before you instantiate the db object it will throw an error because db does not exist yet.

You should not need to use "from app import db" at all because the db object is declared up top.

Upvotes: 1

Related Questions