将 Python 脚本作为 Azure 函数运行时出现问题

问题描述 投票:0回答:1

我的 Azure 函数中有以下代码片段

import logging
import azure.functions as func
import email
import smtplib
import datetime
import pandas as pd
import io
import requests
import os
#import resend
import smtplib
from email.mime.text import MIMEText

app = func.FunctionApp()

@app.schedule(schedule="0 */5 * * * *", arg_name="myTimer", run_on_startup=True, use_monitor=True) 
def NSEData(myTimer: func.TimerRequest) -> None:
    if myTimer.past_due:
        logging.info('The timer is past due!')
        
  
    logging.info('Python timer trigger function executed.')

调试期间,流程在

之后返回
def NSEData(myTimer: func.TimerRequest) -> None:

我无法理解为什么会这样。如果重要的话,我使用 VS Code 作为 IDE。

编辑:

import logging
import azure.functions as func
import email
import datetime
import pandas as pd
import io
import requests
import os
#import resend
import smtplib
from email.mime.text import MIMEText

app = func.FunctionApp()

@app.schedule(schedule="0 */5 * * * *", arg_name="myTimer", run_on_startup=False, use_monitor=False) 
def NSEData(myTimer: func.TimerRequest) -> None:
    logging.info('Python timer trigger function started.')
    if myTimer.past_due:
        logging.info('The timer is past due!')
        base_url = 'https://www.nseindia.com'
        session = requests.Session()
        headers = {
                    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
                         'like Gecko) '
                         'Chrome/80.0.3987.149 Safari/537.36',
                    'accept-language': 'en,gu;q=0.9,hi;q=0.8',
                    'accept-encoding': 'gzip, deflate, br'}

        r = session.get(base_url, headers=headers, timeout=5)
        cookies = dict(r.cookies)

        today = datetime.date.today().strftime('%d%m%Y')
        #response = session.get("https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_"+today+".csv", timeout=15, headers=headers, cookies=cookies)
        response = session.get("https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_22072024.csv", timeout=15, headers=headers, cookies=cookies)
        content = response.content
        todayData=pd.read_csv(io.StringIO(content.decode('utf-8')))

        todayData['max_change_inday'] = todayData[' HIGH_PRICE']/todayData[' PREV_CLOSE']
        new_todayData = todayData[todayData[" SERIES"].str.contains('EQ')]
        todayData = new_todayData.nlargest(10,'max_change_inday')
        new_todayData = todayData[['SYMBOL', ' CLOSE_PRICE', 'max_change_inday']]
        print(new_todayData)




        referenceDate = datetime.date.today() - datetime.timedelta(days=7)
        referenceDate = referenceDate.strftime('%d%m%Y')
        response = session.get("https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_"+referenceDate+".csv", timeout=5, headers=headers, cookies=cookies)
        content = response.content
        referenceData = pd.read_csv(io.StringIO(content.decode('utf-8')))
        new_referenceData = referenceData[referenceData[" SERIES"].str.contains('EQ')]


        finalDS = pd.merge(new_referenceData, new_todayData, on='SYMBOL',how='inner', suffixes = ("_"+referenceDate, "_"+today))
        finalDS['max_change_duration'] = finalDS[' HIGH_PRICE']/finalDS[' CLOSE_PRICE_'+today]
        finalData = finalDS.nlargest(10,'max_change_duration')

        html = """\<html><head></head><body>{0}</body></html>""".format(finalData.to_html())
        headers = {"Content-Type": "multipart/form-data"}


        def send_simple_message():
          return requests.post(
            "https://api.mailgun.net/v3/sandbox553c29c95ef8420482ebc120d6e901b6.mailgun.org/messages",
            auth=("api", "6ef6a1474287175cb0fec546f983979c-0f1db83d-eca69c25"),
            data={"from": "Excited User <[email protected]>",
                  "headers": headers,
                  "to": ["[email protected]"],
                  "subject": "Potential multibaggers " + datetime.date.today().strftime('%d %m %Y'),
                  "html": html})
       
        send_simple_message()
  
    logging.info('Python timer trigger function executed.')

编辑2:

import logging
import azure.functions as func
import email
import datetime
import pandas as pd
import io
import requests
import os
#import resend
import smtplib
from email.mime.text import MIMEText

app = func.FunctionApp()
@app.function_name(name="mytimer")
@app.schedule(schedule="0 */5 * * * *", arg_name="myTimer", run_on_startup=True, use_monitor=False) 
def NSEData(myTimer: func.TimerRequest) -> None:
    base_url = 'https://www.nseindia.com'
    session = requests.Session()
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
                                                 'like Gecko) '
                                                 'Chrome/80.0.3987.149 Safari/537.36',
                                        'accept-language': 'en,gu;q=0.9,hi;q=0.8',
                                        'accept-encoding': 'gzip, deflate, br'}
    r = session.get(base_url, headers=headers, timeout=5)
    cookies = dict(r.cookies)
    today = datetime.date.today().strftime('%d%m%Y')
    #response = session.get("https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_"+today+".csv", timeout=15, headers=headers, cookies=cookies)
    response = session.get("https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_22072024.csv", timeout=15, headers=headers, cookies=cookies)
    content = response.content
    todayData=pd.read_csv(io.StringIO(content.decode('utf-8')))
    todayData['max_change_inday'] = todayData[' HIGH_PRICE']/todayData[' PREV_CLOSE']
    new_todayData = todayData[todayData[" SERIES"].str.contains('EQ')]
    todayData = new_todayData.nlargest(10,'max_change_inday')
    new_todayData = todayData[['SYMBOL', ' CLOSE_PRICE', 'max_change_inday']]
    print(new_todayData)




    referenceDate = datetime.date.today() - datetime.timedelta(days=7)
    referenceDate = referenceDate.strftime('%d%m%Y')
    response = session.get("https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_"+referenceDate+".csv", timeout=5, headers=headers, cookies=cookies)
    content = response.content
    referenceData = pd.read_csv(io.StringIO(content.decode('utf-8')))
    new_referenceData = referenceData[referenceData[" SERIES"].str.contains('EQ')]


    finalDS = pd.merge(new_referenceData, new_todayData, on='SYMBOL',how='inner', suffixes = ("_"+referenceDate, "_"+today))
    finalDS['max_change_duration'] = finalDS[' HIGH_PRICE']/finalDS[' CLOSE_PRICE_'+today]
    finalData = finalDS.nlargest(10,'max_change_duration')

    html = """<html><head></head><body>{0}</body></html>""".format(finalData.to_html())
    headers = {"Content-Type": "multipart/form-data"}


    def send_simple_message():
        return requests.post(
            "https://api.mailgun.net/v3/sandbox553c29c95ef8420482ebc120d6e901b6.mailgun.org/messages",
            auth=("api", "6ef6a1474287175cb0fec546f983979c-0f1db83d-eca69c25"),
            data={"from": "Excited User <[email protected]>",
            "headers": headers,
            "to": ["[email protected]"],
            "subject": "Potential multibaggers " + datetime.date.today().strftime('%d %m %Y'),
            "html": html})
             
    send_simple_message()
python azure-functions
1个回答
0
投票

您的代码的问题是您正在块中编写代码,该代码仅在计时器触发器

mytimer
超过时间时才起作用。

您需要从定时器触发函数中删除以下两行代码:

if myTimer.past_due:
        logging.info('The timer is past due!')

检查缩进如下:

enter image description here

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.