Can bubble run python scripts?

Hey guys wonder if anyone can help me on this -

I want to grab some numbers saved in my Bubble database, use some python code (or any other way you can suggest) to perform some if/or logic and calculations on the numbers. The output would then be a number that I want to save back into my database.

Bit stuck on this and would appreciate any help on it! Cheers

Unless you’re doing complex computation on large datasets then the easiest way to do this is locally using Javascript.

The simplest way to do that in Bubble is to use the Toolbox plugin and use the Run javascript workflow action.

You can bring variables or arrays into your script just how you would normally bring dynamic data into text / search fields.

3 Likes

Thanks @exception-rambler that looks like exactly what I need, certainly no complex computation.

Guess I’ll have to learn some Javascript!

Really appreciate the help, many thanks :facepunch:

Happy to help if you get caught on the script - DM me or put it in a new thread here.
But having some Javascript skills will grant you Bubble superpowers so it’s time well spent.

2 Likes

Thanks again @exception-rambler - one thing I’m not sure of is how to handle cases where there is no value in the database?

Say for example I want to grab a users age and run some logic on it, but if they haven’t entered their age then use a default value of 0

When I’m building plugins I’ll normally include a function that helps me cover the different possibilities of no value. As follows:

function isEmpty(property){
  if (property === '' || property === null || property === undefined) return true;
  else return false;
}

You could add this at the start of your script and then say something like:

if (isEmpty(**Search for your item:first item**)) let newValue = 0;
else { **calculate new value**}

One thing that isn’t 100% straightforward is getting a value back out of your script to use later on.

To do this you’ll need to an a Javascript to Bubble element to your page (this will have come with Toolbox). This workaround is needed because Bubble carefully controls how you can get data back into your workflows / database, so it has to come via a plugin.

Set it up as follows - I’ve used a generic name ‘fetchValue’, you could use anything:

Then finally, back in your workflow, you will finish the script with:

bubble_fn_fetchValue(newValue); where newValue is the name of the variable carrying your adjusted number.

That value will now be available throughout Bubble - either in a Text element / something similar, or in a workflow - by referencing JavascripttoBubbleA’s value

4 Likes

Once again @exception-rambler, thanks a million for this. All working great for me now, really appreciate the detailed explanation and think that your isEmpty function will quickly become a staple of mine…

Hey @exception-rambler - another question I hoped you’d be able to help out with. Wanted to know how private the code I put in my Javascript script will be?

I’m putting some business logic in there which ideally wouldn’t be public so just wanted to check…

Cheers, Lee

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!