【问题标题】:SQLalchemy issue in flask烧瓶中的 SQLalchemy 问题
【发布时间】:2020-02-19 22:36:11
【问题描述】:

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

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

#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”的实例没有“整数”成员,
'SQLAlchemy' 的实例没有'String' 成员, 我忽略了它,教练告诉我将它添加到当前文件夹的终端

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

我不知道发生了什么。需要帮助,因为我无法前进。
当我运行文件时
这是完整代码的导师github页面-https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Flask_Blog/04-Database/flaskblog.py

【问题讨论】:

  • 你有这个title:db.Column(db.String(100),unique=True,nullable=False) 而不是title=db.Column(db.String(100),unique=True,nullable=False)。这可能不是问题,但这是一个问题
  • 更正了错字,但机器人问题仍然存在。
  • 哦,是的,这不是问题:)。 db 似乎是罪魁祸首。这些是错误还是警告?我看不到你的用户界面,但似乎某种 linter 说db 对象没有Column、Integer 或String 属性。午餐应用程序时代码是否失败?
  • 所有数据库都在红色下。并且“'SQLAlchemy'的实例...”在问题菜单下。总共有22个问题
  • 问题并不意味着代码应用不会吃午饭。我只是问应用程序是否根本无法运行

标签: python flask sqlalchemy


【解决方案1】:

我看到它没有运行的一个原因是(根据回溯),第 38 行 db.text 应该是 db.String。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-05-21
      • 2016-01-15
      • 2012-12-29
      • 2014-07-20
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多