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

אפליקציות רבות צריכות לטפל בסשנים לצורך אימות והעדפות משתמש. Flask framework כולל הטמעה מבוססת-זיכרון לביצוע הפונקציה הזו. עם זאת, ההטמעה הזו לא מתאימה לאפליקציה שאפשר להציג מכמה מופעים, כי הסשן שמתועד במופע אחד עשוי להיות שונה מסשנים במופעים אחרים. במדריך הזה נסביר איך לטפל בסשנים ב-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.

    מכונה מקומית

    בדפדפן, עוברים אל 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 הושלמו בהצלחה ולא הופיעו שגיאות. אם היו שגיאות (לדוגמה, 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.

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