How to use Python scripts in n8n (GCP Cloud Run Function)

When do I use it? Does it cost anything?

If you need to input parameter values and receive results from a completed Python script in n8n.
No-code automation tools, including Make, provide limited support for running Python code directly. If you need to install an external Python package (library), you can create it by running Python code without cost through this guide.

What is Cloud Run Function?

(ChatGPT) GCP's Cloud Run is a fully managed serverless platform provided by Google Cloud , an environment where containerized applications can be run. Cloud Run Function generally refers to a serverless application that performs a specific function or role running on Cloud Run .
Cloud Run Cost Structure
Free Tier The following amounts are provided free each month:
CPU: 180,000 vCPU-s (approximately 50 hours)
Memory: 360,000 GiB-s (about 100 hours @ 3GiB)
Request: 2 million
Outbound network: 1GB
If your traffic is low, you may not be charged as long as you don't exceed the free limit.

Step Description

💡
NOTE: This is a somewhat challenging course. It would be helpful if you have some prior knowledge of Google Cloud.
Please create a Google Cloud account and project in advance.
1.
After connecting, search for "Cloud Run" in the search bar , and select the menu labeled "Cloud Run Functions" .
2.
Select Create Function. During this process, a pop-up window about using the API may appear. Just agree to all of them.
3.
Set the function name, select the trigger as “Allow unauthenticated calls” and press Next.
4.
Select Python 3.12 as the runtime . Now, write the Python script you will run in main.py. Place the necessary packages in requirements.txt. In the entry point field, enter the name of the function you will ultimately execute. Once you have finished writing, click Deploy at the bottom .
5.
Please wait a moment and a green check mark will appear, indicating that deployment is complete. Now, if you copy the URL value and run it in the browser, the Python script you wrote earlier will run.
6.
If you deployed the function with the default values, it will appear as below.
7.
If you have written it incorrectly , please edit it, or if you are not using it, please delete it.

Usage Example 1 - Generate SOLAPI Token (Parameter GET)

Main.py (entry point : get_token)
import time
import datetime
import uuid
import hmac
import hashlib
from flask import jsonify, request

def unique_id():
    return str(uuid.uuid1().hex)

def get_iso_datetime():
    utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
    utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
    return datetime.datetime.now().replace(tzinfo=datetime.timezone(offset=utc_offset)).isoformat()

def get_signature(key, msg):
    return hmac.new(key.encode(), msg.encode(), hashlib.sha256).hexdigest()

def get_headers(apiKey, apiSecret):
    date = get_iso_datetime()
    salt = unique_id()
    data = date + salt
    return {
        'Authorization': 'HMAC-SHA256 ApiKey=' + apiKey + ', Date=' + date + ', salt=' + salt + ', signature=' +
                         get_signature(apiSecret, data)
    }

def get_token(request):
    apiKey = request.args.get('apiKey')
    apiSecret = request.args.get('apiSecret')

    if not apiKey or not apiSecret:
        return jsonify({'error': 'apiKey and apiSecret are required!'}), 400

    headers = get_headers(apiKey, apiSecret)
    return jsonify(headers)

Usage Example 2 - Google News URL Decode (Header, Body POST)

curl -X POST https://us-central1-datapopcorn.cloudfunctions.net/googlenewsdecoder \
    -H "Content-Type: application/json" \
    -d '{
        "source_url": "https://news.google.com/rss/articles/CBMidkFVX3lxTE5rWFdRQXNJX1lTVXR1Uzh0dURROUJXVXh1QnZXaUR0WllUZS1NZzRka3BXcTByeVI3d2N3LVNJRWl5aTJxU0lISUxmVXB0dnRCRmZVbFR3c2R4eWg1UnVjNmZSUU9iRnBKbmpSMUEwMEczVHYyNWc?oc=5",
        "interval": 5
    }'
Requirement.txt
Main.py (entry point : get_token)