我如何将变量传递给谷歌云函数

2024-04-06

我目前正在创建一个云任务,它将定期将新数据导入到 automl 数据集中。目标是 GCP 云函数 http 目标。因为我不想在云函数中对数据集 ID 进行硬编码。我希望它接受来自 Web UI 的数据集 ID。因此我用这种方式输入flask的代码。

@app.route('/train_model', methods=["POST", "GET"])
def train_model():
    if request.method == 'POST':
        form = request.form
        model = form.get('model_name')
        date = form.get('date')
        dataset_id=form.get('dataset_id')
        datetime_object = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
        timezone = pytz.timezone('Asia/Hong_Kong')
        timezone_date_time_obj = timezone.localize(datetime_object)

        # Create a client.
        client = tasks_v2beta3.CloudTasksClient.from_service_account_json(
            "xxx.json")

        # TODO(developer): Uncomment these lines and replace with your values.
        project = 'xxxx'
        dataset_id = dataset_id
        utf = str(dataset_id, encoding='utf-8')
        location = 'us-west2'
        url='https://us-central1-cloudfunction.cloudfunctions.net/create_csv/' + "?dataset_id=dataset_id"

        queue1 = 'testing-queue'

        parent = client.queue_path(project, location, queue1)
        task = {
            "http_request": {
                'http_method': 'POST',
                'url': url
            }}

        # set schedule time
        timestamp = timestamp_pb2.Timestamp()
        timestamp.FromDatetime(timezone_date_time_obj)
        task['schedule_time'] = timestamp
        response = client.create_task(parent, task)

        print(response)
        return redirect(url_for('dataset'))

云函数代码

import pandas
from google.cloud import datastore
from google.cloud import storage
from google.cloud import automl

project_id=123456995
compute_region='us-central1'


def create_csv(dataset_id):

    datastore_client = datastore.Client() #
    data = datastore_client.query(kind='{}label'.format(dataset_id))
    storage_client = storage.Client()
    metadata = list(data.fetch())
    path = []
    label = []
    for result in metadata:
        path.append(result['Storage_url'])
        label.append(result['label'])
    record = {
        'Path': path,
        'Label': label
    }
    table = pandas.DataFrame(record)
    csv_pandas = table.to_csv('/tmp/label.csv', header=None, index=None) #create csv through query datatore

    # upload to cloud storage bucket

    bucket_name1='testing'
    destination_blob_name='label.csv'

    bucket = storage_client.bucket(bucket_name1)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_filename('/tmp/label.csv')

    object = bucket.get_blob(destination_blob_name)
    bucket = object.bucket
    bucket_name = bucket.name
    url = 'gs://' + bucket_name + '/' + object.name

      #import data to the dataset
    client= automl.AutoMlClient()
    dataset_full_id = client.dataset_path(
        project_id, "us-central1", dataset_id
    )
    # Get the multiple Google Cloud Storage URIs
    input_uris = url.split(",")
    gcs_source = automl.types.GcsSource(input_uris=input_uris)
    input_config = automl.types.InputConfig(gcs_source=gcs_source)
    # Import data from the input URI
    client.import_data(dataset_full_id, input_config)    

但它给了我这个错误。

Traceback (most recent call last):
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 346, in run_http_function
    result = _function_handler.invoke_user_function(flask.request)
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 217, in invoke_user_function
    return call_user_function(request_or_event)
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 210, in call_user_function
    return self._user_function(request_or_event)
  File "/user_code/main.py", line 52, in create_csv
    client.import_data(dataset_full_id, input_config)
  File "/env/local/lib/python3.7/site-packages/google/cloud/automl_v1/gapic/auto_ml_client.py", line 793, in import_data
    request, retry=retry, timeout=timeout, metadata=metadata
  File "/env/local/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
    return wrapped_func(*args, **kwargs)
  File "/env/local/lib/python3.7/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
    on_error=on_error,
  File "/env/local/lib/python3.7/site-packages/google/api_core/retry.py", line 184, in retry_target
    return target()
  File "/env/local/lib/python3.7/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
    return func(*args, **kwargs)
  File "/env/local/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 List of found errors:   1.Field: name; Message: Required field is invalid

为了能够使用来自 App Engine 应用程序的参数调用云函数:

  1. 创建一个云函数允许未经身份验证的函数调用 https://cloud.google.com/functions/docs/securing/managing-access-iam

  2. Enable CORS 请求 https://cloud.google.com/functions/docs/writing/http#functions_http_cors_auth-python

import requests
import json

from flask import escape

def hello_http(request):

    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*'
    }



    request_json = request.get_json(silent=True)
    request_args = request.args

    if request_json and 'dataset_id' in request_json:
        dataset_id = request_json['dataset_id']
    elif request_args and 'dataset_id' in request_args:
        dataset_id = request_args['dataset_id']
    else:
        dataset_id = 'default'

    print('Function got called with dataset id {}'.format(escape(dataset_id)))

    return 'This is you dataset id {}!'.format(escape(dataset_id), 200, headers )
  1. Deploy App Engine 标准环境中的 Python 3 快速入门 https://cloud.google.com/appengine/docs/standard/python3/quickstart
from flask import Flask
import requests
import json



# If `entrypoint` is not defined in app.yaml, App Engine will look for an app
# called `app` in `main.py`.
app = Flask(__name__)


@app.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    response = requests.post('https://us-central1-your-project.cloudfunctions.net/function-2', data=json.dumps({"dataset_id":"m_your_dataset_id"}), headers={'Accept': 'application/json','Content-Type': 'application/json'})
    return  'Response {}'.format(str(response))


