1

Trying to set up Flask and SQLAlchemy on Windows but I've been running into issues.

I've been using Flask-SQLAlchemy along with PostgreSQL 9.1.4 (32 bit) and the Psycopg2 package. Here are the relevant bits of code, I created a basic User model just to test that my DB is connecting, and committing.

The three bits of code would come from the __init__.py file of my application, the models.py file and my settings.py file.

When I try opening up my interactive prompt and try the code in the following link out I get a ProgrammingError exception (details in link).

What could be causing this? I followed the documentation and I'm simply confused as to what I'm doing wrong especially considering that I've also used Django with psycopg2 and PostgreSQL on Windows.

1
  • It seems the schema is not created. You need to create the db first, and assign the login to the db in postgresql; then you should be able to create the tables. Commented Jun 23, 2012 at 13:05

3 Answers 3

6

I had great help using this tutorial Flask Mega Tutorial

Sign up to request clarification or add additional context in comments.

Comments

4

At the time you execute create_all, models.py has never been imported, so no class is declared. Thus, create_all does not create any table.

To solve this problem, import models before running create_all or, even better, don't separate the db object from the model declaration.

Comments

0

Simple steps to use Flask SQLAlchemy:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

//employee.db database will get created in current python project

app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///employee.db'

db = SQLAlchemy(app)

class Employee(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(20))
    dept = db.Column(db.String(40))

To test this code you need to run your python shell

RUN IN PYTHON SHELL :

//This is going to create table create_all() method
from one_to_many import db
db.create_all()

//This is going to insert data into table
from one_to_many import Employee
new_emp = Employee(name="Viraj",dept="IT")
db.session.add(new_emp)
db.session.commit()

//To check or retrieve data use this 
show_all_data = Employee.query.all()
for i in show_all_data:
    print(i.id,i.name,i.dept)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.