2015-12-03 13 views
13

Avendo un problema che sembra essere comune, ho svolto la mia ricerca e non vedo che sia stato ricreato esattamente da qualche parte. Quando stampo json.loads(rety.text), vedo l'output di cui ho bisogno. Eppure quando chiamo return, mi mostra questo errore. Qualche idea? L'aiuto è molto apprezzato e grazie. Sto usando il pallone MethodHandler.Python Flask, TypeError: l'oggetto 'dict' non è richiamabile

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',]) 

Ecco il Traceback (Tenete a mente sono risultati stampa sopra):

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) 

risposta

28

Flask only expects views to return a response-like object. questo significa un Response, una stringa o una tupla che descrive il corpo, codice e le intestazioni. Stai restituendo un ditt, che non è una di quelle cose. Poiché stai restituendo JSON, restituisci una risposta con la stringa JSON nel corpo e un tipo di contenuto di application/json.

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

Nel tuo esempio, hai già una stringa JSON, il contenuto restituito dalla richiesta che hai fatto. Tuttavia, se si desidera convertire una struttura Python ad una risposta JSON, utilizzare jsonify:

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

Dietro le quinte, Flask è un'applicazione WSGI, che prevede di passare oggetti intorno richiamabili, motivo per cui si ottieni quell'errore specifico: un dict non è richiamabile e Flask non sa come trasformarlo in qualcosa che è.

+0

Grazie a David, questo sembra attenuare l'errore. Tuttavia, ora sto ottenendo un nuovo errore che, a mio avviso, potrebbe non essere correlato alla domanda originale. Qualche idea qui? {u'code ': 400, u'error': u'Input JSON non valido alla riga 1, colonna 2 '} 127.0.0.1 - - [02/Dic/2015 23:39:34] "POST/results2 HTTP/1.1 "200 - – puhtiprince

+0

@puhtiprince che è il json della richiesta che hai fatto, sta dicendo che non hai fatto bene. Devi passare 'json =' per postare, piuttosto che 'data ='. – davidism

5

Utilizzare la funzione Flask.jsonify per restituire i dati.

Esempio - return jsonify (dati)

Problemi correlati