טיפול בסשנים באמצעות Firestore

באפליקציות רבות נדרש ניהול סשנים לצורך אימות והעדפות משתמש. מסגרת Flask כוללת הטמעה מבוססת-זיכרון לביצוע הפונקציה הזו. עם זאת, ההטמעה הזו לא מתאימה לאפליקציה שאפשר להציג מכמה מופעים, כי הסשן שמתועד במופע אחד עשוי להיות שונה ממופעים אחרים. במדריך הזה מוסבר איך לנהל סשנים ב-App Engine.

מטרות

  • כותבים את האפליקציה.
  • מריצים את האפליקציה באופן מקומי.
  • פורסים את האפליקציה ב-App Engine.

עלויות

במסמך הזה משתמשים ברכיבים הבאים של Google Cloud, והשימוש בהם כרוך בתשלום:

בעזרת מחשבון העלויות אתם יכולים להעריך את העלויות בהתאם לשימוש הצפוי.

משתמשים חדשים של Google Cloud ? יכול להיות שאתם זכאים לתקופת ניסיון בחינם.

כשמסיימים את המשימות שמתוארות במסמך הזה אפשר למחוק את המשאבים שיצרתם כדי להימנע מחיובים נוספים. מידע נוסף זמין בקטע הסרת המשאבים.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אנחנו ממליצים למשתמשים חדשים ב- Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Firestore API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Firestore API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. מתקינים במערכת את Python, את pip ואת virtualenv. הוראות מפורטות זמינות במאמר הגדרת סביבת פיתוח בשפת Python ל- Google Cloud.

הגדרת הפרויקט

  1. בחלון הטרמינל, מתחילים בספרייה לבחירתכם ויוצרים ספרייה חדשה בשם sessions. כל הקוד של המדריך הזה נמצא בספרייה sessions.

  2. עוברים לספרייה sessions:

    cd sessions
    
  3. יוצרים את requirements.txt עם התוכן הבא:

    google-cloud-firestore==2.11.1
    flask==2.2.5
    
  4. מתקינים את יחסי התלות:

    pip install  -r requirements.txt
    

בסוף המדריך, מבנה הקובץ הסופי יהיה דומה לזה:

sessions
├── app.yaml
├── main.py
└── requirements.txt

כתיבת אפליקציית האינטרנט

האפליקציה הזו מציגה ברכות בשפות שונות לכל משתמש. המשתמשים החוזרים תמיד מקבלים פנייה באותה שפה.

כמה חלונות של אפליקציות שמוצגת בהם ברכה בשפות שונות.

כדי שהאפליקציה תוכל לאחסן העדפות של משתמש, צריך דרך לאחסן מידע על המשתמש הנוכחי בסשן. אפליקציית הדוגמה הזו משתמשת בקובצי Cookie וב-Firestore כדי לאחסן נתוני סשן.

  • בחלון הטרמינל, יוצרים קובץ בשם main.py עם התוכן הבא:

    import random
    from uuid import uuid4
    
    from flask import Flask, make_response, request
    from google.cloud import firestore
    
    
    app = Flask(__name__)
    db = firestore.Client()
    sessions = db.collection('sessions')
    greetings = [
        'Hello World',
        'Hallo Welt',
        'Ciao Mondo',
        'Salut le Monde',
        'Hola Mundo',
    ]
    
    
    @firestore.transactional
    def get_session_data(transaction, session_id):
        """ Looks up (or creates) the session with the given session_id.
            Creates a random session_id if none is provided. Increments
            the number of views in this session. Updates are done in a
            transaction to make sure no saved increments are overwritten.
        """
        if session_id is None:
            session_id = str(uuid4())   # Random, unique identifier
    
        doc_ref = sessions.document(document_id=session_id)
        doc = doc_ref.get(transaction=transaction)
        if doc.exists:
            session = doc.to_dict()
        else:
            session = {
                'greeting': random.choice(greetings),
                'views': 0
            }
    
        session['views'] += 1   # This counts as a view
        transaction.set(doc_ref, session)
    
        session['session_id'] = session_id
        return session
    
    
    @app.route('/', methods=['GET'])
    def home():
        template = '<body>{} views for "{}"</body>'
    
        transaction = db.transaction()
        session = get_session_data(transaction, request.cookies.get('session_id'))
    
        resp = make_response(template.format(
            session['views'],
            session['greeting']
            )
        )
        resp.set_cookie('session_id', session['session_id'], httponly=True)
        return resp
    
    
    if __name__ == '__main__':
        app.run(host='127.0.0.1', port=8080)
  • הדיאגרמה הבאה ממחישה איך Firestore מטפל בסשנים באפליקציית App Engine.

    תרשים ארכיטקטורה: משתמש, App Engine, ‏ Firestore.

