Search code examples
pythondatabaseflaskruntime-errorflask-sqlalchemy

how can i get rid of the runtime error and name error?


im watching a flask tutorial and ive followed step by step perfectly. so now we are in databases and im using sqlalchemy. the part that got me confused was when i tried to convert the data into a table (thats what the guy said) and after typing db.create_all(), terminal gave me a runtime error. then i saw that everyone was having the same issue and somebody said to implement the app.app_context()push() command line before the createall. however it gave another error but this time it says that name 'app' was not defined.

# import the flask module
from flask import Flask, render_template
# we import the database tool
from flask_sqlalchemy import SQLAlchemy



# we set the class variable
app = Flask(__name__)

   
    
# we set the app in order to recognize the database and we give it a name
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db'

# we create our variable where the db is gonna be stored 
db = SQLAlchemy(app)  # we pass our app variable as a parameter

# we create the class model
class Item(db.Model):
    # parameters after specifying the type of database
    # --> (data type(optional : length), nullable, unique)
    # the primary key parameter is only gonna be used on the id
    id = db.Column(db.Integer(), primary_key = True)
    name = db.Column(db.String(length = 30), nullable = False, unique = True)
    price = db.Column(db.Integer(), nullable = False)
    barcode = db.Column(db.String(length = 12), nullable = False, unique = True)
        
    description = db.Column(db.String(length = 500), nullable = False, unique = True)

# we set the route (url)
@app.route('/')   # decorator
# we set the main function
def home_page():
    return render_template('home.html')

@app.route('/market')
def market():

    items = [
    {'id': 1, 'name': 'Phone', 'barcode': '893212299897', 'price': '$500'},
    {'id': 2, 'name': 'Laptop', 'barcode': '123985473165', 'price': '$900'},
    {'id': 3, 'name': 'Keyboard', 'barcode': '231985128446', 'price': '$150'}
    ]
    # primer parametro será nuestro archivo html
    return render_template('market.html', item_name = 'Phones', items = items)  # colocar el segundo parametro en el archivo html

enter image description here


Solution

  • In order to use your application in the python console, it is necessary to import it. In addition, the error message indicates that a syntax error has occurred due to a missing period.

    I would advise you to use the flask shell instead of the python console, which initializes the application context upon startup.

    flask --app market shell
    

    A push is then not necessary and you can create the tables directly after importing the database.

    from market import db, Item
    db.create_all()