Hi,
I follow the above procedure with minor differences (I created a timer trigged function instead of a https response). When I run the code from VS code it works perfectly. But when I try to run it locally (F5) I receive messages that the function was sucessfully executed but the code is not actually perfomed. Don't need to say that it didn't work either we deployed. Is there any thing I am missing?
import logging
import azure.functions as func
import pyodbc
import os
import struct
def main():
logging.info("teste dummy SQL server access from azure web function")
#sql connection
con_str_base = "Driver={0};Server=tcp:{1};Database={2}"
driver = '{ODBC Driver 17 for SQL Server}'
server = '...'
db_name = '...'
db_token = ''
connection_string = con_str_base.format(driver,server,db_name)
#connect to database
if os.getenv("MSI_SECRET"):
cnx = pyodbc.connect(connection_string+';Authentication=ActiveDirectoryMsi')
#logging.info("connected")
else:
SQL_COPT_SS_ACCESS_TOKEN = 1256
exptoken = b''
for i in bytes(db_token, "UTF-8"):
exptoken += bytes({i})
exptoken += bytes(1)
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken
cnx = pyodbc.connect(connection_string, attrs_before = { SQL_COPT_SS_ACCESS_TOKEN:tokenstruct })
cur = cnx.cursor()
#load items
cur.execute("SELECT max(counter) from amp_homolog.dummy1")
c = cur.fetchone()[0]
cur.execute('insert into amp_homolog.dummy1(counter) values({})'.format(c+1))
cnx.commit()
if __name__ == '__main__':
main()
UPDATE 1
I found my problem. It is that kind of thing so simple that sometimes the tutorials forget to mention. I was no saving my code in the correct file! For those how, like me, are starting to work with azure web function, the code to run need to be save on the file defined in the function.json (default is __init__.py)
UPDATE 2
After I manged to run the function locally I tried to deploy it but it is not working. When I try to connect to the SQL DB I receive the following error:
('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user '<token-identified principal>'. (18456) (SQLDriverConnect)")
I tried to deploy the same code to another function and this time it worked. The only difference between the first and the second is that the first web function is a consumption serveless plan while the second one has a Function Premium plan. Beside that all configurations are the same.
Any idea why it don't work for the first case?