Advertisement
MaximF

Untitled

Aug 14th, 2020 (edited)
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. import pymysql
  2. from flask import Flask, request
  3.  
  4. import balance
  5.  
  6. app = Flask(__name__)
  7.  
  8. db = pymysql.connect(
  9.         'localhost',
  10.         'user',
  11.         'password',
  12.         'my_db',
  13.         cursorclass=pymysql.cursors.DictCursor
  14.     )
  15.  
  16. # my request is POST with JSON body {"id": any integer}
  17. @app.route('/get', methods=['POST'])
  18. def get_data():
  19.     try:
  20.         json = request.json
  21.         if json is None or 'id' not in json.keys():
  22.             return jsonify({'data': {}, 'code': 1}), 400
  23.  
  24.         id_ = json['id']
  25.         if not isinstance(id_, int):
  26.             return jsonify({'data': {}, 'code': 2}), 400
  27.         if id_ < 1 or id_ > 2147483647:
  28.             return jsonify({'data': {}, 'code': 6}), 400
  29.  
  30.         print(db._sock) # checking if there is a connection. It wil print None when InterfaceError.
  31.         with db.cursor() as cur:
  32.             cur.execute(f'select id from users where id = {id_}') # InterfaceError occurs here (at first query to db).
  33.             res = cur.fetchall()
  34.  
  35.             if not res:
  36.                 cur.execute(f'insert into users (id) values ({id_})')
  37.                 cur.execute(f'insert into settings (userId) values ({id_})')
  38.                 cur.execute(f'insert into ntfs (userId) values ({id_})')
  39.                 db.commit()
  40.  
  41.         user = balance.get_money(CURRENCIES, id_) # my function, not relevant to problem
  42.         user.sort(key=lambda u: 0 if u[1] is None else u[1], reverse=True)
  43.         return jsonify({'data': user, 'code': 0}), 200
  44.  
  45.     except Exception as e:
  46.         print('Get -', e.__class__.__name__, e)
  47.         pprint(request.json)
  48.         return jsonify({'data': {}, 'code': -1}), 500
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement