[Azure] Try using Azure Functions

Introduction

This is a memo when I tried FaaS (Function as a Service), which is a representative of serverless computing, on Azure.

Azure has a feature for deploying functions called "Azure Functions" (function app). In AWS, it is a function corresponding to "AWS Lambda".

For the time being, I'll write it down so that I don't forget how to deploy some locally created function.

(There are several other ways)

What to prepare

python is made with 3.7.3. Since Azure is a Microsoft service (??), we will create it using VScode.

procedure

What we will create is a "function that returns the day of the week after entering the year / month / day".

Create an empty folder on your desktop to store the material "sample functions" and work in it. スクリーンショット (400).png

① Previous work: Install azure-functions-core-tools

Azure Functions Core Tools seems to be a module for developing and testing functions locally from a terminal or command prompt. I'll put it in first for the time being.

Just open the VScode terminal and type the command.

npm install -g azure-functions-core-tools

② Create a function

Then at the terminal

func init

Type. A screen like "Please select the language to use" will appear, so select'python'.

Then, some files will be generated in the folder. These are the files needed for deployment. If you need additional libraries, add them to requirements.txt.

Then at the terminal

func new

Type. Then, a screen like "Please select a template to use" will appear. This time I want to create a function that returns some value when I throw a query, so select Http trigger. You will be asked "Tell me the name of the function", so this time I will set it to "WhatDayOfWeek".

A folder named "WhatDayOfWeek" is created in the "sample function" folder, and contains the template. スクリーンショット (423).png

This __init__.py describes the processing to be performed on the cloud side. In the template, if you throw a character string in an HTTP request, it will return "Hello [name entered]!". logging is a standard python module for working with logs. It is not written in requirements.txt, but it can be used. (On the contrary, if you add it poorly, you can not deploy it.)

Only this __init__.py is OK to process.

__init__.py


import logging

import azure.functions as func

#A function that only determines if it is a leap year
def LeapOrNot(Y):
    if (Y % 4 != 0):
        return False
    elif (Y % 100 != 0):
        return True
    elif (Y % 400 != 0):
        return False
    else:
        return True

#Judgment of the number of leap years The standard is Thursday, January 1, 1970
def HowManyLeap(Y):
    mul4 = Y // 4 - 492 #492 = 1970 // 4
    mul100 = Y // 100 - 19 # 19 = 1970 // 100
    mul400 = Y // 400 - 4 # 4 = 1970 // 400
    return mul4 - mul100 + mul400

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    days = ['Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue', 'Wed']
    day_num = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    Year = req.params.get('Year')
    Month = req.params.get('Month')
    Date = req.params.get('Date')

    if not (Year and Month and Date):
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            Year = req_body.get('Year')
            Month = req_body.get('Month')
            Date = req_body.get('Date')

    Y = int(Year)
    M = int(Month)
    D = int(Date)

    #edit validation
    if Y < 1970:
        return func.HttpResponse('Not supported before 1970',status_code=400)
    elif M > 12:
        return func.HttpResponse('Wrong date',status_code=400)
    elif LeapOrNot(Y):
        if M == 2:
            if day_num[M-1] + 1 < D:
                return func.HttpResponse('Wrong date',status_code=400)
        elif day_num[M-1] < D:
            return func.HttpResponse('Wrong date',status_code=400)
    else: 
        if day_num[M-1] < D:
            return func.HttpResponse('Wrong date',status_code=400)
    
    #Calculate the number of days elapsed
    passed_num = (Y - 1970) * 365 + sum(day_num[:M-1]) + D - 1
    if LeapOrNot(Y) and M > 2:
        leap_num = HowManyLeap(Y)
    elif LeapOrNot(Y):
        leap_num = HowManyLeap(Y-1)
    else:
        leap_num = HowManyLeap(Y)

    return func.HttpResponse('{}'.format(days[(passed_num + leap_num) % 7]))

The function itself is now complete. You can also create another function by typing func new in the" sample function "folder.

(③) Test locally

If you want to test if it works as expected

func start

For all the functions in the folder WhatDayOfWeek: [GET,POST] http://localhost:7071/api/WhatDayOfWeek You can get a URL like this. With this, http://localhost:7071/api/WhatDayOfWeek?Year=2020&Month=3&Day=26 You can do a test such as throwing a parameter and returning Thu.

④ Deploy to the cloud

Once you have completed the function locally, it's time to deploy. If you include an Azure extension, you can use the Azure function from the VScode activity bar. You should see "FUNCTIONS" in the sidebar, from which you should see the locally created functions in "Local Project"-> "Functions".

You can deploy from the part shown in the red frame here. (If you haven't logged in to your Azure account, you'll need to log in here.) With this button alone, the functions contained in "Local Project" can be deployed together.

