【问题标题】:How to prevent an object's class from changing如何防止对象的类发生变化
【发布时间】:2026-01-06 22:00:02
【问题描述】:

我在带有对象的烧瓶应用程序中遇到问题。第一次运行该函数时,它运行得非常好。但是,第二次运行时,我收到一个错误,即“str”对象没有属性 SubmitFeedResult。我可以通过重新启动应用程序并再次运行该功能来解决这个问题(然后运行良好)。函数运行后,对象被更改为字符串,我想知道是否有办法防止对象的类更改为字符串(我倾向于否,因为由于库中的源代码,它会这样做我正在使用),或者解决这个问题的好方法是什么。为了让应用程序为其他用户成功运行,我不能拥有类 str 的对象

几个月前我问过这个问题,简单地解决了它,但现在问题又回来了。这是某些上下文的原始帖子的链接:'str' Object has no attribute 'SubmitFeedResult'

这里是主要功能:

@app.route('/submission/', methods=['GET','POST'])
def feed_submission():
    if request.method == 'POST':
            file = request.files['file']
            # Only XML files allowed
            if not allowed_filetype(file.filename):
                output = '<h2 style="color:red">Filetype must be XML! Please upload an XML file.</h2>'
                return output
                raise ValueError('Filetype Must Be XML.')
            # Read file and encode it for transfer to Amazon
            file_name = request.form['file_name']
            f = file.read()
            u = f.decode("utf-8-sig")
            c = u.encode("utf-8")
            feed_content = c
            submit_feed_response = conn.submit_feed(
                FeedType=feed_operation(file_name),
                PurgeAndReplace=False,
                MarketplaceIdList=[MARKETPLACE_ID],
                content_type='text/xml',
                FeedContent=feed_content)
            feed_info = submit_feed_response.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId
            return redirect(url_for('feed_result', feed_id=feed_info))
    else:
        return render_template('submit_feed.html',access_key=MWS_ACCESS_KEY,secret_key=MWS_SECRET_KEY,
        merchant_id=MERCHANT_ID,marketplace_id=MARKETPLACE_ID)

这个函数运行后,重定向到这个函数,返回请求的响应:

@app.route('/feed-result/<int:feed_id>')
def feed_result(feed_id):
    response = MWSConnection._parse_response = lambda s,x,y,z: z
    submitted_feed = conn.get_feed_submission_result(FeedSubmissionId=feed_id)
    result = Response(submitted_feed, mimetype='text/xml')
    return(result)

我在问题发生之前和之后记录了submit_feed_response的类型和值的信息,以查看导致错误的原因:

typeof1 = type(submit_feed_response)
val1 = submit_feed_response
typeof_conn1 = type(conn)
app.logger.warning("Type of submit_feed_response (original): " + str(typeof1))
app.logger.warning("Value of submit_feed_response: " + str(val1))

在日志中,当应用程序正常运行时,我看到:

Type of submit_feed_response (original): <class 'boto.mws.response.SubmitFeedResponse'>
Value of submit_feed_response: SubmitFeedResponse{u'xmlns': u'http://mws.amazonaws.com/doc/2009-01-01/'}(SubmitFeedResult: SubmitFeedResult{}(FeedSubmissionInfo: FeedSubmissionInfo{}...

失败后,我看到(如预期的那样)类型是字符串:

Type of submit_feed_response: <type 'str'>
Value of submit_feed_response: <?xml version="1.0"?>

......

这是回溯:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\CTS 41\Documents\Amazon-app\application.py", line 98, in feed_submission
feed_info = submit_feed_response.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId
AttributeError: 'str' object has no attribute 'SubmitFeedResult'

似乎库导致对象在运行后返回一个字符串。有没有一种很好的pythonic方式来解决这个问题?即我是否能够以某种方式更改对象的类以确保它保持不变,或者完全从内存中删除它?我尝试了除块之外的尝试,但返回相同的错误。

编辑

我已将问题缩小到:

response = MWSConnection._parse_response = lambda s,x,y,z: z 在函数feed_result 中。它可以从 boto 返回 XML 响应(调用自然不会以 XML 格式返回,我不确定以 XML 格式返回它的另一种方式,请参阅How can I return XML from boto calls?)。

我决定插入

MWSConnection._parse_response = None 行上方

feed_info = feed.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId,但是它仍然返回相同的错误。有没有办法可以在运行一次后从内存中清除此功能?我需要这个函数来正确响应响应,但也许有更好的方法?

【问题讨论】:

  • 你不是在 6 个月前 ask the same thing 吗?
  • @Wondercricket 我做到了,我以为我已经解决了,但我没有。我应该改为编辑该帖子吗?如果是这样,我会关闭这个
  • @Wondercricket 让我知道这是否是在 * 上重新打开问题的正确方法
  • 我不能 100% 确定在这种情况下是否会得到适当的收益,但是找到那个元帖子做得很好。
  • 为什么不把类型检查放在那里然后记录调试信息呢?比如,那个字符串里有什么?什么输入导致它被返回?等等。此外,您是否查看过该方法的来源?什么情况下会返回字符串?

标签: python flask boto amazon-mws


【解决方案1】:

我能够解决这个问题。如问题中所述,该问题源于feed_result 中的response = MWSConnection._parse_response = lambda s,x,y,z: z 行。此行对于将响应解析为 XML 并提供服务是必需的,这导致在调用此函数后,提交提要的响应被解析为 XML 字符串。为了解决这个问题,我检查了feed 是否不是字符串,并按照我最初的方式检索了 ID:

if type(feed) is not str:
            feed_info = feed.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId

如果是字符串,则解析为XML字符串,使用ElementTree检索ID:

else:
            tree = et.fromstring(feed)
            xmlns = {'response': '{http://mws.amazonaws.com/doc/2009-01-01/}'}
            info = tree.find('.//{response}FeedSubmissionId'.format(**xmlns))
            feed_info = info.text

现在无需重新启动应用程序即可正常工作。

【讨论】:

    最近更新 更多