How to write a Azure Web Job Role by Python and get it running

William Mo
Aug 22, 2017 · 2 min read

There is a very simple requirement, which have a trigger to send email to specific receiver once one record insert to a MySQL data table. it is really simple right?

However, there is not simple way or straight forward way to fulfill this requirement. On the Global Azure, Azure App could a possible solution, but I am running this on Azure China. So solution would be implement a Web job to run a script in a scheduler.

As I am trying to learning Python recently, I try to use Python as my main programming language to instead C# in future. The program could be split to two parts:

  1. Query DB to get the first 20 lines of data and order by time desc
  2. Gather the data and send out email. In this case, I use SendCloud to simplify the SMTP settings.

This is the first time I try Web Job and try Python on a PaaS Azure Website. there are several points are worth to share.

  • How to install python required package

When writing Python code, it is quite simply to import several library, like in this case, “mysql.connector” and requests. But How to install these package without the console? without pip? I googled lots of pages, but there is no standard document to describe this, just some Q&A mentioned this method. Following is the way that I figured out:

  • create a new folder under wwwroot from FTP console.
  • upload the necessary package from your local computer “site-packages” to the newly created folder.
  • add following code at the beginning of your Python code.

```

import sys

sitepackage = “D:\home\site\wwwroot\env\Lib\site-packages”

sys.path.append(sitepackage)

```

Tips: It is not necessary to upload all your package to website, just the package you will be used.I just upload the code file to WebJob and try to run it, and then check the log to see which package is missing, and add one by one.

Following is the code snippet.

)