4.将所有参数传递给data在我们的例子中,我们通过dataset_id = m_your_dataset_id

5.通过访问调用该函数https://your-project.appspot.com

6.检查日志:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我如何将变量传递给谷歌云函数 的相关文章

随机推荐

  • ControllerPlugin 类中的 ZF2 getServiceLocator

    我正在尝试在插件类中获取服务定位器 实体管理器 我怎样才能得到它 在我的控制器中我得到的是这样的 public function getEntityManager if null this gt em this gt em this gt
  • 我可以在 SQL Server 中选择 0 列吗?

    我希望这个问题比类似的问题好一点创建一个没有列的表 https stackoverflow com questions 2438321 create a table without columns 是的 我问的是一些最让人觉得毫无意义的学术
  • 表不必要的冗余

    我的物品列出如下 当然这只是一个总结 但我正在使用 详细信息 表中显示的方法来表示一种 继承 类型 可以这么说 因为 项目 和 可下载 将是相同的 除了每个都有一些相关的附加字段只对他们而言 我的问题是在这个设计模式中 这种事情在我们的项目
  • 当前不会命中断点。该文档尚未加载任何符号

    我用谷歌搜索了这个特定问题 但似乎找不到可行的解决方案 症状 在 Web 应用程序项目中的 aspx 页面的代码隐藏中添加断点后 该断点在页边空白处显示为一个空心的红色圆圈 圆圈右下角有一个用黄色三角形括起来的感叹号 将鼠标悬停在断点上时
  • 使用自定义对象的 JTable、JComboBox

    您好 如果您将 JComboBox 放入 JTable 中并将 String 数组放入 JComboBox 中 则一切正常 如果您将自己的数据类型放入 JComboBox 则在同一列中选择值会变得很复杂 这是官方示例 http docs o
  • 在单调递增然后递减的序列 cera 中查找一个数

    查找单调增加然后单调减少的序列中的最大值或最小值可以在 O log n 内完成 但是 如果我想检查一个数字是否存在于这样的序列中 这也可以在 O log n 中完成吗 我认为这是不可能的 考虑这个例子 1 4 5 6 7 10 8 3 2
  • 如何创建元组数组?

    我知道要在 C 中创建元组 我们使用以下格式 Tuple
  • Azure SQL 数据库 Bacpac 本地还原

    我使用 Azure 管理控制台中的 导出 选项创建了 Azure SQL 数据库的 BACPAC 备份 将其下载到我的计算机后 我对如何将其恢复到本地 SQL Server 实例有点困惑 我遇到了 DacImportExportCli 工具
  • 在 Visual Studio 中使用 FFmpeg

    我正在尝试在 Visual Studio 2010 的 C 项目中使用 FFmpeg 我想将这些库作为静态链接文件包含在内 简单的程序如libavcodec api example c http cekirdek pardus org tr
  • 寻找Excel自定义函数工具提示

    这个问题已经被asked https stackoverflow com questions 4262421 how to put a tooltip on a user defined function before https stac
  • 关于映射和迭代器的理论澄清

    如果我有一个带有地图作为私有成员的类 例如 class MyClass public MyClass std map
  • 添加样式以回显[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我想为这个 php echo 添加一
  • 如何从 javascript 数组推送 JSON 中的元素

    我想将 javascript 数组值添加到 JSON 值对象中 其他元素也替换了我的元素 如收件人 主题 消息 我得到的 Json 如下 下面是我的代码 var BODY recipients values subject title bo
  • 在 MySQL 中获取下个月的第一个和最后一个日期

    如何在 where 子句中使用下个月的第一天和最后一天 Use SELECT DATE SUB LAST DAY DATE ADD NOW INTERVAL 1 MONTH INTERVAL DAY LAST DAY DATE ADD NO
  • FileOutputstream.close() 并不总是将字节写入文件系统?

    看完之后这个答案 https stackoverflow com questions 7849528 fileoutputstream close is really slow when writing large file 7849941
  • 设置 WebRequest 的正文数据

    我正在 ASP NET 中创建一个 Web 请求 我需要向正文添加一堆数据 我怎么做 var request HttpWebRequest Create targetURL request Method PUT response HttpW
  • GitHub 的 GPG 公钥是什么?

    如果您通过 GitHub 网站进行编辑 或合并拉取请求 则生成的提交将自动使用 GitHub 的 GPG 密钥进行签名 它看起来像这样 我希望拥有完整的公钥 以便我可以将其添加为我的系统上的可信密钥 GitHub 的 GPG 公钥是什么 G
  • 在 Windows 记事本的 Python 中创建 UTF-16 换行符

    在 Ubuntu 中运行的 Python 2 7 中 这段代码 f open testfile txt w f write Line one encode utf 16 f write u r n encode utf 16 f write
  • HTML LocalStorage 中的数据在其他窗口/选项卡中可用所需的时间

    我有一个使用 HTML LocalStorage 的网页 同时打开此页面的多个选项卡 窗口是很常见的 由于这些都使用相同的 LocalStorage 并且 LocalStorage 不提供事务或类似功能 因此我想实现某种形式的互斥 以防止不
  • 我如何将变量传递给谷歌云函数

    我目前正在创建一个云任务 它将定期将新数据导入到 automl 数据集中 目标是 GCP 云函数 http 目标 因为我不想在云函数中对数据集 ID 进行硬编码 我希望它接受来自 Web UI 的数据集 ID 因此我用这种方式输入flask