class Post(DB.Model): id = DB.Column(DB.Integer, primary_key=True, autoincrement=True) author_id = DB.Column(DB.Integer, DB.ForeignKey('user.id'), nullable=False) created = DB.Column(DB.DateTime(), nullable=False, default=datetime.datetime.utcnow) title = DB.Column(DB.TEXT(), nullable=False) body = DB.Column(DB.TEXT(), nullable=False) user = DB.relationship('User')
def register(): email = request.json['email'] password = request.json['password'] first_name = request.json['first_name'] last_name = request.json['last_name'] phone = request.json['phone'] error = None with DB() as db: if not email: error = 'Email is required.' elif not password: error = 'Password is required.' elif not first_name: error = 'First Name is required.' elif not last_name: error = 'Last Name is required.' elif not phone: error = 'Phone is required.' if email: db.execute( 'SELECT id FROM accounts WHERE email = %s', (email,) ) if db.fetchone() is not None: error = 'Account {} is already registered.'.format(email) if error is None: db.execute( 'INSERT INTO accounts (email, password, first_name, last_name, phone) VALUES (%s, %s, %s, %s, %s)', (email, generate_password_hash(password), first_name, last_name, phone) ) return "Successful", 201 return error, 400
def list(): with DB() as db: db.execute( '''SELECT transactions.id, transactions.transaction_desc, transactions.amount, accounts.first_name AS seller_name, transactions.status FROM transactions LEFT JOIN accounts on transactions.seller_id = accounts.id WHERE buyer_id = %s OR seller_id = %s;''', (g.account['id'], g.account['id'])) return jsonify(db.fetchall())
def save(self): with DB() as db: values = (self.buyer_id, self.seller_id, self.transaction_desc, self.status, self.amount, self.id) db.execute( '''UPDATE transactions SET buyer_id = ?, seller_id = ?, transaction_desc = ?, status = ?, amount = ? WHERE id = ?''', values) return self
def load_logged_in_user(): account_id = session.get('account_id') if account_id is None: g.account = None else: with DB() as db: db.execute( 'SELECT * FROM accounts WHERE id = %s', (account_id,) ) g.account = db.fetchone()
def transaction_code(transaction_id): try: t_id = int(transaction_id) except ValueError: return 'Id is invalid', 400 with DB() as db: db.execute('SELECT seller_id FROM transactions WHERE paypal_id = %s;', [t_id]) transaction = db.fetchone() if transaction is not None: if g.account['id'] != transaction['seller_id']: return 'Unathorized', 403 return send_file('../qr-codes/{}.png'.format(t_id)) return 'Id is invalid', 400
def create(): transcation_desc = request.json['transaction_desc'] amount = float(request.json['amount']) error = None if not transcation_desc: error = "Transaction Description must" if not amount or amount <= 0: error = "Amount shouldn't be negative" if error is None: email = g.account['email'] headers = {'Content-Type': 'application/json', "Authorization": token} data = { "intent": "CAPTURE", "purchase_units": [{ "amount": { "currency_code": "USD", "value": amount }, "payee": { "email": email } }] } resp = requests.post( 'https://api.sandbox.paypal.com/v2/checkout/orders', headers=headers, json=data) if resp.status_code == 401: print(resp.text) print('Token expired') return "Internal server error", 500 resp_data = resp.json() with DB() as db: id = resp_data['id'] db.execute( "INSERT INTO transactions(paypal_id, seller_id, transaction_desc, amount, status) VALUES (%s, %s, %s, %s, 'Pending');", (id, g.account['id'], transcation_desc, amount)) code = ('QRpayment:{}'.format(id)).encode() img = qrcode.make(fernet.encrypt(code)) img.save('qr-codes/{}.png'.format(id)) return '/transactions/{}'.format(id), 201 return error, 400
def check(): transaction_data = request.json['data'] decrypted = fernet.decrypt(transaction_data.encode()).decode() code = decrypted.split(':') if code[0] != 'QRpayment': print('Unrecognized QR code') return 'Unrecognized QR code', 400 transaction_id = code[-1] print(transaction_id) with DB() as db: db.execute( '''SELECT transactions.id, transactions.paypal_id, transactions.transaction_desc, transactions.amount, accounts.first_name AS seller_name, transactions.status FROM transactions LEFT JOIN accounts on transactions.seller_id = accounts.id WHERE transactions.paypal_id = %s''', [transaction_id]) transaction = db.fetchone() if transaction['status'] == "Pending": return jsonify(transaction), 200 else: return "Transaction is either already complete or invalid", 403
def accept(): id = request.json['id'] error = None if not id: error = "Supply id" if error is None: with DB() as db: db.execute( 'SELECT seller_id,amount FROM transactions WHERE id = %s', (id)) transaction = db.fetchone() transaction_amount = transaction['amount'] db.execute('SELECT balance FROM accounts;') account_balance = db.fetchone()['balance'] print(account_balance) if transaction_amount > account_balance: return "Account balance insufficient", 403 db.execute( '''UPDATE accounts SET balance = balance - %s WHERE id = %s''', (transaction_amount, g.account['id'])) db.execute( '''UPDATE accounts SET balance = balance + %s WHERE id = %s''', (transaction_amount, transaction['seller_id'])) db.execute( '''UPDATE transactions SET buyer_id = %s, status = 'Completed' WHERE id = %s;''', (g.account['id'], id)) # Return users new balance return jsonify({'balance': (account_balance - transaction_amount)}), 201 return error, 400
def login(): email = request.authorization['username'] password = request.authorization['password'] error = None with DB() as db: db.execute( 'SELECT * FROM accounts WHERE email = %s', (email,) ) account = db.fetchone() if account is None: error = 'Incorrect email.' elif not check_password_hash(account['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['account_id'] = account['id'] return 'Successful', 200 return error, 401
class User(DB.Model, UserMixin): id = DB.Column(DB.Integer, primary_key=True) username = DB.Column(DB.String(255), unique=True) email = DB.Column(DB.String(255), unique=True) password = DB.Column(DB.String(255)) active = DB.Column(DB.Boolean()) confirmed_at = DB.Column(DB.DateTime()) roles = DB.relationship('Role', secondary=roles_users, backref=DB.backref('users', lazy='dynamic'))
class Role(DB.Model, RoleMixin): id = DB.Column(DB.Integer(), primary_key=True) name = DB.Column(DB.String(80), unique=True) description = DB.Column(DB.String(255))
import datetime from flask_security import ( UserMixin, RoleMixin, ) from flaskr.db import DB roles_users = (DB.Table( 'roles_users', DB.Column('user_id', DB.Integer(), DB.ForeignKey('user.id')), DB.Column('role_id', DB.Integer(), DB.ForeignKey('role.id')))) class Role(DB.Model, RoleMixin): id = DB.Column(DB.Integer(), primary_key=True) name = DB.Column(DB.String(80), unique=True) description = DB.Column(DB.String(255)) class User(DB.Model, UserMixin): id = DB.Column(DB.Integer, primary_key=True) username = DB.Column(DB.String(255), unique=True) email = DB.Column(DB.String(255), unique=True) password = DB.Column(DB.String(255)) active = DB.Column(DB.Boolean()) confirmed_at = DB.Column(DB.DateTime()) roles = DB.relationship('Role', secondary=roles_users, backref=DB.backref('users', lazy='dynamic'))
def initialize_tables(): """Create any tables needed, if any.""" DB.create_all()
def all(): with DB() as db: db.execute('SELECT * FROM transactions;') rows = db.fetchall() return [Transaction(*row) for row in rows]
def find(id): with DB() as db: db.execute('SELECT * FROM transactions WHERE id = ?', (id, )) row = db.fetchone() return Transaction(*row)
def delete(self): with DB() as db: db.execute('DELETE FROM transactions WHERE id = ?', (self.id, ))
from flaskr.db import DB DB.drop_all() DB.create_all()
def current_user(): with DB() as db: db.execute('SELECT first_name, last_name, email, balance FROM accounts WHERE id = %s', [g.account['id']]) user = db.fetchone() return jsonify(user), 200