-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
74 lines (55 loc) · 1.5 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
67
68
69
70
import time
from datetime import datetime
from flask import Flask, request, abort
app = Flask(__name__)
db = []
# messenger starting page with link to status page
@app.route('/')
def start_page():
return 'Welcome, see <a href="/status">status</a> for information'
# messenger status page
@app.route('/status')
def status():
date_now = datetime.now()
date_data = {
'status': True,
'name': 'Messenger',
'time': date_now.strftime('%d.%m.%Y %H:%M:%S'),
'users': len(set(message['name'] for message in db))
}
return date_data
# send message function
@app.route('/send', methods=['POST'])
def send():
data = request.json
db.append({
'id': len(db),
'name': data['name'],
'text': data['text'],
'timestamp': time.time()
})
return {'ok': True}
# list of messages
@app.route('/messages')
def messages():
if 'after_timestamp' in request.args:
after_timestamp = float(request.args['after_timestamp'])
else:
after_timestamp = 0
# pagination
max_limit = 100
if 'limit' in request.args:
limit = int(request.args['limit'])
if limit > max_limit:
abort(400, 'too big limit')
else:
limit = max_limit
# count messages that should be returned
after_id = 0
for message in db:
if message['timestamp'] > after_timestamp:
break
after_id += 1
return {'messages': db[after_id:after_id+limit]}
# server entrypoint
app.run()