From here, you can operate the deployment work on Azure from VS code. (If you create all the resources in the Azure portal, you can just deploy them to the original Azure Functions resources as they are.)

I will make it from scratch. <1> +Create new Function App in Azure (Advanced) You will be asked if you want to create a new function app. The function app created by the subscription you are logged in to will be displayed, so if you create it in advance, you can just select it here. Some people don't say "Advanced", but there are fewer settings.

<2> Enter the name of the function app

You will be asked for the name of the function app you will create on Azure, so enter it. Here, set it as "sample functions". It seems that this name must be'globally unique', but is it the theory that there are not many users to be able to make it with this name? ?? </ del>

<3> Language selection

Select the language to use in the function app. You can select node.js, java, etc., but here we will use python. I was asked when I made it locally, but is it asked here as well? I think </ del>

<4> Billing plan selection

You will see "Select a hosting plan". This is a billing plan, which is described in detail in Azure official documentation. Roughly speaking

There are 3 choices. Is pay-as-you-go the most FaaS-like? Impression that. This time, let's set it to Consumption.

<5> Select a resource group

Select the resource group to which the function app belongs. If you make a new one, you will probably be asked what region you want to make, but here we will use the original one.

<6> Select a storage account

Storage for data. This also uses the original one.

<7> Select Application Insights

Application Insights is like a monitoring monitor for functions. It seems that you can see the log and performance status. (Official Document)

If it was originally created with another App Service, it seems that you can select it and integrate it. This can be skipped, so you may not need it if you just want to create a function for the time being.

At this point, the deployment will start. You can also see the log during deployment from the "output" of VScode. スクリーンショット (420).png

⑤ Try using the created function

If "Deployment to ~~ completed" appears, the deployment is complete. At this point you can also see the function page from the Azure portal. スクリーンショット (421).png If you click "URL" on this screen, you should see a screen like "Your function is working!".

The URL of the function can be obtained from VScode by right-clicking [Subscription name]-> [Created function name]-> "Functions"-> [Function name] and selecting "Copy Function Url".

Let's experiment by creating python code locally.

python


import requests

url = "[Acquired URL]"

param = {'Year':2020,'Month':3,'Date':26}

res = requests.get(url, params = param)

print(res.text)

☟ Result

Thu

at the end

When using FaaS on Azure, there seems to be a way to do it all with CLI. I'm not quite sure about it. I tried and errored while looking at the official document, but I had a hard time. If you just want to "create a function and deploy it for the time being", I think it's like this.

Recommended Posts

[Azure] Try using Azure Functions
Try using Azure Logic Apps
Azure Functions: Try Durable Functions for Python
Try using Tkinter
Try using docker-py
Try using cookiecutter
Try using geopandas
Try using Selenium
Try using scipy
Try using pandas.DataFrame
Try using django-swiftbrowser
Try using matplotlib
Try using tf.metrics
Try using PyODE
Try using Python with Google Cloud Functions
Try using virtualenv (virtualenvwrapper)
Try using virtualenv now
Try using W & B
Try using Django templates.html
[Kaggle] Try using LGBM
Try using Python's feedparser.
Try using Python's Tkinter
Memo using trigonometric functions
Try using Tweepy [Python2.7]
Try using Jupyter Notebook of Azure Machine Learning
Try using Pytorch's collate_fn
Try using PythonTex with Texpad.
[Python] Try using Tkinter's canvas
Try using Jupyter's Docker image
Try using scikit-learn (1) --K-means clustering
Try using matplotlib with PyCharm
Try using Kubernetes Client -Python-
Try using the Twitter API
Try using OpenCV on Windows
Try using Jupyter Notebook dynamically
Try using AWS SageMaker Studio
Try tweeting automatically using Selenium.
Try using SQLAlchemy + MySQL (Part 1)
Try using the Twitter API
Try using SQLAlchemy + MySQL (Part 2)
Try using Django's template feature
Try using the PeeringDB 2.0 API
Try using Pelican's draft feature
Try using pytest-Overview and Samples-
Try using folium with anaconda
Try using Janus gateway's Admin API
Try using Spyder included in Anaconda
Try using design patterns (exporter edition)
Try using Pillow on iPython (Part 1)
Try using Pillow on iPython (Part 2)
Try using Pleasant's API (python / FastAPI)
Try using LevelDB in Python (plyvel)
Try using pynag to configure Nagios
Try using PyCharm's remote debugging feature
Try using ArUco on Raspberry Pi
Try using cheap LiDAR (Camsense X1)
Using global variables in python functions
[Sakura rental server] Try using flask.
Try using Pillow on iPython (Part 3)
Reinforcement learning 8 Try using Chainer UI
Try to get statistics using e-Stat