Skip to content

Instantly share code, notes, and snippets.

@debdutgoswami
Created April 6, 2020 21:35
Show Gist options
  • Save debdutgoswami/383233b20b28f7841f37816fe7ad7b5d to your computer and use it in GitHub Desktop.
Save debdutgoswami/383233b20b28f7841f37816fe7ad7b5d to your computer and use it in GitHub Desktop.
Cloud Function Python code to store emails in a Google Sheet.

Subscribe with Email

This is simple implementation for a mini project wherein there is an option for the users to subscribe to a mailing list. This directly adds the user's email to Google Sheets.


# Function dependencies, for example:
# package>=version
gspread>=3.1.0
oauth2client>=4.1.3
import gspread
from oauth2client.service_account import ServiceAccountCredentials
def subscribe(request):
data = {
# paste your credentials.json file here
}
_name = "Your Google Sheets' Name"
request_json = request.get_json()
request_args = request.args
if request_json and ("email" in request_json):
email = request_json["email"]
else:
email = request_args["email"]
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_dict(data,scope)
client = gspread.authorize(creds)
sheet = client.open(_name).sheet1
rows = sheet.get_all_records()
for row in rows:
row_email = row['email']
if row_email == email:
return '409'
sheet.append_row([email])
return '200'
@alexanu
Copy link

alexanu commented Sep 29, 2022

Hi Debdut, Thank you for posting this gist.
When I'm trying to run similar code in google cloud function, the line 20 produces an error "not JSON serializable".
In the code I do like this

    with open('google-sheets-creds.json') as f:
        gs_creds = json.load(f)
	...
	credentials = ServiceAccountCredentials.from_json_keyfile_dict(gs_creds, scope)

Did have a similar issue?
What do you mean in line 6 by "paste your credentials.json file here"? to pu here name of the file or content of the file?

Thank you!

@debdutgoswami
Copy link
Author

Hey @alexanu
I meant to put the content of the file there, not the name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment