🎯 هدف الدرس
تعلم كيف يمكن لتطبيق Flask حفظ الملاحظات في السحابة بدلًا من الحفظ المحلي فقط،
مع ضمان الأمان والتشفير قبل رفع الملفات.
🧩 الفكرة العامة
سنضيف خاصية جديدة في تطبيقنا وهي:
- عند حفظ ملاحظة، يتم تشفيرها أولًا (كما في الدرس 14).
- ثم تُرفع نسخة منها إلى التخزين السحابي (Google Drive أو Firebase).
- يمكن للمستخدم استرجاع الملاحظات من السحابة في أي وقت.
🧠 الجزء الأول: استخدام Google Drive API
الخطوة 1️⃣ – إعداد Google Cloud Console
1- انتقل إلى Google Cloud Console.2- أنشئ مشروعًا جديدًا باسم مثل: Flask Notes Cloud Sync.
3- فعّل خدمة Google Drive API.
4- أنشئ بيانات اعتماد (Credentials) من النوع:
- OAuth Client ID
- وحدد نوع التطبيق: Web Application.
credentials.json — قم بحفظه في مجلد مشروعك.الخطوة 2️⃣ – تثبيت المكتبات المطلوبة
افتح الطرفية (Terminal) ونفّذ:
pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
الخطوة 3️⃣ – كتابة كود رفع ملف إلى Google Drive
افتح ملفًا جديدًا باسم drive_upload.py وأضف:
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle, os
SCOPES = ['https://www.googleapis.com/auth/drive.file']
def upload_to_drive(filename):
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('drive', 'v3', credentials=creds)
file_metadata = {'name': os.path.basename(filename)}
media = MediaFileUpload(filename, mimetype='text/plain')
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print(f"✅ Uploaded to Google Drive with ID: {file.get('id')}")
الخطوة 4️⃣ – دمجها مع Flask
في ملف Flask الرئيسي، بعد تشفير الملاحظة، أضف:
from drive_upload import upload_to_drive
@app.route('/upload/<int:id>')
def upload_note(id):
note = Note.query.get(id)
filename = f"note_{id}.txt"
with open(filename, "w", encoding="utf-8") as f:
f.write(note.content)
upload_to_drive(filename)
flash("تم رفع الملاحظة إلى Google Drive بنجاح ✅", "success")
return redirect(url_for('index'))
🔥 الجزء الثاني: استخدام Firebase Storage
الخطوة 1️⃣ – إعداد Firebase Project
- ادخل إلى Firebase Console.
- أنشئ مشروعًا جديدًا باسم Notes Cloud Sync.
- فعّل خدمة Storage.
- حمّل ملف الإعداد
serviceAccountKey.json.
الخطوة 2️⃣ – تثبيت مكتبة Firebase Admin
pip install firebase-admin
الخطوة 3️⃣ – كود رفع الملف إلى Firebase
أنشئ ملفًا جديدًا باسم firebase_upload.py وضع فيه:
import firebase_admin
from firebase_admin import credentials, storage
import os
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred, {"storageBucket": "your-project-id.appspot.com"})
def upload_to_firebase(filename):
bucket = storage.bucket()
blob = bucket.blob(os.path.basename(filename))
blob.upload_from_filename(filename)
blob.make_public()
print(f"✅ Uploaded to Firebase: {blob.public_url}")
الخطوة 4️⃣ – دمجها في Flask
أضف زرًا جديدًا في واجهة التطبيق:
<a href="{{ url_for('upload_firebase', id=note.id) }}" class="btn btn-warning">رفع إلى Firebase ☁️</a>
وفي Flask:
from firebase_upload import upload_to_firebase
@app.route('/upload_firebase/<int:id>')
def upload_firebase(id):
note = Note.query.get(id)
filename = f"note_{id}.txt"
with open(filename, "w", encoding="utf-8") as f:
f.write(note.content)
upload_to_firebase(filename)
flash("تم رفع الملاحظة إلى Firebase بنجاح ☁️", "success")
return redirect(url_for('index'))
💪 تمرين عملي للدرس 15
المطلوب:
- أضف خيارًا في واجهة التطبيق يسمح للمستخدم بالاختيار بين رفع الملاحظات إلى Google Drive أو Firebase.
- عند الحفظ، يتم رفع الملاحظة إلى السحابة المختارة تلقائيًا.
✅ الحل المقترح (مختصر):
@app.route('/cloud_upload/<int:id>/<provider>')
def cloud_upload(id, provider):
note = Note.query.get(id)
filename = f"note_{id}.txt"
with open(filename, "w", encoding="utf-8") as f:
f.write(note.content)
if provider == "drive":
upload_to_drive(filename)
else:
upload_to_firebase(filename)
flash(f"تم رفع الملاحظة بنجاح إلى {provider} ☁️", "success")
return redirect(url_for('index'))

