Azure Functions with Python Flask

Viewed 18

I am trying to use Azure Functions with Python code to connect to a sql server (Not Azure SQL database) and fetch the data.

In my previous python code, I used flask to fetch data with different url input

import pyodbc
import sys
import logging
import datetime

from waitress import serve
from flask import Flask, g
from flask_cors import CORS, cross_origin
from datetime import datetime

#creating instance of the class
app = Flask(__name__)
app.secret_key = 'xxx'

server = 'xxx'
database = 'xxx'
username = 'xxx'
password = 'xxx'

app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/yrate":{"origins":"*"}, r"/frate":{"origins":"*"}})
logger = logging.getLogger('yrate')    

def error_handling():
    return 'Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)


def get_db():
    if not hasattr(g, 'db'):
        g.db = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
    return g.db


@app.route('/')
def root():
    return 'root'


@app.route("/datatable", methods=['GET'])
def get_table():
    out = ''
    query = ''
    try:
        print("")
        query = 'SELECT * from dbo.LCurve'

        db = get_db()
        cursor = db.execute(query)
        rows = cursor.fetchall()
        columns = cursor.description
        # logger.info(query)

        for row in rows:
            out = out + str(row) + "\n"

        out = str(columns) + " " + out
    except:
        out = "404 : table not found"

    return out


@app.route("/frate/<vDate>/<fDate>/<tenor>", methods=['GET'])
def get_f_rate(vDate, fDate, tenor):
    try:
        query = ''

        formatStr = '%m-%d-%Y'
        dt = datetime.datetime.strptime(fDate, formatStr)
        resetYear = dt.year
        resetMonth = dt.month

        query = 'SELECT rate FROM dbo.LCurve where [valuation date]=convert(DATETIME, \'{vdate}\', 101) AND DATEPART(year, [reset date]) = {resetYear} AND DATEPART(month, [reset date]) = {resetMonth} AND [tenor]=\'{tenor}\';'.format(
            vdate=vdate, resetYear=resetYear, resetMonth=resetMonth, tenor=tenor)

        db = get_db()
        cursor = db.execute(query)
        row = cursor.fetchone()
        #logger.info(query)

        if row is None:
            rate = 'No Rate Found!'
        else:
            rate = str(row[0])

        return rate
    except:
        logger.error(error_handling())
        return '!ERROR'

if __name__ == '__main__':
    app.run()

Since this method can provide us the flexibility with inputting different url/para to fetch data.

I would like to put this python code to Azure Functions, but not sure should we use "Flask" in Azure Functions which is a serverless service?

If not, is there any other methods to make the para can be as flexible as Flask?

If yes, I can use Flask in Azure Functions without other issue/cost, is my code correct? *I basically move all the code (without app.run()) to the init.py file, and add the following code the the end.

def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    return func.WsgiMiddleware(app).handle(req, context)

I also modified host.json and function.json files refer to : How to route all requests to a singe azure function and maintain the route

I am very new to this area...
I would be highly appreciated if there is any suggestions!

0 Answers
Related