在一个Azure函数中运行多个Python脚本。

huangapple go评论70阅读模式
英文:

Running multiple python scripts in one Azure Function

问题

按照标题所说,我想要一个Azure函数,用于运行项目中的所有Python脚本。我的理想状态应该类似于这样。

- azure_app
  - azure_function
    - __init__.py(运行代码)
    - function.json(触发器)
    - python_script_one.py
    - python_script_two.py

我有一些运行不同网站爬虫并需要不同处理的Python脚本。然而,它们属于同一个项目,所以在理想情况下,我希望所有单独的Python文件都在一个函数中被调用,以便我不必为每个脚本生成大量不同的函数。我一直在寻找解决方案,所以非常感谢任何建议。

我正在使用定时器作为函数的触发器,代码如下。

def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

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

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

希望这有所帮助。

英文:

As the title says I want to have an Azure function that runs all of the Python scripts in that project. My ideal state would look something like this.

-azure_app
  - azure_function
    - __init__.py (runs code)
    - function.json (trigger)
    - python_script_one.py
    - python_script_two.py

The Python scripts I have are running crawlers for different websites and require different processes. However, they are part of the same project so in an ideal world, I would have all of the individual Python files and have the init file call all of them in one function so that I don't have to generate a multitude of different functions for each script. I've struggled to find a solution to this so any advice is much appreciated.

I am using a timer as the trigger for the function the code is as follows.

def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

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

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

答案1

得分: 1

以下是您要的翻译部分:

p1.py:

print("Hello Rithwik running from Script 1")

p2.py:

print("Running from Script 2")

然后在 __init__.py 中:

import logging
from pkg_resources import run_script
import azure.functions as func
import sys
import os
import importlib.util

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    rs('p1')
    rs('p2')
    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}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

def rs(sn):
    sp = os.path.join(os.path.dirname(__file__), f'{sn}.py')

    s = importlib.util.spec_from_file_location(sn, sp)
    m = importlib.util.module_from_spec(s)
    sys.modules
展开收缩
= m
s.loader.exec_module(m)

输出

英文:

>Running multiple python scripts in one Azure Function

I have reproduced in my environment and got expected results as below:

Firstly, created azure python http trigger function and then created 2 files as below:

p1.py:

print("Hello Rithwik running from Script 1")

在一个Azure函数中运行多个Python脚本。

p2.py:

print("Running from Script 2")

在一个Azure函数中运行多个Python脚本。

Then in __init__.py:

import logging

from pkg_resources import run_script
import azure.functions as func
import sys
import os
import importlib.util


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    rs('p1')
    rs('p2')
    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}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )
def rs(sn):
    sp = os.path.join(os.path.dirname(__file__), f'{sn}.py')

    s = importlib.util.spec_from_file_location(sn, sp)
    m = importlib.util.module_from_spec(s)
    sys.modules
展开收缩
= m s.loader.exec_module(m)

Output:

在一个Azure函数中运行多个Python脚本。

huangapple
  • 本文由 发表于 2023年6月5日 23:14:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76407828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定