Can bubble run python scripts?

I’m not sure if Bubble’s compiler minifies code that is used within workflows. It certainly minifies all plugin code, but it’s possible that it doesn’t ‘see’ the code used in the Run Javascript action.

Minification doesn’t offer real security for your code - it’s there to reduce the file sizes - but it does make it really hard to read. For example:

var profit = 1000;
var scaler = 0.3;
function secretCalc(input, multiplier) {
    return (input *100) / multiplier;
}
console.log(secretCalc(profit, scaler);

Becomes:

var n=1e3;var r=.3;function e(n,r){return n*100/r}console.log(e(n,r));

And this code will be sat within a sea of other a, b and c variables and functions. From personal experience I can tell you it’s between really hard --> impossible to work out what’s going on. So once you’ve written your code you can use a tool like this to minify it.

Alternatively you can run your code server side (Backend Workflows in Bubble) and then it will never touch the client. Toolbox has a server side action too - Server Script - you can see how it works here. You’ll need to save the return value to the database in order to access it back on the client.

2 Likes

Thanks for all the info shared on this thread, its super helpful. I’m curious if you think it’d be possible to take an image uploaded to a bubble app, pass it to pythonanywhere to do some image transformations/detections using openCV, and then return the transformed image back to bubble?

Hey Ken, I’m really curious - how are you actually storing/attaching the processed csv’s onto a bubble thing from python? Do you have to base64 encode first? In my case I’m trying to attach a .pickle file onto a bubble thing and am really scratching my head on how to proceed.

Actually, never mind :slight_smile: I just figured it out!!

Python side it looks like

from flask import Flask, json, jsonify, make_response, request
from werkzeug.wrappers import Response
from werkzeug.wsgi import FileWrapper
import io
import pandas as pd

@app.route('/process-zipfile', methods=['GET'])
def call13():
    zip_url = request.form.get('zip_url')
    ## CREATE PANDAS DATAFRAME ##

    df = df[columns]
    buffer = io.BytesIO()
    df.to_pickle(buffer)
    buffer.seek(0)
    file_wrapper = FileWrapper(buffer)
    headers = {
        'Content-Disposition': 'attachment; filename="{}"'.format("df_cleaned.pkl")
    }
    response = Response(file_wrapper,
                        mimetype='application/octet-stream',
                        direct_passthrough=True,
                        headers=headers)
    return response

And then you would call that endpoint / catch the response using the Bubble API connector (as a GET request that saves a FILE)

2 Likes

Hey @gevestobs, I am currently trying to deploy a simple python selenium webscraping script as a scheduled task on PythonAnywhere. I have been struggling to make it work for some time. The script functions as a quick check that verifies a new user’s social media following when they register on our bubble site. I want the script to run as soon as they register. However, when trying to connect the scheduled task to our website using the API Connector, I cannot see the parameter I have specified in the script. I just see general information that PythonAnwyhere provides such as “Expiry Date”, “Time Scheduled”, etc.

Apologies if it’s too specific but if you are aware of what steps to take, I would really appreciate some help!

I need to use Python scripts I’ve written to gather specific information and then take that data and create and update database entries. How hard or easy is it to update Bubble’s database after you run a Python script?

Here’s a Python snippet I wrote for retrieving database data. I haven’t yet written anything to directly modify the Bubble DB via API/Python but that of course is one option available to you. Another option is to create a webhook endpoint/workfllow in Bubble that you call via your Python script that will then do the updating for you.

1 Like

I used https://themasonry.com/flow to quickly host a few python scripts that I integrated into my app.

1 Like

Hi @gevestobs,

Is it possible to see the use case with Discord?

Hi,
I’m using pythonanywhere to get a csv file from bubble, clean it and send back something that bubble can work with to put into the db. For some reason I can’t get panda to work so I am reading the file and then sending it back to bubble as text. I try to create a dictionary in python with key value pairs but I don’t know how to return that for bubble to use (I get an error if I try to return it directly). Any insight would be very helpful. This is the code with which I do a post request:
@app.route("/getfile", methods=[‘POST’])
def getfile():
file = request.files[‘file’]
file_content = file.read()

#store the file contents as a string
fstring = file.read()

#create list of dictionaries keyed by header row
csv_dicts = [{k: v for k, v in row.items()} for row in csv.DictReader(fstring.splitlines(), skipinitialspace=True)]
#print(csv_dicts)
#do something list of dictionaries

#return csv_dicts //gives error
return file_content //can’t access text file in bubble design interface

Much thanks!
Ina

Hey Ina! Looks like you’re using Python’s Flask library in your code. I’ve used this on Pythonanywhere before with Bubble to good success and you can too. To figure things out, take a look at making the most basic flask example work / return JSON to bubble (google flask getting started return json hello world or something similar). That will b the best place to start. As for your problem in particular, I don’t see you’re code attempting to return your dict as JSON. Any Flask examples that you see using jsonify should steer you in the right direction. Best!

Thank you very much for your input! I’ll look into jsonify to see if I can return the dictionary to bubble. Thanks!

hey @mebeingken - wonder if you could explain how you connect up google cloud functions to your Bubble app? struggling a little with it…

This is a guide for setting up Google Cloud Run with Flask:

You can then use this for Bubble to communicate with your app.

1 Like

Hey so to understand this correctly, is bubble GETting from the flask server? ie, bubble GETs from /process-zipfile, and the response is provided by your python code?

That’s exactly right. And from Bubble’s side, that API connector request should be set to FILE so that it can download it without error.

1 Like

Hi! I want to run my python file in my bubble app, but I have a hard time connecting the two. Is there a chance you could help me with that?

you can’t

Hi @hristina.nik.pi,

Running Python in your Bubble app is not possible, but there are a couple of things you can do:

  1. Convert your Python script to Javascript, using the Toolbox plugin it is possible to execute Javascript in the frontend and backend.
  2. Use an external service like PythonAnywhere to run the script. You might need to extend your script with REST API’s (f.i. FastAPI) in order to receive data from and send data to Bubble.

Another platform I regularly use to process data before it is send to Bubble is Anvil.works, it’s quite good because they have developed a number of libraries to speed up development.

Best,

Gerbert
MVP Design

I have a follow up q.

I’m running a python script in Azure functions. It returns the ‘response’ To Bubble and all works well.

However, now I would like to add a streaming function. Can bubble receive a streamed response from an API and display it to the user ‘as it comes in’?

If yes, how?

Thank you!
P