sauceishere
sauceishere

Reputation: 326

How to connect to Azure MySQL from Azure Functions by Python

I am trying to;

  1. Run the python code triggered by Cosmos DB when cosmos DB receives the data..
  2. The python code in Azure Functions has code to ingest data from Azure MySQL.

What I have done are;

Do you know how to install mysql module for Python to Azure Functions and connect to the database?

Thanks!

Upvotes: 1

Views: 3529

Answers (1)

Jay Gong
Jay Gong

Reputation: 23792

According to your description ,I think your issue is about how to install the Python third-party module in the Azure function app.

Please refer to the steps as below :

Step 1 :

login kudu : https://Your_APP_NAME.scm.azurewebsites.net/DebugConsole.

Run Below command in d:/home/site/wwwroot/<your function name> folder.(will take some time)

python -m virtualenv myvenv

Step 2 :

Load the env via the below command in env/Scripts folder.

activate.bat

Step 3 :

Your shell should be now prefixed by (env).

Update pip

python -m pip install -U pip

Install what you need

python -m pip install MySQLdb

Step 4 :

In your code, update the sys.path to add this venv:

import sys, os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), 'env/Lib/site-packages')))

Then connect to mysql db via the snippet of code below

#!/usr/bin/python
import MySQLdb

# Connect
db = MySQLdb.connect(host="localhost",
                     user="appuser",
                     passwd="",
                     db="onco")

cursor = db.cursor()

# Execute SQL select statement
cursor.execute("SELECT * FROM location")

# Commit your changes if writing
# In this case, we are only reading data
# db.commit()

# Get the number of rows in the resultset
numrows = cursor.rowcount

# Get and display one row at a time
for x in range(0, numrows):
    row = cursor.fetchone()
    print row[0], "-->", row[1]

# Close the connection
db.close()

Hope it helps you.

Upvotes: 2

Related Questions