简体   繁体   English

如何使用 flask 从 SQLalchemy 检索一行

[英]How to retrieve a row from SQLalchemy with flask

I am learning how to use SQLalchemy and databases in general with flask.我正在学习如何将 SQLalchemy 和数据库与 flask 一起使用。 I am following a tutorial and it uses the below classes and files.我正在关注一个教程,它使用以下类和文件。

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database

To show an inserted row in the database, the tutorial uses the following:为了在数据库中显示插入的行,本教程使用以下内容:

from app.models import User
>>> u = User(username='susan', email='susan@example.com')
>>> u
<User susan>

My problem is that I can not display the same output.我的问题是我无法显示相同的 output。 I mean when I code the the statement, I get an error我的意思是当我对语句进行编码时,我得到一个错误

from app.models import User从 app.models 导入用户
ImportError: No module named app.models ImportError:没有名为 app.models 的模块

Please let me know how to adapt the posted code so I can retrieve data from database请让我知道如何调整发布的代码,以便我可以从数据库中检索数据

Folder Structure :文件夹结构

d:\xxx\xxx\db1\app\models
d:\xxx\xxx\db1\__init__
d:\xxx\xxx\db1\config

** init **: **初始化**:

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import routes, models

config :配置

import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
# ...
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
    'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False

models :型号

from app import db
from app.models import User

class User(db.Model):
    id = db.Column(db.Integer, primaty_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

def __repr__(self):
    return '<User {}>'.format(self.username)    

You cannot import User on the same module where models is declared, so I don't think If you need that second line in models.py, Try commenting and see what happens您不能在声明模型的同一模块上导入用户,所以我不认为如果您需要 models.py 中的第二行,请尝试评论并看看会发生什么

from app import db
from app.models import User ## I think the problems is 

class User(db.Model):
    id = db.Column(db.Integer, primaty_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

def __repr__(self):
    return '<User {}>'.format(self.username)  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM