|
| 1 | +from flask_sqlalchemy import SQLAlchemy |
| 2 | +from sqlalchemy.exc import IntegrityError |
1 | 3 | from models import Currency |
2 | 4 |
|
| 5 | +db = SQLAlchemy() |
| 6 | + |
3 | 7 | class Trade(db.Model): |
| 8 | + __tablename__ = 'trades' |
| 9 | + |
4 | 10 | id = db.Column(db.Integer, primary_key=True) |
5 | | - user_id = db.Column(db.Integer, db.ForeignKey('user.id')) |
6 | | - currency_id = db.Column(db.Integer, db.ForeignKey('currency.id')) |
| 11 | + user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) |
| 12 | + currency_id = db.Column(db.Integer, db.ForeignKey('currencies.id'), nullable=False) |
7 | 13 | amount = db.Column(db.Float, nullable=False) |
8 | 14 | price = db.Column(db.Float, nullable=False) |
9 | 15 |
|
10 | 16 | currency = db.relationship('Currency', backref='trades') |
11 | 17 |
|
12 | 18 | def __repr__(self): |
13 | | - return f"Trade('{self.user_id}', {self.amount}, {self.price}, {self.currency.symbol})" |
| 19 | + return f"Trade('{self.user_id}', {self.amount}, {self.price}, '{self.currency.symbol}')" |
| 20 | + |
| 21 | + def total_value(self) -> float: |
| 22 | + """Calculate the total value of the trade.""" |
| 23 | + return self.amount * self.price |
| 24 | + |
| 25 | + @classmethod |
| 26 | + def create(cls, user_id: int, currency_id: int, amount: float, price: float): |
| 27 | + """Create a new trade instance and add it to the database.""" |
| 28 | + new_trade = cls(user_id=user_id, currency_id=currency_id, amount=amount, price=price) |
| 29 | + try: |
| 30 | + db.session.add(new_trade) |
| 31 | + db.session.commit() |
| 32 | + return new_trade |
| 33 | + except IntegrityError: |
| 34 | + db.session.rollback() |
| 35 | + raise ValueError("Failed to create trade. Please check the provided data.") |
| 36 | + |
| 37 | + @classmethod |
| 38 | + def get_all(cls): |
| 39 | + """Retrieve all trades from the database.""" |
| 40 | + return cls.query.all() |
| 41 | + |
| 42 | + @classmethod |
| 43 | + def get_by_user(cls, user_id: int): |
| 44 | + """Retrieve all trades for a specific user.""" |
| 45 | + return cls.query.filter_by(user_id=user_id).all() |
| 46 | + |
| 47 | +# Example usage |
| 48 | +if __name__ == "__main__": |
| 49 | + from flask import Flask |
| 50 | + |
| 51 | + app = Flask(__name__) |
| 52 | + app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///trades.db' |
| 53 | + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False |
| 54 | + db.init_app(app) |
| 55 | + |
| 56 | + with app.app_context(): |
| 57 | + db.create_all() # Create the database tables |
| 58 | + |
| 59 | + # Example of creating a trade |
| 60 | + try: |
| 61 | + # Assuming you have a user with ID 1 and a currency with ID 1 |
| 62 | + trade = Trade.create(user_id=1, currency_id=1, amount=10, price=50000) |
| 63 | + print(f"Trade created: {trade}") |
| 64 | + |
| 65 | + # Calculate total value of the trade |
| 66 | + print(f"Total value of the trade: {trade.total_value()}") |
| 67 | + |
| 68 | + # Retrieve all trades |
| 69 | + all_trades = Trade.get_all() |
| 70 | + print(all_trades) |
| 71 | + |
| 72 | + # Retrieve trades by user |
| 73 | + user_trades = Trade.get_by_user(1) |
| 74 | + print(user_trades) |
| 75 | + |
| 76 | + except ValueError as e: |
| 77 | + print(e) |
0 commit comments