import json import requests import pandas as pd from flask import Flask, render_template, request, send_from_directory import threading import os app = Flask(__name__) # Sabitler (Constants) DEFAULT_PRODUCT_COUNT = 24 DEFACTO_URL = f"https://www.defacto.com.tr/Catalog/PartialIndexScrollResult?page=1&SortOrder=0&pageSize={DEFAULT_PRODUCT_COUNT}&fx_c1=1&fx_c2=1413" TIMEOUT = 15 # Bağlantı zaman aşımı süresi (saniye) EXCEL_FILE_NAME = "urunler.xlsx" # Global değişkenler old_products = pd.DataFrame() products = [] # HTML şablonu (index.html) - GÜNCELLENDİ HTML_TEMPLATE = """ Defacto İndirim Takip

Defacto İndirimli Ürünler

Ürünler

Ürün Adı İndirim Normal Fiyat
""" # Dosya yükleme formu ve ana sayfa artık aynı yerde @app.route("/") def index(): return HTML_TEMPLATE # Veri çekme fonksiyonu @app.route("/fetch_data") def fetch_data(): global products try: max_products = int(request.args.get('product_count', DEFAULT_PRODUCT_COUNT)) url = DEFACTO_URL.replace(f"pageSize={DEFAULT_PRODUCT_COUNT}", f"pageSize={max_products}") response = requests.get(url, timeout=TIMEOUT) response.raise_for_status() api_response = response.json() products = filter_discounted_products(api_response, max_products) return {"message": "Veriler çekildi.", "products": products} except (ValueError, requests.exceptions.RequestException, json.JSONDecodeError) as e: return {"message": f"Hata: {e}", "products": []} # Excel'e kaydetme fonksiyonu @app.route("/save_to_excel") def save_to_excel(): global products try: if products: df = pd.DataFrame(products) df.to_excel(EXCEL_FILE_NAME, index=False) return {"message": f"Veriler {EXCEL_FILE_NAME} dosyasına kaydedildi."} else: return {"message": "Kaydedilecek veri yok.", "error": True} except Exception as e: return {"message": f"Kaydetme hatası: {e}", "error": True} # İndirim kontrol fonksiyonu @app.route("/check_for_discounts") def check_for_discounts(): global old_products if old_products.empty: return {"message": "Lütfen önce Excel dosyasını yükleyin.", "error": True} try: max_products = int(request.args.get('product_count', DEFAULT_PRODUCT_COUNT)) url = DEFACTO_URL.replace(f"pageSize={DEFAULT_PRODUCT_COUNT}", f"pageSize={max_products}") response = requests.get(url, timeout=TIMEOUT) response.raise_for_status() current_products = filter_discounted_products(response.json(), max_products) changes_message = "" for old_product in old_products.to_dict('records'): if matching_current_product := next((p for p in current_products if p['name'] == old_product['name']), None): if matching_current_product['discount'] > 0: changes_message += (f"Ürün: {old_product['name']}\n" f"Eski Fiyat: {old_product['normalPrice']}\n" f"Güncel İndirim: {matching_current_product['discount']}\n\n") if changes_message: return {"message": changes_message} else: return {"message": "İndirim değişikliği bulunamadı."} except (ValueError, requests.exceptions.RequestException, json.JSONDecodeError) as e: return {"message": f"Hata: {e}", "error": True} except Exception as e: return {"message": f"Bir hata oluştu: {e}", "error": True} # İndirimli ürünleri filtreleyen fonksiyon - GÜNCELLENDİ def filter_discounted_products(api_data, max_products): discounted_products = [] product_count = 0 if "Data" in api_data and "SearchResponse" in api_data["Data"]: for product in api_data["Data"]["SearchResponse"]["Documents"]: if product_count >= max_products: break campaign = product.get("CampaignBadge") if campaign and "DiscountAmount" in campaign: discounted_products.append({ "name": product.get("ProductName", "Unknown"), "discount": campaign["DiscountAmount"], "normalPrice": product.get("ProductPriceInclTax", 0) }) product_count += 1 return discounted_products # Excel dosyasını yükleme fonksiyonu @app.route('/upload_excel', methods=['POST']) def upload_excel(): global old_products try: if 'file' not in request.files: return {"message": "Dosya seçilmedi.", "error": True} file = request.files['file'] if file.filename == '': return {"message": "Dosya seçilmedi.", "error": True} if file: old_products = pd.read_excel(file) if not {'name', 'normalPrice'}.issubset(old_products.columns): return {"message": "Excel dosyasında 'name' ve 'normalPrice' sütunları bulunamadı.", "error": True} return {"message": "Excel dosyası başarıyla yüklendi."} except Exception as e: return {"message": f"Excel dosyası yüklenirken bir hata oluştu: {e}", "error": True} if __name__ == "__main__": # Uygulamayı ayrı bir iş parçacığında (thread) çalıştır def run_app(): app.run(host='0.0.0.0', port=8081, debug=True, use_reloader=False) thread = threading.Thread(target=run_app) thread.daemon = True # Ana iş parçacığı sonlandığında bu iş parçacığının da sonlanmasını sağla thread.start() # Pydroid3'te ana iş parçacığının çalışmaya devam etmesini sağlamak için bir döngü ekleyin # (Aksi takdirde uygulama hemen kapanır) while True: import time time.sleep(1)