מחיקת סשנים

אתם יכולים למחוק נתוני סשן או להטמיע אסטרטגיה של מחיקה אוטומטית. אם אתם משתמשים בפתרונות אחסון לסשנים כמו Memcache או Redis, סשנים שתוקפם פג נמחקים אוטומטית.

הרצה באופן מקומי

  1. בחלון הטרמינל, מתקינים את שרת ה-HTTP של Gunicorn:

    pip install gunicorn
    
  2. מריצים את שרת ה-HTTP של Gunicorn:

    gunicorn -b :8080 main:app
    
  3. צפייה באפליקציה בדפדפן האינטרנט:

    Cloud Shell

    בסרגל הכלים של Cloud Shell, לוחצים על Web preview (תצוגה מקדימה של אתר) תצוגה מקדימה של אתר ובוחרים באפשרות Preview on port 8080 (תצוגה מקדימה ביציאה 8080).

    מכונה מקומית

    בדפדפן, עוברים אל http://localhost:8080.

    מופיעה אחת מחמש ברכות: "Hello World",‏ "Hallo Welt",‏ "Hola mundo",‏ "Salut le Monde" או "Ciao Mondo". השפה משתנה אם פותחים את הדף בדפדפן אחר או במצב פרטי. אפשר לראות ולערוך את נתוני הסשן בGoogle Cloud מסוף.

    ‫סשנים של Firestore במסוף Google Cloud .

  4. כדי לעצור את שרת ה-HTTP, בחלון הטרמינל, לוחצים על Control+C.

פריסה והפעלה ב-App Engine

אתם יכולים להשתמש בסביבת ברירת המחדל ב-App Engine כדי ליצור ולפרוס אפליקציה שפועלת בצורה מהימנה בעומס כבד ועם כמויות גדולות של נתונים.

במדריך הזה משתמשים בסביבת ברירת המחדל ב-App Engine כדי לפרוס את השרת.

  1. בחלון הטרמינל, יוצרים קובץ app.yaml ומעתיקים את הטקסט הבא:

    runtime: python37
  2. פורסים את האפליקציה ב-App Engine:

    gcloud app deploy
    
  3. אפשר לצפות באפליקציה הפעילה בכתובת: https://your-project-id.appspot.com:

    gcloud app browse
    

    ‫your-project-id הוא מזהה הפרויקט ב- Google Cloud .

הברכה נשלחת עכשיו על ידי שרת אינטרנט שפועל במכונה של App Engine.

ניפוי באגים באפליקציה

אם אתם לא מצליחים להתחבר לאפליקציית App Engine, כדאי לבדוק את הדברים הבאים:

  1. בודקים שהפקודות gcloud deploy הושלמו בהצלחה ולא הוחזרו שגיאות. אם היו שגיאות (לדוגמה, message=Build failed), תקנו אותן ונסו לפרוס את אפליקציית App Engine שוב.
  2. נכנסים לדף Logs Explorer במסוף Google Cloud .

    כניסה לדף Logs Explorer

    1. ברשימה הנפתחת Recently selected resources, לוחצים על App Engine Application ואז על All module_id. מוצגת רשימה של בקשות מהביקור שלכם באפליקציה. אם לא מוצגת רשימה של בקשות, מוודאים שבחרתם באפשרות All module_id מהרשימה הנפתחת. אם מופיעות הודעות שגיאה במסוף של Google Cloud , צריך לוודא שקוד האפליקציה תואם לקוד שבקטע על כתיבת אפליקציית האינטרנט.

    2. מוודאים ש-Firestore API מופעל.

הסרת המשאבים

מחיקת הפרויקט

  1. במסוף Google Cloud , נכנסים לדף Manage resources.

    כניסה לדף Manage resources

  2. ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  3. כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.

מחיקת המכונה של App Engine

  1. במסוף Google Cloud , נכנסים לדף Versions של App Engine.

    כניסה לדף Versions

  2. מסמנים את התיבה שלצד גרסת האפליקציה שלא מוגדרת כברירת מחדל ושרוצים למחוק.
  3. כדי למחוק את גרסת האפליקציה, לוחצים על Delete.

המאמרים הבאים