Flask Web Deployment on Google Cloud

Follow the project here Convert Schedule to .ics, we will going to edit the app.py (main.py)

source code here

Python Script Development

Here is a little bit different from regular app. Most of time we have a landing page under root (/) but since my script is a POST method which is a callable page. It cannot be used to independently. Thus we choose to load the index.html first at root page.

Your main.py file is set up to deploy a web application using Flask, a popular micro web framework in Python. Let's break down this file step by step:

Importing Libraries and Modules

from flask import Flask, request, send_file
from flask_cors import CORS
import io
import datetime
import cal_web  # Import your cal_web script

Setting Up the Flask App

app = Flask(__name__)
CORS(app)

Routing

Index Route

@app.route('/')
def index():
    return app.send_static_file('index.html')

Generate ICS Route

@app.route('/generate-ics', methods=['POST'])
def generate_ics():
    ...

Handling POST Request to Generate ICS

  1. Extracting Data from Request:

    • data = request.json gets the JSON data sent with the POST request.
    • Extracts startDate, endDate, and schedule from the JSON data.
  2. Converting Dates:

    • Converts startDate and endDate from string to datetime objects.
    • If the conversion fails, it returns a 400 error with an "Invalid date input" message.
  3. Generating ICS File:

    • Uses cal_web.parse_input to parse the schedule text.
    • cal_web.parse_and_create_ics_files is then used to create a ZIP file containing the .ics files.
  4. Sending the ZIP File as a Response:

    • The ZIP data is converted to a file-like object using io.BytesIO.
    • send_file is used to send this file as a response to the client, with appropriate headers to prompt a file download.

Running the App

if __name__ == '__main__':
    app.run(debug=True)

Summary

In summary, this script sets up a Flask web server with two endpoints: one for serving the index.html file and another for handling POST requests to generate .ics files from a given schedule. The script integrates with the cal_web module you've previously written to handle the calendar-related logic. The use of CORS allows for cross-origin requests, making it suitable for a modern web application setup.

.yaml edit

Usually editing in this way

runtime: python39  # Specify the Python version
entrypoint: gunicorn -b :$PORT main:app  # Replace 'main' with the name of your Python file without '.py'

Next use html Script HTML Template