forked from sagaragarwal94/python_rest_flask
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
66 lines (54 loc) · 2.48 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/python3
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
db_connect = create_engine('sqlite:///chinook.db')
app = Flask(__name__)
api = Api(app)
class Employees(Resource):
def get(self):
conn = db_connect.connect() # connect to database
query = conn.execute("select * from employees") # This line performs query and returns json result
return {'employees': [i[0] for i in query.cursor.fetchall()]} # Fetches first column that is Employee ID
def post(self):
conn = db_connect.connect()
print(request.json)
LastName = request.json['LastName']
FirstName = request.json['FirstName']
Title = request.json['Title']
ReportsTo = request.json['ReportsTo']
BirthDate = request.json['BirthDate']
HireDate = request.json['HireDate']
Address = request.json['Address']
City = request.json['City']
State = request.json['State']
Country = request.json['Country']
PostalCode = request.json['PostalCode']
Phone = request.json['Phone']
Fax = request.json['Fax']
Email = request.json['Email']
query = conn.execute("insert into employees values(null,'{0}','{1}','{2}','{3}', \
'{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}', \
'{13}')".format(LastName,FirstName,Title,
ReportsTo, BirthDate, HireDate, Address,
City, State, Country, PostalCode, Phone, Fax,
Email))
return {'status':'success'}
class Tracks(Resource):
def get(self):
conn = db_connect.connect()
query = conn.execute("select trackid, name, composer, unitprice from tracks;")
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
return jsonify(result)
class Employees_Name(Resource):
def get(self, employee_id):
conn = db_connect.connect()
query = conn.execute("select * from employees where EmployeeId =%d " %int(employee_id))
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
return jsonify(result)
api.add_resource(Employees, '/employees') # Route_1
api.add_resource(Tracks, '/tracks') # Route_2
api.add_resource(Employees_Name, '/employees/<employee_id>') # Route_3
if __name__ == '__main__':
app.run()