Skip to content
This repository has been archived by the owner on Apr 15, 2020. It is now read-only.

Commit

Permalink
using postgresql as persistence plan to store visitor count
Browse files Browse the repository at this point in the history
  • Loading branch information
jwenjian committed Jul 6, 2019
1 parent 586504c commit 57fa384
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 20 deletions.
1 change: 0 additions & 1 deletion db.json

This file was deleted.

36 changes: 18 additions & 18 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import datetime

import psycopg2
from flask import Flask, Response, request
from pybadges import badge
from tinydb import TinyDB, Query
from os import environ

app = Flask(__name__)

Expand All @@ -28,33 +29,32 @@ def total_count_svg() -> Response:
:return: A svg badge with latest visitor count
"""
global total_count_hub
db = TinyDB('db.json')
total_count_table = db.table('total_count')
record = Query()

conn = psycopg2.connect(environ['DATABASE_URL'])
cursor = conn.cursor()

repo_id = request.args.get('repo_id')
if repo_id is None or repo_id == '':
return invalid_count_resp()

print("repo_id = ", repo_id)

original_count = 0
doc = None
docs = total_count_table.search(record.repo_id == repo_id)
if docs is not None and len(docs) > 0:
doc = docs[0]
original_count = doc['count'] if doc['count'] is not None else 0
else:
doc = {'repo_id': repo_id, 'count': 0}

original_count += 1
new_count = 1

doc['count'] = original_count
cursor.execute('SELECT * FROM TOTAL_COUNT_RECORD WHERE repo_id = %s', (repo_id, ))
doc = cursor.fetchone()

total_count_table.upsert(doc, record.repo_id == repo_id)
if doc is not None:
# 0: id, 1: repo_id, 2: count
original_count = doc[2]
new_count = original_count + 1
cursor.execute('UPDATE TOTAL_COUNT_RECORD SET count = %s WHERE repo_id = %s', (new_count, repo_id))
conn.commit()
else:
cursor.execute('INSERT INTO TOTAL_COUNT_RECORD(repo_id, count) VALUES(%s, %s)', (repo_id, new_count))
conn.commit()

svg = badge(left_text="Total Visitor", right_text=str(original_count))
svg = badge(left_text="Total Visitor", right_text=str(new_count))

expiry_time = datetime.datetime.utcnow() - datetime.timedelta(minutes=10)

Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Flask
pybadges
gunicorn
tinydb
psycopg2-binary

0 comments on commit 57fa384

Please sign in to comment.