-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserMicroservice.py
178 lines (158 loc) · 6.54 KB
/
UserMicroservice.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
from flask import Flask, request, jsonify
import sqlite3
from flask import g
import hashlib
import datetime
import click
from flask.cli import with_appcontext
######################
# API USAGE
# Web server route for this API: localhost:5000
# --------------------
# Create a new user: Send a POST request to route of createUser() fn
# Example request:
# curl -i -X POST -H 'Content-Type:application/json' -d '{"usernameAPI":"newuser", "emailAPI":"newuser@gmail.com", "passwordAPI":"newuser@123"}' http://localhost:5000/createUser;
# --------------------
# Authenticate an existing post: Send a GET request to route of authenticateUser() fn
# Example request:
# curl -i -X GET -H 'Content-Type:application/json' -d '{"usernameAPI":"ankita", "passwordAPI":"ankita@123"}' http://localhost:5000/authenticateUser;
# --------------------
# Follow an existing user: Send a POST request to route of addFollower() fn
# Example request:
# curl -i -X POST -H 'Content-Type:application/json' -d '{"usernameAPI":"om", "usernameFollowingAPI":"ankita"}' http://localhost:5000/addFollower;
# --------------------
# Remove an existing follower: Send a DELETE request to route of removeFollower() fn
# Example request:
# curl -i -X DELETE -H 'Content-Type:application/json' -d '{"usernameAPI":"om", "usernameFollowingAPI":"ankita"}' http://localhost:5000/removeFollower;
# --------------------
######################
# Database
# db_name: UsersMicroservice.db
# table1: Users
# username
# email
# pass
# table2: Followers
# username
# usernamefollowing
# table3: Tweets
# username
# tweet
# time_stamp
# config variables
app = Flask(__name__)
DATABASE = 'UsersMicroservice.db'
# helper function to get hash of the password during user authentication
def hsh(txt):
a = hashlib.md5()
a.update(txt.encode('utf-8'))
return a.hexdigest()
# helper function to generate a response with status code and message
def get_response(status_code, message):
return {"status_code": str(status_code), "message": str(message)}
# get db from flask g namespace
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
# function to execute a single query at once
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
# initiate db with
# $FLASK_APP=post_api.py
# $flask init
@app.cli.command('init')
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
# home page
@app.route('/', methods=['GET'])
def home():
return jsonify(get_response(status_code=200, message="Database Initialized and Populated!"))
# function to create a new user
@app.route("/createUser", methods=['POST'])
def createUser():
params = request.get_json()
username_ = params.get('usernameAPI')
email_ = params.get('emailAPI')
password_ = params.get('passwordAPI')
if not username_ or not email_ or not password_:
return jsonify(get_response(status_code=409, message="username / emails / password is not in request")), 409
else:
with sqlite3.connect("UsersMicroservice.db") as con:
cur = con.cursor()
cur.execute("INSERT OR IGNORE INTO Users (username, email, pass) VALUES (?,?,?)", (username_, email_, hsh(password_)))
con.commit()
for user in query_db('select * from Users'):
print(user)
response = jsonify(get_response(status_code=201, message="User created"))
response.status_code = 201
response.autocorrect_location_header = False
return response
# function to authenticate an existing user
@app.route("/authenticateUser", methods=['GET'])
def authenticateUser():
params = request.get_json()
username = params.get('usernameAPI')
password = params.get('passwordAPI')
if not username or not password:
return jsonify(get_response(status_code=409, message="username / password is not in request")), 409
else:
user = query_db('select * from users where username = ?', [username], one=True)
userEnteredPasswordHash = hsh(password)
dbPassword = user[2]
if userEnteredPasswordHash == dbPassword:
print("User Authentication Successful")
response = jsonify(get_response(status_code=200, message="True"))
response.status_code = 200
return response
else:
print("User Authentication Error")
response = jsonify(get_response(status_code=400, message="False"))
response.status_code = 400
return response
# function to add a follower to the following list
@app.route("/addFollower", methods=['POST'])
def addFollower():
params = request.get_json()
username = params.get('usernameAPI')
username_following = params.get('usernameFollowingAPI')
if not username or not username_following:
return jsonify(get_response(status_code=409, message="username / username to following is not in request")), 409
else:
with sqlite3.connect("UsersMicroservice.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO Followers (username, usernamefollowing) VALUES (?,?)", (username, username_following))
con.commit()
msg = username+" started following "+username_following
response = jsonify(get_response(status_code=201, message=msg))
response.status_code = 201
response.autocorrect_location_header = False
return response
# function to remove a follower from folllowing list
@app.route("/removeFollower", methods=['DELETE'])
def removeFollower():
params = request.get_json()
username = params.get('usernameAPI')
username_following = params.get('usernameFollowingAPI')
if not username or not username_following:
return jsonify(get_response(status_code=409, message="username / username to following is not in request")), 409
else:
with sqlite3.connect("UsersMicroservice.db") as con:
cur = con.cursor()
cur.execute("DELETE FROM Followers WHERE username=? AND usernamefollowing=?", (username, username_following))
con.commit()
msg = username+" started unfollowing "+username_following
response = jsonify(get_response(status_code=200, message=msg))
response.status_code = 200
response.autocorrect_location_header = False
return response
if __name__ == "__main__":
app.run(debug = True)