问题
I''m still new to Flask/SQLAlchemy. I made this where I was having context issues. I've managed to fixed the SQLAlchemey issue, but now I am unable to retrieve data from my postgres DB
I have a separate directory for models, routes and a main app.py file. I'm initializing my db in app.py, importing the db in models.model and creating a basic class. I've managed to add data manually in python terminal and by hard coding a new class in the app.py file. I see this table/data in postgres.
The next thing I'd like to do is retrieve this data in one of my routes, and send it as part of a Get request. Below is code for all 2 files.
app.py
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from my_routes.user import User
app = Flask(__name__)
app.config.from_pyfile('config.py')
api = Api(app)
db = SQLAlchemy(app)
from models.model import Task
db.create_all()
db.session.commit()
# task = Task(4, 'nothing yet')
# db.session.add(task)
# db.session.commit()
# task = Task.query.all()
# print (task)
# api.add_resource(root.HelloWorld, '/')
api.add_resource(User, '/user')
# api.add_resource(MyTest, '/test')
if __name__ == '__main__':
app.run()
models.model
from app import db
class Task(db.Model):
id = db.Column('id', db.Integer, primary_key=True)
data = db.Column('data', db.Unicode)
def __init__(self, id, data):
self.id = id
self.data = data
routes.my_test.MyTest
from flask_restful import Resource
from models.model import Task
class MyTest(Resource):
def get(self):
first_task = Task.query.first()
return {'test route': first_task}
When I try to run app.py, I get the following error:
ImportError: cannot import name 'Task'
How do I go about fixing this import error, and making data from my Task table available to all my routes?
来源:https://stackoverflow.com/questions/49102195/flask-sqlalchemy-cannot-retrieve-data-from-db-and-send-it-in-get-request