烧瓶中的SQLalchemy问题

时间:2019-10-23 16:02:53

标签: python flask sqlalchemy

我正在从youtube学习烧瓶。在当前的讲座中,我们正在使用数据库

首先我们安装了sqlalchemy     pip install flask-sqlalchemy 然后在我的主要flaskblog.py应用中

enter image description here

#url_for is for importing css files
from flask import Flask,render_template,url_for,flash,redirect
from flask_sqlalchemy import SQLAlchemy
from forms import RegistrationForm,LoginForm 
app = Flask(__name__)


app.config['SECRET_KEY']='c3dfea8abf7e49794dfcdd1c8e02024d' #value is random


# /// means relative path from the curret path
#site.db will be created in the project directory
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db'


#creating instance of database
db=SQLAlchemy(app)


#to create a user model
class User(db.Model):
    #adding colums for table
    id=db.Column(db.Integer,primary_key=True)
    username=db.Column(db.String(20),unique=True,nullable=False)#max 20 characters.should be unique and compulsory
    email=db.Column(db.String(120),unique=True,nullable=False)
    image_file=username=db.Column(db.String(20),nullable=False,default='default.jpg')
    password=db.Column(db.String(60),nullable=False)


    #creating relationship between user and post table
    #backref is adding column to Post model.
    posts=db.relationship('Post',backref='author',lazy=True)


    #how our object is prined
    def __repr__(self):
        return f"User('{self.username}','{self.email}','{self.image_file}')"


class Post(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    title:db.Column(db.String(100),unique=True,nullable=False)
    date_posted=db.Column(db.DateTime,nullable=False,default=datetime.utcnow) #saving dates automatically
    content=db.Column(db.text,nullabe=False)
    user_id=db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)


    def __repr__(self):
        return f"Post('{self.title}','{self.date_posted}')"

在vscode中,我遇到了奇怪的错误-
     “ SQLAlchemy”的实例没有“列”成员,
     “ SQLAlchemy”的实例没有“ Integer”成员,
     “ SQLAlchemy”的实例没有“ String”成员, enter image description here 我忽略了它,导师告诉我将其添加到当前文件夹的终端

$from flaskblog import db
cant read /var/mail/flaskblog

我不知道发生了什么。我无法前进就需要帮助。
当我运行文件时
enter image description here 这是用于完整代码的insructors github页面-https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Flask_Blog/04-Database/flaskblog.py

2 个答案:

答案 0 :(得分:0)

我看到其未运行的原因之一是(根据回溯),第38行db.text应该是db.String

答案 1 :(得分:-1)

抱歉,从bash而不是python控制台运行import db命令时犯了一个非常愚蠢的错误