我使用pycharm 5.0和python3.5。我通过pycharm的内置函数下载所有的liarbry(setting-project-project interpreter - “+”)。其他库看起来很好,但是烧瓶出现了一些问题-SQLAlchemy。
我成功导入了flask-SQLAlchemy。但是,pycharm提醒我“类'SQLAlchemy'中的”未解析的属性引用'Column'。“在类'SQLAlchemy'中未解析的属性引用'关系'”等等。
我尝试了一些方法,但它们没有用。例如:1.restart 2.remove and redownload 3.refresh cache.which提到PyCharm shows unresolved references error for valid code
代码:
from flask import Flask, redirect, render_template, session, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from wtforms import StringField, SubmitField
import os
from wtforms.validators import data_required
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] =\
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role', lazy='dynamic')
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username
我该如何解决这个问题?
答案 0 :(得分:1)
flask_sqlalchemy.SQLAlchemy
类的构造函数调用_include_sqlalchemy
,它将sqlalchemy
和sqlalchemy.orm
的所有属性附加到其实例。
这仅在运行时完成,而不是由PyCharm的代码检查检测到。
要求flask_sqlalchemy
使用更标准的方式导入这些属性,例如from sqlalchemy import *
。但是这会将属性导入flask_sqlalchemy
模块而不是SQLAlchemy
的每个实例,从而改变他们访问的方式。
我不是Python或SQLAlchemy专家,并且不会判断这是否是好设计,但你可以在https://github.com/mitsuhiko/flask-sqlalchemy上打开一个问题并在那里讨论。
答案 1 :(得分:0)
这是我的工作。
from flask_sqlalchemy import SQLAlchemy
from typing import Callable
class MySQLAlchemy(SQLAlchemy): # Or you can add the below code on the SQLAlchemy directly if you think to modify the package code is acceptable.
Column: Callable # Use the typing to tell the IDE what the type is.
String: Callable
Integer: Callable
db = MySQLAlchemy(app)
class User(db.Model, UserMixin):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20)) # The message will not show: Unresolved attribute reference 'Column' for class 'SQLAlchemy'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def create_test_data():
db.create_all()
test_user = User(name='Frank') # I add __init__, so it will not show you ``Unexpected argument``
db.session.add(test_user)
db.session.commit()