【问题标题】:Load Json Script with Flask Request, convert to pandas Dataframe and back to Json as Flask Response使用 Flask 请求加载 Json 脚本,转换为 pandas Dataframe 并返回 Json 作为 Flask 响应
【发布时间】:2016-04-04 09:44:23
【问题描述】:

我正在使用 Python/pickle 作为我的评分模型。要评分的数据将来自作为 Json 脚本的 Flask 请求。需要从 Flask Request 中读取数据,将数据转换为 pandas 数据帧,通过 pandasql 转换数据,调用评分模型并将评分结果数据帧输出为 Json 中的 Flask Response。

  1. 当传入的数据是我硬盘上的 Json 文件时(使用 json.load()),我可以让上述所有内容正常工作。
  2. 为了调试,我可以使用 Flask 请求来加载 Json 脚本并将其转换为数据帧并将数据帧作为 Json 中的 Flask 响应返回。
  3. 但是, 在通过 Flask 请求加载 Json 脚本后,我尝试使用 pandasql 转换数据,但得到错误找不到数据框“异常:未找到 df” .
    • 我该如何解决这个问题?提前致谢(代码和 Json 脚本如下)

根据上面的 #2:此代码有效。

app = Flask(__name__)

@app.route('/results', methods=['POST'])
def load():
    data = request.get_json(force=True)
    df = pd.io.json.json_normalize(data)
    df.columns = df.columns.map(lambda x: x.split(".")[-1])

    resp = make_response(df.to_json())
    return resp

if __name__ == '__main__':
    app.run(debug=True)

每个问题 #3:此代码不起作用!使用 pandasql 转换数据框得到错误:'df is not found' (full tr​​aceback at bottom)

app = Flask(__name__)

@app.route('/results', methods=['POST'])
def load():
    data = request.get_json(force=True)
    df = pd.io.json.json_normalize(data)
    df.columns = df.columns.map(lambda x: x.split(".")[-1])

# set up query to transform data (simple example)
    q = """ 
        Select *
        from df 
        """
    query = pandasql.sqldf(q, globals())

    resp = make_response(query.to_json())
    resp.mimetype = 'application/json'
    return resp

if __name__ == '__main__':
    app.run(debug=True)

完整的错误回溯:

File "C:\ app.py", line 1836, in __call__
  return self.wsgi_app(environ, start_response)
line 1820, in wsgi_app
  response = self.make_response(self.handle_exception(e))
line 1403, in handle_exception
  reraise(exc_type, exc_value, tb)
line 1817, in wsgi_app
  response = self.full_dispatch_request()
line 1477, in full_dispatch_request
  rv = self.handle_user_exception(e)
line 1381, in handle_user_exception
  reraise(exc_type, exc_value, tb)
line 1475, in full_dispatch_request
  rv = self.dispatch_request()
line 1461, in dispatch_request
  return self.view_functions[rule.endpoint](**req.view_args)
line 52, in load
  query = pandasql.sqldf(q, globals())
line 108, in sqldf
  raise Exception("%s not found" % table)
Exception: df not found

Json 脚本:

{
    "response":{
      "version":"1.1",
      "token":"dsfgf",
       "body":{
         "customer":{
             "customer_id":"1234567",
             "verified":"true"
        },
         "contact":{
             "email":"mr@abc.com",
             "mobile_number":"0123456789"
        },
         "personal":{
             "gender": "m",
             "title":"Dr.",
             "last_name":"Muster",
             "first_name":"Max",
             "family_status":"single",
             "dob":"1985-12-23"
            }
        }
    }
}

【问题讨论】:

    标签: python json flask request pandasql


    【解决方案1】:

    简单的解决方案:

    • 将 globals() 替换为 [ query = pandasql.sqldf(q, globals()) ] 中的 locals()

    对于需要加入多个数据框的更复杂的需求,请参阅https://github.com/yhat/pandasql/issues/42 的 cmets

    【讨论】:

      猜你喜欢
      • 2018-08-10
      • 2017-12-01
      • 1970-01-01
      • 2021-12-26
      相关资源
      最近更新 更多