如何防止对象的类更改

时间:2017-05-18 21:00:53

标签: python flask boto amazon-mws

我在带有物体的烧瓶应用程序中遇到了麻烦。第一次运行该函数时,它运行得非常好。然而,第二次运行时,我得到一个'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,然而它仍然会出现同样的错误。有没有办法可以在运行一次后从内存中清除此功能?我需要这个函数来正确地提供响应,但也许还有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我能够解决这个问题。如问题中所述,问题源于<?xml version="1.0" encoding="utf-8"?> <packages> <package id="CarouselView.FormsPlugin" version="4.4.2" targetFramework="monoandroid71" /> <package id="Plugin.CurrentActivity" version="1.0.1" targetFramework="monoandroid71" /> <package id="Plugin.Permissions" version="2.0.1" targetFramework="monoandroid71" /> <package id="Xam.Plugin.Media" version="3.0.1" targetFramework="monoandroid71" /> <package id="Xam.Plugins.Forms.ImageCircle" version="1.8.1" targetFramework="monoandroid71" /> <package id="Xam.Plugins.Forms.RoundedBoxView" version="1.0.0.7" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Animated.Vector.Drawable" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Annotations" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Compat" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Core.UI" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Core.Utils" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Design" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Fragment" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Media.Compat" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Transition" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v4" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.AppCompat" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.CardView" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.MediaRouter" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.Palette" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.RecyclerView" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Vector.Drawable" version="25.3.1" targetFramework="monoandroid71" /> <package id="Xamarin.Build.Download" version="0.4.5" targetFramework="monoandroid71" /> <package id="Xamarin.Forms" version="2.3.4.247" targetFramework="monoandroid71" /> <package id="XFControls" version="1.0.0.6" targetFramework="monoandroid71" developmentDependency="true" /> </packages> 中的response = MWSConnection._parse_response = lambda s,x,y,z: z行。此行是将响应解析为XML并为其提供服务所必需的,这会导致在调用此函数后将提交的响应解析为XML字符串。为了解决这个问题,我检查了feed_result是不是字符串,并检索了我最初的ID:

feed

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

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

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