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

如何使用Gramex FormHandler动态(在运行时)创建或更改DB模式

  •  2
  • sandeep  · 技术社区  · 2 年前

    我希望能够(在运行时)使用Gramex的FormHandler microservice在特定事件(例如,单击按钮)上动态创建或更改DB模式。

    3 回复  |  直到 2 年前
        1
  •  2
  •   Niket Nishi    2 年前

    您可以使用FormHandler的queryfunction来完成,它可以根据url中传递的查询参数修改查询。

    有关更多信息,请参阅下面的链接 https://gramener.com/gramex/guide/formhandler/#formhandler-queryfunction

        2
  •  1
  •   S Anand    2 年前

    FormHandler支持 defining columns in the spec .

    例如,此配置创建一个名为 profile 共4列:用户、密码、年龄和id。

    url:
        handler: FormHandler
        kwargs:
          url: 'postgresql://$USER:$PASS@server/db'       # Pick any database
          table: profile              # Pick any table name to create
          id: id                      # The "id" column is primary key
          # Define your table's columns
          columns:
            user: TEXT                # Use any SQL type allowed by DB
            password: VARCHAR(40)     # including customizations
            age:
              type: INTEGER           # You can also specify as a dict
              nullable: true          # Allows NULL values for this field
              default: 0              # that default to zero
            id:
              type: INTEGER           # Define an integer ID column
              primary_key: true       # as a primary key
              autoincrement: true     # that auto-increments
    

    但如果在运行时需要更改,例如当用户单击按钮时,可以使用 FunctionHandler 具有 gramex.data.alter()

    例如,将其添加到 gramex.yaml :

    url:
      alter:
        pattern: /alter
        handler: FunctionHandler
        kwargs:
          # You can decide the columns dynamically here
          function: >
            gramex.data.alter(url, table, columns={
               col: 'TEXT' for col in handler.args.get('col', [])
            })
    

    什么时候 /alter?col=email 调用时,函数会添加 email 列作为文本。

    注意:没有删除列的选项。

        3
  •  0
  •   Gurudev Kumar    2 年前

    你应该试试这个:

    在yaml处理程序中:

    queryfunction: mymodule.sales_query(args)

    在python代码中:

    def sales_query(args):
        cities = args.get('ct', [])
        if len(cities) > 0:
            vals = ', '.join("'%s'" % pymysql.escape_string(v) for v in cities)
            return 'SELECT * FROM sales WHERE city IN (%s)' % vals
        else:
            return 'SELECT * FROM sales'
    

    参考资料来源: https://gramener.com/gramex/guide/formhandler/#formhandler-queryfunction