· 6 years ago · Jan 14, 2020, 06:52 PM
1"""
2This script listens for websocket and allows to save/update
3the given user's name and date of birth in the SQLite database
4and then shows days count until specific username's birthday (or congrats).
5Request format is PUT /hello/<username> ( "dateOfBirth": "YYYY-MM-DD" )
6and GET /hello/<username>.
7"""
8
9import logging
10from flask import Flask, request, json
11import sqlite3
12import datetime
13
14logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
15 level=logging.INFO)
16LOGGER = logging.getLogger(__name__)
17
18birthdaybot = Flask(__name__)
19
20def check_date(date_str):
21 now = str(datetime.datetime.now)
22 try:
23 datetime.datetime.strptime(date_str, '%Y-%m-%d')
24 except ValueError:
25 return('bad date format, should be YYYY-MM-DD')
26 exit(1)
27 if datetime.datetime.strptime(date_str, '%Y-%m-%d') > datetime.datetime.now():
28 return('the date is in the future')
29 exit(2)
30
31def save_to_db(name, b_date):
32 conn = sqlite3.connect('birthdaybot.db')
33 cur = conn.cursor()
34 sql = ''' INSERT INTO users(name, b_date)
35 VALUES(?,?) '''
36 create_table = ''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, b_date TEXT) '''
37 cur.execute(create_table)
38 cur.execute(sql, b_date)
39 return cur.lastrowid
40
41@birthdaybot.route('/hello/<username>', methods=['GET', 'PUT'])
42def hello(username):
43 """
44 Receives and checs http request body.
45 Returns 400 error code if request body is not a correct data.
46 """
47 name = username
48 response = ''
49 if request.method == 'PUT' and not request.is_json:
50 response = birthdaybot.response_class(
51 response='{"result": "incorrect json"}',
52 status=400,
53 mimetype='application/json'
54 )
55 elif request.method == 'PUT' and not name.isalpha():
56 response = birthdaybot.response_class(
57 response='{"result": "incorrect username"}',
58 status=400,
59 mimetype='application/json'
60 )
61 elif request.method == 'PUT':
62 b_date = request.json.get('dateOfBirth', None)
63 resp = check_date(b_date)
64 """
65 вот тут вызываешь свою функцию и кладешь в базу и имя и дату рождения
66 """
67 try:
68 save_to_db(name, b_date)
69 except HuyZanetException, error:
70 resp = str(error)
71 response = birthdaybot.response_class(
72 response='{"result": "'+resp+'"}',
73 status=200,
74 mimetype='application/json'
75 )
76 elif request.method == 'GET':
77 print('get')
78 response = birthdaybot.response_class(
79 response='{"result": "GET"}',
80 status=200,
81 mimetype='application/json'
82 )
83 return response
84
85if __name__ == '__main__':
86 birthdaybot.run(host='0.0.0.0', port=8000)