|
2 | 2 | import redis |
3 | 3 | import mysql.connector |
4 | 4 | import logging |
| 5 | +from fastapi import FastAPI |
| 6 | +from pydantic import BaseModel |
| 7 | +import requests |
| 8 | + |
| 9 | + |
| 10 | +class Username(BaseModel): |
| 11 | + username: str |
5 | 12 |
|
6 | 13 |
|
7 | 14 | logger = logging.getLogger(__name__) |
|
15 | 22 | database = 'DB' |
16 | 23 | ) |
17 | 24 |
|
| 25 | +app = FastAPI() |
| 26 | + |
18 | 27 | r = redis.StrictRedis(host='redis', port=6379, decode_responses=True, password="") |
19 | 28 | ALLOWED_PREFIX = 'allowed' # max number of requests allowed per WINDOW_LENGTH |
20 | 29 |
|
21 | 30 | # preparing a cursor object |
22 | 31 | cursor_object = database.cursor() |
23 | | -user_record = """SELECT * FROM subscription_details """ |
24 | | -records = cursor_object.execute(user_record) |
25 | | -result = cursor_object.fetchall() |
26 | 32 |
|
27 | | -# >>> print(result) |
28 | | -# [('free_user', 'Free', 10, 1), ('basic_user', 'Basic', 100, 15), ('advanced_user', 'Advanced', 1000, 60), ('test', 'Advanced', 1000, 60)] |
| 33 | +@app.post('/sync', status_code=200) |
| 34 | +def sync(username: Username): |
| 35 | + print(f'Syncing {username} to redis') |
| 36 | + user_record = f"""SELECT * FROM subscription_details where username = '{username.username}'""" |
| 37 | + print(user_record) |
| 38 | + cursor_object.execute(user_record) |
| 39 | + result = cursor_object.fetchall() |
| 40 | + |
| 41 | + for username, subscription_tier, request_limit, retention_period in result: |
| 42 | + r.set(f'{ALLOWED_PREFIX}-{username}', request_limit) |
| 43 | + |
| 44 | + |
| 45 | +@app.get('/sync_all', status_code=200) |
| 46 | +def sync_all(): |
| 47 | + user_record = """SELECT * FROM subscription_details """ |
| 48 | + records = cursor_object.execute(user_record) |
| 49 | + result = cursor_object.fetchall() |
| 50 | + |
| 51 | + # >>> print(result) |
| 52 | + # [('free_user', 'Free', 10, 1), ('basic_user', 'Basic', 100, 15), ('advanced_user', 'Advanced', 1000, 60), ('test', 'Advanced', 1000, 60)] |
| 53 | + |
| 54 | + logger.debug(result) |
29 | 55 |
|
30 | | -logger.debug(result) |
31 | | -database.close() |
| 56 | + for username, subscription_tier, request_limit, retention_period in result: |
| 57 | + r.set(f'{ALLOWED_PREFIX}-{username}', request_limit) |
32 | 58 |
|
33 | | -for username, subscription_tier, request_limit, retention_period in result: |
34 | | - r.set(f'{ALLOWED_PREFIX}-{username}', request_limit) |
| 59 | +# r.close() |
| 60 | +if __name__ == '__main__': |
| 61 | + requests.get('http://data_population:8020/sync_all/') |
35 | 62 |
|
36 | | -r.close() |
|
0 commit comments