Following is local.settings.json file -
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "blob (connection string) that was created when Azure function is created",
"FUNCTIONS_WORKER_RUNTIME": "python",
"My_STORAGE": "blob (connection string) that function should monitor"
}
}
Following is function.json file -
{
"scriptFile": "__init__.py",
"bindings": [{
"name": "myblob",
"type": "blobTrigger",
"direction": "in",
"path": "mycontainer/{name}",
"connection": "My_STORAGE"
}]
}
Following is my code init.py - (test_func is user defined function to do some business logic)
def main(myblob: func.InputStream):
test_func(myblob.name)
logging.info(f "Python blob trigger function processed blob \n"
f "Name: {myblob.name}\n"
f "Blob Size: {myblob.length} bytes")
I am using Ubuntu 16.04.5 LTS local machine to create and publish Python Function App to Azure using CLI and Azure Functions Core Tools (Ref). I have configured Blob Trigger and my function.json file looks like this:, 2 days ago Now that you created every resource needed, it is time to publish your function to Azure. <APP_NAME> is the globally unique name you set in step 2.5. Make sure you are inside your created function. func azure functionapp publish <APP_NAME> --python ,The Function App is "Always On" but when I upload a blob in the storage the function is not getting triggered. Another Reference Link is this (Ref). , 2 days ago Jan 13, 2021 · I am working on one of the Azure Function which is written in Python and it should get called based on Blob trigger event. However, the trigger is not firing when I am uploading a zip file in a blob container to which azure function is supposed to monitor. Following is local.settings.json file -. { "IsEncrypted": false, "Values ...
{ "disabled": false, "scriptFile": "__init__.py", "bindings": [ { "name": "<Blob Trigger Name>", "type": "blobTrigger", "direction": "in", "path": "<Blob Container Name>/{name}", "connection": "<Connection String having storage account and key>" }, { "name": "outputblob", "type": "blob", "path": "<Blob Container Name>", "connection": "<Connection String having storage account and key>", "direction": "out" } ] }
{ "disabled": false, "scriptFile": "__init__.py", "bindings": [ { "name": "<Blob Trigger Name>", "type": "blobTrigger", "direction": "in", "path": "<Blob Container Name>/{name}", "connection": "<Connection String having storage account and key>" }, { "name": "outputblob", "type": "blob", "path": "<Blob Container Name>", "connection": "<Connection String having storage account and key>", "direction": "out" } ] }
def main(<Blob Trigger Name>: func.InputStream, doc: func.Out[func.Document]): logging.info(f"Python blob trigger function processed blob \n" f"Name: {<Blob Trigger Name>.name}\n" f"Blob Size: {<Blob Trigger Name>.length} bytes") logging.basicConfig(filename='example.log',level=logging.DEBUG) logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') # Write text to the file. file = open("QuickStart.txt", 'w') file.write("Hello, World!") file.close() # Create the BlockBlockService that is used to call the Blob service for the storage account block_blob_service = BlockBlobService(account_name='<Storage Account Name>', account_key='<Storage Account Key>') container_name='<Blob Container Name>' # Set the permission so the blobs are public. block_blob_service.set_container_acl(container_name, public_access=PublicAccess.Container) # Upload the created file, use local_file_name for the blob name block_blob_service.create_blob_from_path(container_name, 'QuickStart.txt', '')
func azure functionapp publish "functionname"--publish - local - settings
import logging
import azure.functions as func def main(myblob: func.InputStream): logging.info(f "Python blob trigger function processed blob \n"
f "Name: {myblob.name}\n"
f "Blob Size: {myblob.length} bytes")
{
"scriptFile": "__init__.py",
"bindings": [{
"name": "myblob",
"type": "blobTrigger",
"direction": "in",
"path": "samples-workitems/{name}",
"connection": ""
}]
}
Published Feb 4, 2022
import datetime
import logging
import os
import json
import gzip
from twitterstats
import Fetcher
from azure.storage.blob
import BlobServiceClient
import azure.functions as func
def main(mytimer: func.TimerRequest) - > None:
utc_timestamp = datetime.datetime.utcnow().replace(
tzinfo = datetime.timezone.utc).isoformat()
# Getting follower data
fetcher = Fetcher()
followers = fetcher.get_followers()
# Connecting to Azure Storage
AZURE_CONNECTION_STRING = os.getenv('AzureWebJobsStorage')
container_name = str("output")
blob_name = f "FOLLOWERS_{utc_timestamp}.json.gz"
blob_service_client = BlobServiceClient.from_connection_string(AZURE_CONNECTION_STRING)
blob_client = blob_service_client.get_blob_client(container = container_name, blob = blob_name)
# Upload compressed data to Azure Storage
json_data = json.dumps(followers)
encoded = json_data.encode('utf-8')
compressed = gzip.compress(encoded)
blob_client.upload_blob(compressed)
# Upload tweet stats to Azure Storage
promoted_tweets = fetcher.get_tweets(promoted = True)
unpromoted_tweets = fetcher.get_tweets(promoted = False)
blob_name = f "TWEETS_{utc_timestamp}.json.gz"
blob_client = blob_service_client.get_blob_client(container = container_name, blob = blob_name)
json_data = json.dumps(dict(promoted = promoted_tweets, unpromoted = unpromoted_tweets))
encoded = json_data.encode('utf-8')
compressed = gzip.compress(encoded)
blob_client.upload_blob(compressed)
def get_data_from_azure(blob_service_client, blob_name, container_name = "output",
default = None):
try:
blob_client = blob_service_client.get_blob_client(container = container_name, blob = blob_name)
data = blob_client.download_blob().readall()
uncompressed = gzip.decompress(data)
return json.loads(uncompressed)
except:
return default
def write_to_azure(blob_service_client, blob_name, data, container_name = "output"):
blob_client = blob_service_client.get_blob_client(container = container_name, blob = blob_name)
json_data = json.dumps(data)
encoded = json_data.encode('utf-8')
compressed = gzip.compress(encoded)
blob_client.upload_blob(compressed, overwrite = True)
blobscaninfo/<Your Function Name>/storageAccount/storageContainer
Node.js is not essential for programming in Python, but it is necessary to program functions in JavaScript or to install Azure Core Tools on Windows without using Chocolatey.,Create a Function App in Azure without opening the Portal. This currently works only for the Windows runtime. To select a Linux runtime to be able to program in Python, you will need to create it in the Azure Portal, as described., Create a Function App in Azure without opening the Portal. This currently works only for the Windows runtime. To select a Linux runtime to be able to program in Python, you will need to create it in the Azure Portal, as described. ,You now know a little about programming functions, but to build a more complex application, you need to interface with data storage systems. With this in mind, Azure offers the Blob service.
Then, use it to switch to Node.js version 10.6.0 by using the following command:
nvm install 10.6 .0
You might need to reinstall globally installed Node Package Manager (npm) packages after the switch. You can check whether the correct version is running by using this command:
node - v
On Linux Ubuntu 18.04, use these commands:
wget - q https: //packages.microsoft.com/config/ubuntu/18.04/
packages - microsoft - prod.deb
sudo dpkg - i packages - microsoft - prod.deb
sudo apt - get update
sudo apt - get install azure - functions - core - tools
You can also install it on macOS, using Homebrew:
brew tap azure / functions brew install azure - functions - core - tools
on Windows, using Chocolatey on an administration command line:
choco install azure - functions - core - tools
Python 3.6 is already installed in Linux Ubuntu 18, but there are a couple of things you still need to take into consideration. First, instead of calling python
from the command line, you should use python3
. And you need to install the virtual environment tool for Python by using the following command:
apt - get install python3 - env
By default, the installation directory will be:
c:\users\<username>\AppData\Local\Programs\Python\Python36
But you can change it to something shorter for all users, like this, by selecting “Customize installation”:
C: \python\ python36
Python 2.x is already installed on macOS, and the operating system uses it for some things, so you don’t want to tamper with that version. You can identify which version of Python is running by using the following at the command line:
python - V
Homebrew always installs the latest version of a program by default, but you can instruct it to use an older one by specifying the hash of its repository URL. Here’s how to do that for Python 3.6.7:
brew unlink python
brew install https: //raw.githubusercontent.com/Homebrew/homebrew-core/
f2a764ef944b1080be64bd88dca9a1d80130c558 / Formula / python.rb
You might encounter an error linking to the /user/local/Frameworks folder. If this happens, you must create that directory (and reinstall it again):
sudo mkdir / usr / local / Frameworks
sudo chown $(whoami): admin / usr / local / Frameworks
You can switch to a different version with:
brew
switch python 3.6 .7
On macOS and Linux, using a Bash shell, the commands are as follows:
mkdir myproject cd myproject python - m venv.env source. / .env / bin / activate cd.. func init myproject
Creating the project on Windows with cmd.exe is similar:
mkdir myproject cd myproject python - m venv.env .\.env\ bin\ activate.bat cd.. func init myproject
You should also enter that directory and install or update pip
(to install other packages), ptvsd
(to debug Python files), and pylint
(a linter to check for code mistakes). You might already have those installed in your global Python, but it might be necessary to install them again in your recently activated Python virtual environment:
cd myproject
python - m pip install--upgrade pip
python - m pip install--upgrade ptvsd
python - m pip install--upgrade pylint
Let’s take a look at each of these, starting with the most important one (the one that has the code for the function), __init__.py:
import logging
import azure.functions as func
def main(req: func.HttpRequest) - > func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
return func.HttpResponse(f "Hello {name}!")
else:
return func.HttpResponse(
"Please pass a name in the query string or in the request body",
status_code = 400
)