代码之家  ›  专栏  ›  技术社区  ›  Alessio

Azure函数-写入表

  •  0
  • Alessio  · 技术社区  · 2 年前

    我在写入Azure SQL数据库的表时遇到问题,我已按照文档中指示的步骤进行了操作:

    1. 在创建了函数应用程序资源之后,我使用Http模板和“v1编程模型”创建了一个azure函数。

      Language used: python 3.11
      Runtime version: 4.34.1.1
      
    2. 我有一个Azure SQL数据库,在其中我使用以下命令创建了一个表:

      CREATE TABLE dbo.ToDo 
      (
          [Id] UNIQUEIDENTIFIER PRIMARY KEY,
          [order] INT NULL,
          [title] NVARCHAR(200) NOT NULL,
          [url] NVARCHAR(200) NOT NULL,
          [completed] BIT NOT NULL
      );
      
    3. 在数据库的网络选项卡中,我选中了“允许Azure服务和资源访问此服务器”选项。

    4. 在函数应用程序的“环境变量”选项卡中,我创建了 SqlConnectionString 变量,并相应地替换SQL身份验证参数。

    5. 我已经在中设置了绑定 function.json

      {
          "authLevel": "function"
          "type": "httpTrigger",
          "direction": "in",
          "name": "req",
          "methods": [
              "post"
          ]
      },
      {
          "type": "http",
          "direction": "out",
          "name": "$return"
      },
      {
          "name": "todoItems",
          "type": "sql",
          "direction": "out",
          "commandText": "dbo.ToDo",
          "connectionStringSetting": "SqlConnectionString"
      }
      
    6. init.py文件的内容是:

    import logging
    import azure.functions as func
    
    
    def main(req: func.HttpRequest, todoItems: func.Out[func.SqlRow]) -> func.HttpResponse:
        logging.info('Python HTTP trigger and SQL output binding function processed a request.')
    
        try:
            req_body = req.get_json()
            rows = func.SqlRowList(map(lambda r: func.SqlRow.from_dict(r), req_body))
        except ValueError:
            pass
    
        if req_body:
            todoItems.set(rows)
            return func.HttpResponse(
                todoItems.to_json(),
                status_code=201,
                mimetype="application/json"
            )
        else:
            return func.HttpResponse(
                "Error accessing request body",
                status_code=400
            )
    
    1. 当我尝试从门户测试在正文中传递此JSON的函数时:

      {
          "order": 1,
          "title": "test",
          "url": "testUrl",
          "completed": 1
      }
      

    我有个错误

    500内部服务器错误

    有人能帮我弄清楚为什么会出现这个错误吗?

    我希望函数返回状态200和插入到表中的记录。

    0 回复  |  直到 2 年前
        1
  •  0
  •   Julian Hüppauff    2 年前

    第一个“允许Azure服务和资源访问此服务器”不包括Azure功能。要么您需要允许所有流量,将函数和DB注入VNET,要么将函数的出口IP添加到数据库。

    我还建议向您的应用程序添加应用程序见解或更多日志记录