如何使用restful使用flask从CSV获取JSON文件

时间:2016-12-20 19:30:06

标签: python json rest flask

我想使用restful with flask framework将我的CSV文件转换为JSON文件,这样我就可以在我的Xcode项目中获取它。我已经设法导入CSV并将其作为JSON数据获取,但我无法获取JSON文件,并且我的数据并不像我预期的那样呈现(所有内容都在行中打印而不是在JSON结构中打印)。 我需要组织数据和JSON文件。

我的代码:

from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps

e = create_engine('sqlite:///salaries.db')

app = Flask(__name__)
api = Api(app)

class Departments_Meta(Resource):
    def get(self):
    #Connect to databse
    conn = e.connect()
    #Perform query and return JSON data
    query = conn.execute("select distinct DEPARTMENT from salaries")
    return {'departments': [i[0] for i in query.cursor.fetchall()]}

class Departmental_Salary(Resource):
    def get(self, department_name):
        conn = e.connect()
        query = conn.execute("select * from salaries where Department='%s'"%department_name.upper())

        result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
        return result

api.add_resource(Departmental_Salary, '/dept/<string:department_name>')
api.add_resource(Departments_Meta, '/departments')

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

0 个答案:

没有答案