Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 属性错误:';str';对象没有属性'_萨乌州';_Python_Flask_Sqlalchemy_Flask Sqlalchemy - Fatal编程技术网

Python 属性错误:';str';对象没有属性'_萨乌州';

Python 属性错误:';str';对象没有属性'_萨乌州';,python,flask,sqlalchemy,flask-sqlalchemy,Python,Flask,Sqlalchemy,Flask Sqlalchemy,我想评估链接到两个不同用户的值。我创建了一个不同的表来跟踪用户以前的体验和他们感兴趣的体验,并将它们链接到用户。我有一个匹配函数,试图找到最相似的用户,但它给出了标题中列出的属性错误 型号: class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) pre

我想评估链接到两个不同用户的值。我创建了一个不同的表来跟踪用户以前的体验和他们感兴趣的体验,并将它们链接到用户。我有一个匹配函数,试图找到最相似的用户,但它给出了标题中列出的属性错误

型号:

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    prev = db.relationship('prevExp', backref='user', lazy='dynamic')
    interested = db.relationship('interestedExp', backref='user', 
                                 lazy='dynamic')
    matches = db.relationship('Match', backref='matchedTo', lazy='dynamic')

class prevExp(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    arts = db.Column(db.String(1))
    consulting = db.Column(db.String(1))
    dataScience = db.Column(db.String(1))
    education = db.Column(db.String(1))
    engineering = db.Column(db.String(1))
    finance = db.Column(db.String(1))
    government = db.Column(db.String(1))
    law = db.Column(db.String(1))
    management = db.Column(db.String(1))
    marketing = db.Column(db.String(1))
    medical = db.Column(db.String(1))
    technology = db.Column(db.String(1))
    expDescription = db.Column(db.String(400))
    userID = db.Column(db.Integer, db.ForeignKey('user.id'))

class interestedExp(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    arts = db.Column(db.String(1))
    consulting = db.Column(db.String(1))
    dataScience = db.Column(db.String(1))
    education = db.Column(db.String(1))
    engineering = db.Column(db.String(1))
    finance = db.Column(db.String(1))
    government = db.Column(db.String(1))
    law = db.Column(db.String(1))
    management = db.Column(db.String(1))
    marketing = db.Column(db.String(1))
    medical = db.Column(db.String(1))
    technology = db.Column(db.String(1))
    userID = db.Column(db.Integer, db.ForeignKey('user.id'))

class Match(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    person = db.Column(db.String(120))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    userID = db.Column(db.Integer, db.ForeignKey('user.id'))
路线:

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(firstName=form.firstName.data, lastName=form.lastName.data,
                    username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', form=form)

@app.route('/profile/edit/', methods=['GET', 'POST'])
@login_required
def editProfile():
    form = ProfileForm(obj=current_user)
    if form.validate_on_submit():
        previous = prevExp(user=current_user)
        previous.arts = form.prevArts.data
        previous.consulting = form.prevConsulting.data
        previous.dataScience = form.prevDataScience.data
        previous.education = form.prevEducation.data
        previous.engineering = form.prevEngineering.data
        previous.finance = form.prevFinance.data
        previous.government = form.prevGovernment.data
        previous.law = form.prevLaw.data
        previous.management = form.prevManagement.data
        previous.management = form.prevMarketing.data
        previous.medical = form.prevMedical.data
        previous.technology = form.prevTechnology.data
        previous.expDescription = form.expDescription.data
        interested = interestedExp(user=current_user)
        interested.arts = form.arts.data
        interested.consulting = form.consulting.data
        interested.dataScience = form.dataScience.data
        interested.education = form.education.data
        interested.engineering = form.engineering.data
        interested.finance = form.finance.data
        interested.government = form.government.data
        interested.law = form.law.data
        interested.management = form.management.data
        interested.marketing = form.marketing.data
        interested.medical = form.medical.data
        interested.technology = form.technology.data
        db.session.commit()
        flash('Your information has been saved!')
        return redirect(url_for('profile', username=current_user.username))
    return render_template('editProfile.html', form=form) 

@app.route('/matches')
@login_required
def matches():
    match = bestMatch()
    if match == None:
        message = "Sorry, there are no matches at this time. \
                   Please check back later!"
    else:
        message = "We've found a match for you! Check out "
    return render_template('matches.html', message=message, 
                           match=User.query.filter_by(username=match).first())
“匹配”路由中使用的最佳匹配函数:

def bestMatch():
    curr = []
    curr.append(current_user)
    users = set(User.query.all()) - set(curr)
    existingMatches = set(Match.query.filter_by(matchedTo=current_user))
    users -= existingMatches 
    matchScore = dict()
    for user in users:
        username, score = countSimilarities(user)
        matchScore[username] = score
    scores = matchScore.values()
    bestScore = max(scores, default=0) if max(scores, default=0) > 0 else -1
    return matchScore.get(bestScore, None)

def countSimilarities(user):
    score = 0
    if user.major == current_user.major:
        score += 1
    score += countCollege(user.college, current_user.college)
    score += countHobbies(user.hobbies, current_user.hobbies)
    score += countPrevToInterested(user)
    score += countExpDescription(user)
    return user.username, score

def countExpDescription(user):
    user = prevExp.query.filter_by(user=current_user).first().expDescription
    curr = prevExp.query.filter_by(user=user).first().expDescription
    user = set(user.split(' '))
    curr = set(curr.split(' '))
    return len(user.intersection(curr))
编辑:错误:

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask_login/utils.py", line 261, in decorated_view
    return func(*args, **kwargs)
  File "/Users/gracekim/Desktop/projects/coffeechat/app/routes.py", line 96, in matches
    match = bestMatch()
  File "/Users/gracekim/Desktop/projects/coffeechat/app/matching.py", line 13, in bestMatch
    username, score = countSimilarities(user)
  File "/Users/gracekim/Desktop/projects/coffeechat/app/matching.py", line 26, in countSimilarities
    score += countExpDescription(user)
  File "/Users/gracekim/Desktop/projects/coffeechat/app/matching.py", line 52, in countExpDescription
    curr = prevExp.query.filter_by(user=user).first().expDescription
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 1792, in filter_by
    for key, value in kwargs.items()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 1792, in <listcomp>
    for key, value in kwargs.items()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/sql/operators.py", line 365, in __eq__
    return self.operate(eq, other)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/attributes.py", line 211, in operate
    return op(self.comparator, *other, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/relationships.py", line 1093, in __eq__
    other, adapt_source=self.adapter
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/relationships.py", line 1466, in _optimized_compare
    state = attributes.instance_state(state)
AttributeError: 'str' object has no attribute '_sa_instance_state'

下面是一个很小的例子,它再现了错误:

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask_login/utils.py", line 261, in decorated_view
    return func(*args, **kwargs)
  File "/Users/gracekim/Desktop/projects/coffeechat/app/routes.py", line 96, in matches
    match = bestMatch()
  File "/Users/gracekim/Desktop/projects/coffeechat/app/matching.py", line 13, in bestMatch
    username, score = countSimilarities(user)
  File "/Users/gracekim/Desktop/projects/coffeechat/app/matching.py", line 26, in countSimilarities
    score += countExpDescription(user)
  File "/Users/gracekim/Desktop/projects/coffeechat/app/matching.py", line 52, in countExpDescription
    curr = prevExp.query.filter_by(user=user).first().expDescription
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 1792, in filter_by
    for key, value in kwargs.items()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 1792, in <listcomp>
    for key, value in kwargs.items()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/sql/operators.py", line 365, in __eq__
    return self.operate(eq, other)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/attributes.py", line 211, in operate
    return op(self.comparator, *other, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/relationships.py", line 1093, in __eq__
    other, adapt_source=self.adapter
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sqlalchemy/orm/relationships.py", line 1466, in _optimized_compare
    state = attributes.instance_state(state)
AttributeError: 'str' object has no attribute '_sa_instance_state'
类父(基):
id=sa.Column(sa.Integer,主键=True)
child=关系('child',backref='parent')
类子(基):
id=sa.Column(sa.Integer,主键=True)
parent_id=sa.Column(sa.Integer,sa.ForeignKey('parent.id'))
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
Base.metadata.drop_all(引擎)
Base.metadata.create_all(引擎)
父=父()
子=子(父=父)
s=会话()
s、 添加(父级)
s、 提交()
s、 query(Child).filter_by(parent='a string').first()#此行导致错误
其中提出:

Traceback (most recent call last):
  File "55876558.py", line 27, in <module>
    s.query(Child).filter_by(parent='a string').first()
  File "C:\Users\peter_000\.virtualenvs\test-_0Fb_hDQ\lib\site-packages\sqlalchemy\orm\query.py", line 1689, in filter_by
    for key, value in kwargs.items()]
  File "C:\Users\peter_000\.virtualenvs\test-_0Fb_hDQ\lib\site-packages\sqlalchemy\orm\query.py", line 1689, in <listcomp>
    for key, value in kwargs.items()]
  File "C:\Users\peter_000\.virtualenvs\test-_0Fb_hDQ\lib\site-packages\sqlalchemy\sql\operators.py", line 344, in __eq__
    return self.operate(eq, other)
  File "C:\Users\peter_000\.virtualenvs\test-_0Fb_hDQ\lib\site-packages\sqlalchemy\orm\attributes.py", line 180, in operate
    return op(self.comparator, *other, **kwargs)
  File "C:\Users\peter_000\.virtualenvs\test-_0Fb_hDQ\lib\site-packages\sqlalchemy\orm\relationships.py", line 1039, in __eq__
    other, adapt_source=self.adapter))
  File "C:\Users\peter_000\.virtualenvs\test-_0Fb_hDQ\lib\site-packages\sqlalchemy\orm\relationships.py", line 1372, in _optimized_compare
    state = attributes.instance_state(state)
AttributeError: 'str' object has no attribute '_sa_instance_state'
回溯(最近一次呼叫最后一次):
文件“55876558.py”,第27行,在
s、 查询(子项).filter_by(parent='a string').first()
文件“C:\Users\peter\u 000\.virtualenvs\test-\u 0Fb\u hDQ\lib\site packages\sqlalchemy\orm\query.py”,第1689行,按筛选
对于键,以kwargs.items()为单位的值
文件“C:\Users\peter\u 000\.virtualenvs\test-\u 0Fb\u hDQ\lib\site packages\sqlalchemy\orm\query.py”,第1689行,在
对于键,以kwargs.items()为单位的值
文件“C:\Users\peter\u 000\.virtualenvs\test-\u 0Fb\u hDQ\lib\site packages\sqlalchemy\sql\operators.py”,第344行,在uu eq中__
返回自操作(eq,其他)
文件“C:\Users\peter\u 000\.virtualenvs\test-\u 0Fb\u hDQ\lib\site packages\sqlalchemy\orm\attributes.py”,第180行,在operate中
返回op(自比较器,*其他,**kwargs)
文件“C:\Users\peter\u 000\.virtualenvs\test-\u 0Fb\u hDQ\lib\site packages\sqlalchemy\orm\relationships.py”,第1039行,在uu eq中__
其他,adapt_source=self.adapter)
文件“C:\Users\peter\u 000\.virtualenvs\test-\u 0Fb\u hDQ\lib\site packages\sqlalchemy\orm\relationships.py”,第1372行,在\u optimized\u compare中
状态=属性。实例\状态(状态)
AttributeError:“str”对象没有属性“\u sa\u instance\u state”
Child.parent
是一个关系属性,在官方文档中是一个很好的资源,可以帮助您了解它们是如何工作的。关键在于它们处理其他ORM对象。因此,在查询关系时,需要提供ORM对象。在上面的示例中,如果将此行替换为:
s.query(Child).filter_by(parent='a string').first()
,则错误会消失,因为
parent
是ORM对象

在您的特定情况下,错误来自以下行:
curr=prevExp.query.filter\u by(user=user.first().expDescription
,其中您将变量
user
传递给
filter\u by()
方法<代码>用户是在上面的一行定义的,
user=prevExp.query.filter\u by(user=current\u user).first().expDescription
查询一个
prevExp
对象,一旦使用
first()
检索它,就可以访问它的
expDescription
属性。
expDescription
的列定义是
expDescription=db.column(db.String(400))
:一个字符串。因此,您要传递一个
str
来查询relationship属性,并创建上面简化示例所演示的确切情况


出现错误消息的原因是:每个ORM对象都有一个
\u sa\u instance\u state
属性。由于关系属性纯粹用于表示其他ORM对象,sqlalchemy假定您传入的字符串是ORM对象,而不必首先检查(为什么会这样?!)。字符串没有
\u sa\u instance\u state
属性,因此也没有
AttributeError

不用担心,我在这里的第一个问题是我不确定什么太多或太少,很容易出错。好的,您在您的flask应用程序中声明和启动
app
?这就是
\uuuu call\uuuu
的来源。通常它是由
app启动的。运行
也非常有帮助,因为您可以拥有一个python环境,而不需要更改随附的python3环境mac@C.Nivs我刚刚编辑了这篇文章,将我的init.py包含在声明
应用程序的地方,但老实说,我不太确定从哪里开始。我只是在命令行中运行命令
flask run
。好的,谢谢,请注意,文件应该(可能)是
\uuuu init\uuuuuu.py
在这种情况下,请注意双下划线