-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
67 lines (58 loc) · 2.24 KB
/
app.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
from flask import Flask, request, jsonify
from pymongo import MongoClient
from datetime import datetime
app = Flask(__name__)
# MongoDB connection
client = MongoClient("mongodb://localhost:27017/myDatabase")
db = client['github_webhooks']
collection = db['events']
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.json
event_type = request.headers.get('X-GitHub-Event')
if event_type == 'push':
author = data['pusher']['name']
to_branch = data['ref'].split('/')[-1]
timestamp = datetime.strptime(data['head_commit']['timestamp'], "%Y-%m-%dT%H:%M:%SZ")
event_data = {
"type": "push",
"author": author,
"to_branch": to_branch,
"timestamp": timestamp
}
elif event_type == 'pull_request':
author = data['pull_request']['user']['login']
from_branch = data['pull_request']['head']['ref']
to_branch = data['pull_request']['base']['ref']
timestamp = datetime.strptime(data['pull_request']['created_at'], "%Y-%m-%dT%H:%M:%SZ")
event_data = {
"type": "pull_request",
"author": author,
"from_branch": from_branch,
"to_branch": to_branch,
"timestamp": timestamp
}
elif event_type == 'pull_request' and data['pull_request']['merged']:
author = data['pull_request']['user']['login']
from_branch = data['pull_request']['head']['ref']
to_branch = data['pull_request']['base']['ref']
timestamp = datetime.strptime(data['pull_request']['merged_at'], "%Y-%m-%dT%H:%M:%SZ")
event_data = {
"type": "merge",
"author": author,
"from_branch": from_branch,
"to_branch": to_branch,
"timestamp": timestamp
}
else:
return jsonify({'message': 'Event not supported'}), 400
collection.insert_one(event_data)
return jsonify({'message': 'Event received'}), 200
@app.route('/events', methods=['GET'])
def get_events():
events = list(collection.find().sort("timestamp", -1).limit(10))
for event in events:
event['_id'] = str(event['_id'])
return jsonify(events), 200
if __name__ == '__main__':
app.run(port=5000, debug=True)