|
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +import json |
| 5 | +import azure.functions as func |
| 6 | +from azure.functions.decorators.core import DataType |
| 7 | + |
| 8 | +app = func.FunctionApp() |
| 9 | + |
| 10 | +# Learn more at aka.ms/pythonprogrammingmodel |
| 11 | + |
| 12 | +# The input binding executes the `SELECT * FROM Products WHERE Cost = @Cost` query. |
| 13 | +# The Parameters argument passes the `{cost}` specified in the URL that triggers the function, |
| 14 | +# `getproducts/{cost}`, as the value of the `@Cost` parameter in the query. |
| 15 | +# CommandType is set to `Text`, since the constructor argument of the binding is a raw query. |
| 16 | +@app.function_name(name="GetProducts") |
| 17 | +@app.route(route="getproducts/{cost}") |
| 18 | +@app.generic_input_binding(arg_name="products", type="sql", |
| 19 | + CommandText="SELECT * FROM Products WHERE Cost = @Cost", |
| 20 | + CommandType="Text", |
| 21 | + Parameters="@Cost={cost}", |
| 22 | + ConnectionStringSetting="SqlConnectionString", |
| 23 | + data_type=DataType.STRING) |
| 24 | +def get_products(req: func.HttpRequest, products: func.SqlRowList) -> func.HttpResponse: |
| 25 | + rows = list(map(lambda r: json.loads(r.to_json()), products)) |
| 26 | + |
| 27 | + return func.HttpResponse( |
| 28 | + json.dumps(rows), |
| 29 | + status_code=200, |
| 30 | + mimetype="application/json" |
| 31 | + ) |
| 32 | + |
| 33 | +# The output binding upserts the product, which will insert it into the Products table if |
| 34 | +# the primary key (ProductId) for that item doesn't exist. If it does then update it to |
| 35 | +# have the new name and cost. |
| 36 | +@app.function_name(name="AddProduct") |
| 37 | +@app.route(route="addproduct") |
| 38 | +@app.generic_output_binding(arg_name="product", type="sql", |
| 39 | + CommandText="[dbo].[Products]", |
| 40 | + ConnectionStringSetting="SqlConnectionString", |
| 41 | + data_type=DataType.STRING) |
| 42 | +def add_product(req: func.HttpRequest, product: func.Out[func.SqlRow]) -> func.HttpResponse: |
| 43 | + body = json.loads(req.get_body()) |
| 44 | + row = func.SqlRow.from_dict(body) |
| 45 | + product.set(row) |
| 46 | + |
| 47 | + return func.HttpResponse( |
| 48 | + body=req.get_body(), |
| 49 | + status_code=201, |
| 50 | + mimetype="application/json" |
| 51 | + ) |
0 commit comments