-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
100 lines (88 loc) · 3.76 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import logging
from logging.handlers import RotatingFileHandler
import os
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///products.db"
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", "default_secure_key")
# Set up logging
if not app.debug:
handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
app.logger.addHandler(handler)
db = SQLAlchemy(app)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
price = db.Column(db.Float, nullable=False)
with app.app_context():
db.create_all()
@app.route("/product", methods=["POST"])
def create_product():
data = request.get_json()
name = data.get("name")
price = data.get("price")
if not name or not price:
app.logger.warning('Product creation failed: missing name or price')
return jsonify({"error": "Name and price are required"}), 400
try:
price = float(price)
except ValueError:
app.logger.warning('Product creation failed: invalid price')
return jsonify({"error": "Price must be a number"}), 400
new_product = Product(name=name, price=price)
db.session.add(new_product)
db.session.commit()
app.logger.info(f'Product created: {new_product.id}')
return jsonify({"message": "Product created successfully", "product": {"id": new_product.id, "name": new_product.name, "price": new_product.price}}), 201
# Route for retrieving all products
@app.route("/products", methods=["GET"])
def get_products():
products = Product.query.all()
products_list = [{"id": product.id, "name": product.name, "price": product.price} for product in products]
app.logger.info('Products retrieved successfully')
return jsonify(products_list), 200
# Route for retrieving a single product by ID
@app.route("/product/<int:id>", methods=["GET"])
def get_product(id):
product = Product.query.get_or_404(id)
app.logger.info(f'Product retrieved: {product.id}')
return jsonify({"id": product.id, "name": product.name, "price": product.price}), 200
# Route for updating a product by ID
@app.route("/product/<int:id>", methods=["PUT"])
def update_product(id):
product = Product.query.get_or_404(id)
data = request.get_json()
name = data.get("name")
price = data.get("price")
if not name or not price:
app.logger.warning(f'Product update failed for ID {id}: missing name or price')
return jsonify({"error": "Name and price are required"}), 400
try:
price = float(price)
except ValueError:
app.logger.warning(f'Product update failed for ID {id}: invalid price')
return jsonify({"error": "Price must be a number"}), 400
product.name = name
product.price = price
db.session.commit()
app.logger.info(f'Product updated: {product.id}')
return jsonify({"message": "Product updated successfully", "product": {"id": product.id, "name": product.name, "price": product.price}}), 200
# Route for deleting a product by ID
@app.route("/product/<int:id>", methods=["DELETE"])
def delete_product(id):
product = Product.query.get_or_404(id)
db.session.delete(product)
db.session.commit()
app.logger.info(f'Product deleted: {id}')
return jsonify({"message": "Product deleted successfully"}), 200
# Global error handler
@app.errorhandler(Exception)
def handle_exception(e):
app.logger.error('An unexpected error occurred', exc_info=True)
response = {"error": "An unexpected error occurred"}
return jsonify(response), 500
if __name__ == "__main__":
app.run(host='0.0.0.0')