Skip to content

Instantly share code, notes, and snippets.

@fazt
Created July 18, 2019 01:24
Show Gist options
  • Save fazt/8da641f7a81c3af15cea0554d2bebcd3 to your computer and use it in GitHub Desktop.
Save fazt/8da641f7a81c3af15cea0554d2bebcd3 to your computer and use it in GitHub Desktop.
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask_jsonpify import jsonify
db_connect = create_engine('sqlite:///database.db')
app = Flask(__name__)
api = Api(app)
class Sellers(Resource):
def get(self):
conn = db_connect.connect()
query = conn.execute("select * from sellers")
# fetch first column (product IDs)
return {'products': [i[0] for i in query.cursor.fetchall()]}
class Products(Resource):
def get(self):
conn = db_connect.connect()
query = conn.execute("select * from products")
result = {'products': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]}
return jsonify(result)
class OneSeller(Resource):
def get(self, seller_id):
conn = db_connect.connect()
query = conn.execute("select * from sellers where id=%d" %int(seller_id))
result = {'product': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]}
return jsonify(result)
api.add_resource(Sellers, '/api/sellers')
api.add_resource(Products, '/api/products')
api.add_resource(OneSeller, '/api/sellers/<seller_id>')
if __name__ == '__main__':
app.run(port=4000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment