簡體   English   中英

Python Flask,TypeError:“dict”對象不可調用

[英]Python Flask, TypeError: 'dict' object is not callable

有一個似乎很常見的問題,但我已經完成了我的研究,並沒有看到它在任何地方完全重現。 當我打印json.loads(rety.text) ,我看到了我需要的輸出。 然而,當我調用返回時,它向我顯示了這個錯誤。 有任何想法嗎? 非常感謝並感謝您的幫助。 我正在使用 Flask MethodHandler

class MHandler(MethodView):
    def get(self):
        handle = ''
        tweetnum = 100

        consumer_token = '' 
        consumer_secret = ''
        access_token = '-'
        access_secret = ''

        auth = tweepy.OAuthHandler(consumer_token,consumer_secret)
        auth.set_access_token(access_token,access_secret)

        api  = tweepy.API(auth)

        statuses = api.user_timeline(screen_name=handle,
                          count= tweetnum,
                          include_rts=False)

        pi_content_items_array = map(convert_status_to_pi_content_item, statuses)
        pi_content_items = { 'contentItems' : pi_content_items_array }

        saveFile = open("static/public/text/en.txt",'a') 
        for s in pi_content_items_array: 
            stat = s['content'].encode('utf-8')
            print stat

            trat = ''.join(i for i in stat if ord(i)<128)
            print trat
            saveFile.write(trat.encode('utf-8')+'\n'+'\n')

        try:
            contentFile = open("static/public/text/en.txt", "r")
            fr = contentFile.read()
        except Exception as e:
            print "ERROR: couldn't read text file: %s" % e
        finally:
            contentFile.close()
        return lookup.get_template("newin.html").render(content=fr) 

    def post(self):
        try:
            contentFile = open("static/public/text/en.txt", "r")
            fd = contentFile.read()
        except Exception as e:
            print "ERROR: couldn't read text file: %s" % e
        finally:
                contentFile.close()
        rety = requests.post('https://gateway.watsonplatform.net/personality-insights/api/v2/profile', 
                auth=('---', ''),
                headers = {"content-type": "text/plain"},
                data=fd
            )

        print json.loads(rety.text)
        return json.loads(rety.text)


    user_view = MHandler.as_view('user_api')
    app.add_url_rule('/results2', view_func=user_view, methods=['GET',])
    app.add_url_rule('/results2', view_func=user_view, methods=['POST',])

這是回溯(請記住上面打印的結果):

Traceback (most recent call last):
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request
    response = self.make_response(rv)
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py", line 1577, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/werkzeug/wrappers.py", line 841, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/werkzeug/test.py", line 867, in run_wsgi_app
    app_rv = app(environ, start_response)

Flask 只期望視圖返回一個類似響應的對象。 這意味着一個Response 、一個字符串或一個描述主體、代碼和標題的元組。 您正在返回一個 dict,這不是其中之一。 由於您要返回 JSON,因此請返回正文中包含 JSON 字符串且內容類型為application/json的響應。

return app.response_class(rety.content, content_type='application/json')

在您的示例中,您已經有一個 JSON 字符串,即您發出的請求返回的內容。 但是,如果要將 Python 結構轉換為 JSON 響應,請使用jsonify

data = {'name': 'davidism'}
return jsonify(data)

在幕后,Flask 是一個 WSGI 應用程序,它期望傳遞可調用對象,這就是為什么您會收到特定錯誤:dict 不可調用且 Flask 不知道如何將其轉換為可調用對象。

使用 Flask.jsonify 函數返回數據。

from flask import jsonify 
# ...
return jsonify(data)

如果從 Flask 視圖返回data, status, headers元組,當數據已經是響應對象(例如jsonify返回的內容)時,Flask 當前會忽略狀態代碼和content_type標題。

這不會設置內容類型標頭:

headers = {
    "Content-Type": "application/octet-stream",
    "Content-Disposition": "attachment; filename=foobar.json"
}
return jsonify({"foo": "bar"}), 200, headers

相反,使用flask.json.dumps生成數據(這是jsonfiy內部使用的)。

from flask import json

headers = {
    "Content-Type": "application/octet-stream",
    "Content-Disposition": "attachment; filename=foobar.json"
}
return json.dumps({"foo": "bar"}), 200, headers

或者使用響應對象:

response = jsonify({"foo": "bar"})
response.headers.set("Content-Type", "application/octet-stream")
return response

但是,如果您真的想按照這些示例顯示的內容進行操作並將 JSON 數據作為下載提供,請改用send_file

from io import BytesIO
from flask import json
data = BytesIO(json.dumps(data))
return send_file(data, mimetype="application/json", as_attachment=True, attachment_filename="data.json")

至於燒瓶版本 1.1.0 現在你可以返回 dict

flask 會自動將其轉換為 json 響應。

https://flask.palletsprojects.com/en/1.1.x/quickstart/#apis-with-json https://flask.palletsprojects.com/en/1.1.x/changelog/#version-1-1-0

這沒有嘗試對響應進行 jsonify,而是有效。

return response.content

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM