예제 #1
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request for creating a new location.')

    client = pymongo.MongoClient("mongodb+srv://arnav:[email protected]/myFirstDatabase?retryWrites=true&w=majority")

    mydb = client["db"]
    entry = mydb["locations"]

    
    nameofProject = req.params.get('Name of Project')
    pictureOfProject = req.params.get('Picture of Project')
    facility= req.params.get('Facility of Project')
    exactlocation= req.params.get('Exact Location of Project')
    longitude= req.params.get('Longitude')
    latitude= req.params.get('Latitude')
    when=req.params.get('When')
    program=req.params.get('Program (Urban Agriculture, Artistry and Craftmanship, Tourism and Hospitality)')
    beneficiaries=req.params.get("Beneficiaries (children, youth at risk, women, PWD, eldery)")
    support=req.params.get("Support Provided by MG to Beneficiaries")
    impact=req.params.get("Impact on Beneficiaries")
    number=req.params.get("Number of Beneficiaries Directly Impacted")
    activities=req.params.get("Activities of Beneficiaries")
    indirect=req.params.get("Indirect Impact on Communities")
    numberofIndirect=req.params.get("Number of Community Members Indirectly Impacted")


    if not nameofProject:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            nameofProject = req_body.get('Name of Project')
            pictureOfProject = req.params.get('Name of Project')
            facility= req_body.get('Facility of Project')
            exactlocation= req_body.get('Exact Location of Project')
            longitude= req_body.get('Longitude')
            latitude= req_body.get('Latitude')
            when=req_body.get('When')
            program=req_body.get('Program (Urban Agriculture, Artistry and Craftmanship, Tourism and Hospitality)')
            beneficiaries=req_body.get("Beneficiaries (children, youth at risk, women, PWD, eldery)")
            support=req_body.get("Support Provided by MG to Beneficiaries")
            impact=req_body.get("Impact on Beneficiaries")
            number=req_body.get("Number of Beneficiaries Directly Impacted")
            activities=req_body.get("Activities of Beneficiaries")
            indirect=req_body.get("Indirect Impact on Communities")
            numberofIndirect=req_body.get("Number of Community Members Indirectly Impacted")

    if nameofProject:
        location ={
        "Name of Project": nameofProject,
        "Picture of Project": pictureOfProject,
        "Facility of Project": facility,
        "Exact Location of Project": exactlocation,
        "Longitude ": longitude,
        "Latitude": latitude,
        "When": when,
        "Program (Urban Agriculture, Artistry and Craftmanship, Tourism and Hospitality)": program,
        "Beneficiaries (children, youth at risk, women, PWD, eldery)": beneficiaries,
        "Support Provided by MG to Beneficiaries": support,
        "Impact on Beneficiaries": impact,
        "Number of Beneficiaries Directly Impacted": number,
        "Activities of Beneficiaries": activities,
        "Indirect Impact on Communities": indirect,
        "Number of Community Members Indirectly Impacted": numberofIndirect
        }
        
        return func.HttpResponse(
             str(entry.insert_one(location).inserted_id),
             status_code=200
        )
    else:
        return func.HttpResponse(
             "Parameters were not given",
             status_code=200
        )
예제 #2
0
def main(req: func.HttpRequest) -> func.HttpResponse:

    # Log to Azure function apps online
    logging.info('Python HTTP trigger function processed a request.')

    # Try retrieve params
    req_body = req.get_json()
    account_id = req_body.get('account_id')
    language = req_body.get('language')

    def query_database(query):
        logic_app_url = "https://prod-20.uksouth.logic.azure.com:443/workflows/c1fa3f309b684ba8aee273b076ee297e/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=xYEHzRLr2Frof9x9_tJYnif7IRWkdfxGC5Ys4Z3Jkm4"
        body = {"intent": "query", "params": [query]}
        response = requests.post(url=logic_app_url, json=body)
        return json.loads(response.content)

    data = query_database(f"SELECT TOP 3 * FROM [dbo].[Card]")

    def display_cards(data, language):
        adaptive = AdaptiveCard()
        cards = data["ResultSets"]["Table1"]

        for card in cards:
            font_color = "default"
            backgroundImage_url = "https://i.dlpng.com/static/png/6774669_preview.png" if card[
                "Status"] == "Frozen" else "https://i.pinimg.com/originals/f5/05/24/f50524ee5f161f437400aaf215c9e12f.jpg"

            adaptive.add([
                "items----",
                Container(backgroundImage=backgroundImage_url,
                          spacing="large",
                          separator="true"),
                ColumnSet(),
                Column(),
                TextBlock(text=card["card_id"],
                          color=font_color,
                          dont_translate=True),
                TextBlock(text=card["type"],
                          size="ExtraLarge",
                          weight="Bolder",
                          color=font_color,
                          dont_translate=True),
                TextBlock(text=f"Status: {card['Status']}",
                          size="medium",
                          weight="Bolder",
                          color=font_color),
                TextBlock(
                    text=
                    f"Expires {card['month']}-{card['day']}-{card['year']}",
                    color=font_color),
                TextBlock(text=f"PIN: {card['Pin_Code']}",
                          color=font_color,
                          dont_translate=True), "<",
                Column(),
                Image(
                    url=
                    "https://brokerchooser.com/uploads/images/digital-banks/n26-review-bank-card.png"
                ), "<", "<",
                ActionSet(), "actions ----",
                ActionShowCard(title="Manage Card"),
                ActionSubmit(title="Reset PIN",
                             data={
                                 "card": f"{card['card_id']}",
                                 "action": "PIN"
                             },
                             style="positive"),
                ActionSubmit(
                    title="Defrost Card"
                    if card["Status"] == "Frozen" else "Freeze Card",
                    data={
                        "card":
                        f"{card['card_id']}",
                        "action":
                        f"{'unfreeze' if card['Status']=='Frozen' else 'freeze'}"
                    },
                    style="positive"), "^"
            ])

        return adaptive.to_json(
            translator_to_lang=language,
            translator_key="e8662f21ef0646a8abfab4f692e441ab")

    result = display_cards(data, language)
    return func.HttpResponse(body=result, status_code=200)
예제 #3
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    requestJson = json.loads(req.get_json())
    telitApiEndpoint = "https://api.devicewise.com/api"
    triggerNameRegexPattern = "^TEMEDA_.*_FORWARD$"
    telitUsername = requestJson["telitUsername"]
    telitPassword = requestJson["telitPassword"]
    try:
        if requestJson.has_key("actions"):
            if requestJson.has_key("propertyKey"):
                propertyKey = requestJson["propertyKey"]
                if type(propertyKey) == type('a'):

                    authObject = {}
                    authObject.update({
                        "auth": {
                            "command": "api.authenticate",
                            "params": {
                                "username": telitUsername,
                                "password": telitPassword
                            }
                        }
                    })

                    authJson = json.dumps(authObject)
                    authResponse = requests.post(url=telitApiEndpoint,
                                                 data=authJson)

                    if authResponse.ok:

                        lookupObject = {}
                        lookupObject.update({
                            "auth": {
                                "sessionId":
                                authResponse.json()["auth"]["params"]
                                ["sessionId"]
                            }
                        })
                        lookupObject.update({
                            "cmd": {
                                "command": "trigger.find",
                                "params": {
                                    "name": f"TEMEDA_{propertyKey}_FORWARD"
                                }
                            }
                        })

                        lookupJson = json.dumps(lookupObject)
                        lookupResponse = requests.post(url=telitApiEndpoint,
                                                       data=lookupJson)

                        if lookupResponse.ok:

                            updateObject = {}
                            updateObject.update({
                                "auth": {
                                    "sessionId":
                                    authResponse.json()["auth"]["params"]
                                    ["sessionId"]
                                }
                            })
                            updateObject.update({
                                "cmd": {
                                    "command": "trigger.update",
                                    "params": {
                                        "id":
                                        lookupResponse.json()["cmd"]["params"]
                                        ["id"],
                                        "actions":
                                        requestJson["actions"]
                                    }
                                }
                            })

                            updateJson = json.dumps(updateObject)
                            updateResponse = requests.post(
                                url=telitApiEndpoint, data=updateJson)

                            if updateResponse.ok:
                                return func.HttpResponse(
                                    body=
                                    f"Telit trigger TEMEDA_{propertyKey}_FORWARD updated successfuly. (id={lookupResponse.json()['cmd']['params']['id']})",
                                    status_code=200)

                            else:
                                return func.HttpResponse(
                                    body=f"{json.dumps(updateResponse.json())}",
                                    status_code=400)

                        else:
                            return func.HttpResponse(
                                body=f"{json.dumps(updateResponse.json())}",
                                status_code=400)

                    else:
                        return func.HttpResponse(
                            body=f"{json.dumps(updateResponse.json())}",
                            status_code=401)

                else:
                    return func.HttpResponse(
                        body="Property key must be a valid string.",
                        status_code=400)

            else:
                authObject = {}
                authObject.update({
                    "auth": {
                        "command": "api.authenticate",
                        "params": {
                            "username": telitUsername,
                            "password": telitPassword
                        }
                    }
                })

                authJson = json.dumps(authObject)
                authResponse = requests.post(url=telitApiEndpoint,
                                             data=authJson)

                if authResponse.ok:
                    lookupObject = {}
                    lookupObject.update({
                        "auth": {
                            "sessionId":
                            authResponse.json()["auth"]["params"]["sessionId"]
                        }
                    })
                    lookupObject.update({"cmd": {"command": "trigger.list"}})

                    lookupJson = json.dumps(lookupObject)
                    lookupResponse = requests.post(url=telitApiEndpoint,
                                                   data=lookupJson)

                    if lookupResponse.ok:
                        responseBody = ""
                        for trigger in lookupResponse.json(
                        )["cmd"]["params"]["result"]:
                            if re.match(pattern=triggerNameRegexPattern,
                                        string=trigger["name"]) != None:
                                updateObject = {}
                                updateObject.update({
                                    "auth": {
                                        "sessionId":
                                        authResponse.json()["auth"]["params"]
                                        ["sessionId"]
                                    }
                                })
                                updateObject.update({
                                    "cmd": {
                                        "command": "trigger.update",
                                        "params": {
                                            "id": trigger["id"],
                                            "actions": requestJson["actions"]
                                        }
                                    }
                                })

                                updateJson = json.dumps(updateObject)
                                updateResponse = requests.post(
                                    url=telitApiEndpoint, data=updateJson)

                                if updateResponse.ok:
                                    responseBody += f"Telit trigger {trigger['name']} updated successfuly. (id={trigger['id']})\n"

                                else:
                                    return func.HttpResponse(
                                        body=
                                        f"{json.dumps(updateResponse.json())}",
                                        status_code=400)

                        return func.HttpResponse(body=responseBody,
                                                 status_code=200)

                    else:
                        return func.HttpResponse(
                            body=f"{json.dumps(updateResponse.json())}",
                            status_code=400)

                else:
                    return func.HttpResponse(
                        body=f"{json.dumps(updateResponse.json())}",
                        status_code=401)
    except ValueError as exception:
        return func.HttpResponse(body=f"{exception}", status_code=500)
예제 #4
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Azure cloud bot function processed a request.')
    #Basic Auth Support
    if os.getenv('BASIC_AUTH_ENABLED') and os.getenv(
            'BASIC_AUTH_ENABLED') == "1":
        basic_auth_username = os.getenv('BASIC_AUTH_USERNAME')
        basic_auth_password = os.getenv('BASIC_AUTH_PASSWORD')
        # Make creds to bytes
        if "authorization" not in dict(req.headers).keys():
            logging.info(
                "Request missing authorization header. Returning 401 Unauthorized."
            )
            return func.HttpResponse(f'Unauthorized', status_code=401)

        # Make creds to bytes
        string_requester_credentials = str.split(
            req.headers['Authorization'])[1]
        logging.debug(string_requester_credentials)
        byte_requester_credentials = base64.b64decode(
            string_requester_credentials.encode('ascii'), validate=True)
        byte_stored_credentials = (basic_auth_username + ":" +
                                   basic_auth_password).encode('ascii')

        #Make bytes to hashes
        stored_credentials = hashlib.sha256()
        stored_credentials.update(byte_stored_credentials)
        stored_credentials = stored_credentials.digest()

        requester_credentials = hashlib.sha256()
        requester_credentials.update(byte_requester_credentials)
        requester_credentials = requester_credentials.digest()

        #Compare hashes
        if hmac.compare_digest(requester_credentials, stored_credentials):
            logging.info("Request is authorized.")
        else:
            return func.HttpResponse(f'Unauthorized', status_code=401)

    try:
        source_message = req.get_json()
    except Exception as e:
        logging.info('Bad request: ' + str(e))
        return func.HttpResponse(f'Azure cloud bot had an error',
                                 status_code=400)

    start_time = time.time()
    logging.info(f'{__file__} - source message : {source_message}')
    output_message = {}
    if source_message:
        logging.info(f'source message : {source_message}')
        output_message['Account id'] = source_message['account'].get(
            'id', 'N.A')
        output_message['Finding key'] = source_message.get('findingKey', 'N.A')
        try:
            export_results = handle_event(source_message, output_message)
        except Exception as e:
            export_results = True
            logging.info(f'{__file__} - Handle event failed ' + str(e))
            output_message['Handle event failed'] = str(e)
        if export_results:
            if os.getenv('OUTPUT_EMAIL'):
                sendEvent(output_message)
        else:
            logging.info(
                f'''{__file__} - Output didn't sent : {output_message}''')
        is_send_logs = os.getenv('SEND_LOGS', False)
        logging.info(f'{__file__} - SEND_LOGS set to {str(is_send_logs)}')
        if is_send_logs:
            send_logs(output_message, start_time,
                      source_message.get('account').get('vendor'))
    if output_message:
        return func.HttpResponse(f'{output_message}')
    else:
        return func.HttpResponse(
            f'Azure cloud bot had an error - {output_message}',
            status_code=400)
예제 #5
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    tempPath = "/tmp/"
    algorithm = "hirschberg"
    output_filename = "hirschberg-"
    event = req.get_json()
    required_params = [
        "s1", "s2", "t1", "t2", "service", "concurrence", "repetition",
        "execid", "container", "storage_account_string_connection"
    ]
    errors = []
    for required_param in required_params:
        if not required_param in event:
            errors.append(required_param + " is missing")
    if (len(errors) > 0):
        return func.HttpResponse(json.dumps(errors), status_code=500)
    else:
        connect_str = event["storageConnection"]
        try:
            blob_service_client = BlobServiceClient.from_connection_string(
                connect_str)
        except:
            return func.HttpResponse(json.dumps({
                "error":
                "Failed connecting to Blob Storage - Check your connection string"
            }),
                                     status_code=500)
            _
        _s1 = event["s1"]
        _s2 = event["s2"]
        _t1 = event["t1"]
        _t2 = event["t2"]
        _service = event["service"]
        _concurrence = str(event["concurrence"])
        _repetition = str(event["repetition"])
        id = event["execid"]
        container_name = event["container"]
        s1 = list(_s1)
        s2 = list(_s2)
        started_at = datetime.datetime.now()

        blob = blob_service_client.get_container_client(container_name)
        if not blob.exists():
            blob_service_client.create_container(container_name)

        result = {
            "id": id,
            "service": _service,
            "started_at": str(started_at),
            "s1": {
                "content": _s1,
                "title": _t1,
                "length": len(s1)
            },
            "s2": {
                "content": _s2,
                "title": _t2,
                "length": len(s2)
            },
            "algorithm": algorithm
        }

        local_id = "%.20f" % time.time()
        _output_path = _service + "/repetition_" + _repetition + "/concurrence_" + _concurrence + "/"
        _output_filename = output_filename + str(id) + "_" + str(
            local_id) + ".json"

        f = open(tempPath + _output_filename, "w+")
        f.write(json.dumps(result))
        f.close()

        upload_file_path = os.path.join(tempPath, _output_filename)

        blob_client = blob_service_client.get_blob_client(
            container=container_name, blob=_output_path + _output_filename)
        with open(upload_file_path, "rb") as data:
            blob_client.upload_blob(data)

        h = Hirschberg()
        a, b = h.align(s1, s2)
        score = h.score(a, b)

        align_s1 = a
        align_s2 = b
        finished_at = datetime.datetime.now()
        duration = str(finished_at - started_at)

        result = {
            "id": id,
            "service": _service,
            "started_at": str(started_at),
            "finished_at": str(finished_at),
            "s1": {
                "content": _s1,
                "title": _t1,
                "length": len(s1),
                "align": align_s1
            },
            "s2": {
                "content": _s2,
                "title": _t2,
                "length": len(s2),
                "align": align_s2
            },
            "duration": duration,
            "score": score,
            "algorithm": algorithm
        }

        f = open(tempPath + _output_filename, "w+")
        f.write(json.dumps(result))
        f.close()

        blob_client = blob_service_client.get_blob_client(
            container=container_name, blob=_output_path + _output_filename)
        with open(upload_file_path, "rb") as data:
            blob_client.upload_blob(data, overwrite=True)

        return func.HttpResponse(json.dumps({"result": result}),
                                 status_code=200)
예제 #6
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    
    # Log to Azure function apps online
    logging.info('Python HTTP trigger function processed a request.')

    # Retrieve relevant fields
    req_body = req.get_json()
    account_id = req_body.get('account_id')
    dialog_name = req_body.get('dialog_name')
    dialog_unique_id = req_body.get('dialog_unique_id')
    dialog_start_or_end = req_body.get('dialog_start_or_end')
    activity = req_body.get('activity')
    
    # Deserialize activity json
    activity_dict = json.loads(activity)

    def query_database(query):
        logic_app_url = "https://prod-20.uksouth.logic.azure.com:443/workflows/c1fa3f309b684ba8aee273b076ee297e/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=xYEHzRLr2Frof9x9_tJYnif7IRWkdfxGC5Ys4Z3Jkm4"
        body = {"intent": "query", "params": [query]}
        response = requests.post(url=logic_app_url, json=body)
        return json.loads(response.content)

    def preprocess_insert_data(account_id, dialog_name, dialog_unique_id, dialog_start_or_end, activity_dict):      
        # Initialize blank output_dict
        output = dict()
        
        # Fill in fields from inputs
        output['account_id'] = account_id
        output['dialog_name'] = dialog_name
        output['dialog_unique_id'] = f"d-{dialog_unique_id}"
        
        # Timestamp formatting - remove the +XX:XX UTC offset bit
        output['dialog_start_time'] = activity_dict.get('timestamp').split('+')[0]
        output['dialog_end_time'] = None

        # Try get user IDs from both from and to portions
        from_dict = activity_dict.get('from')
        to_dict = activity_dict.get('recipient')
        user_id = ''
        if from_dict.get('role') == 'user':
            user_id = from_dict.get('id')
        if to_dict.get('role') == 'user':
            user_id = to_dict.get('id')
            
        # Add user ID to output dict
        output['user_id'] = user_id
        
        # Error handle conversation dict
        conversation_dict = activity_dict.get('conversation')
        if conversation_dict:
            output['conversation_id'] = conversation_dict.get('id')
        
        # Error handle channel dict
        channel_dict = activity_dict.get('channelData')
        if channel_dict:
            output['channel_client_activity_id'] = channel_dict.get('clientActivityID')
            
        return output

    def construct_insert_query(preprocessed_data):
        col_names = [k for k in preprocessed_data.keys()]
        value_names = [f"'{v}'"  if v else 'NULL' for v in preprocessed_data.values()]
        return f"INSERT INTO [dbo].[DialogLog] ({', '.join(col_names)}) VALUES ({', '.join(value_names)})"

    # Add new entry if its a start log
    if dialog_start_or_end.lower() == 'start':
        # Preprocess data
        preprocessed_data = preprocess_insert_data(account_id, dialog_name, dialog_unique_id, dialog_start_or_end, activity_dict)
        # Construct query from preprocessed data
        insert_query = construct_insert_query(preprocessed_data)
        # Execute query (log data to the Dialog-Log table)
        query_database(insert_query)
        
    # Else we simply update the existing entry's dialog end time
    elif dialog_start_or_end.lower() == 'end':
        dialog_end_time = activity_dict.get('timestamp').split('+')[0]
        update_query = f"UPDATE [dbo].[DialogLog] SET dialog_end_time = '{dialog_end_time}' WHERE dialog_unique_id = 'd-{dialog_unique_id}'"
        query_database(update_query)
    
    return func.HttpResponse(body='logged', status_code=200)
def main(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse:
    api_baseurl = envconfig.req("API_BASEURL")

    # Check if JSON is valid
    try:
        req_json = req.get_json()
    except ValueError:
        return http.invalid_json_response()

    # Validate data
    try:
        req_body = cfg.IngressWhitelistUpdate(**req_json)
    except pydantic.error_wrappers.ValidationError as e:
        return http.validation_error_response(e)

    if len(req_body.ip_whitelist) == 0:
        return func.HttpResponse(
            body=http.response_body(
                success=True,
                msg="No change",
                reason="Provided whitelist was an empty list [].",
            ),
            status_code=200,
            headers=http.response_headers(),
        )

    try:
        # Client for handling state in storage account
        blob_client = st.new_blob_client()

        # Validate client id
        client_id = cfg.Id.from_str(req.route_params.get("client_id"))
        # Get current configuration from state in Azure
        state_in_azure = st.StateInAzure(blob_client)
        state = state_in_azure.get_by_id(client_id)

        # Append all unique ip addresses to the existing whitelist
        for ip in req_body.ip_whitelist:
            if ip not in state.ip_whitelist:
                state.ip_whitelist.append(ip)

        # Create IngressUpdate from new state
        ingress_update = cfg.IngressUpdate(subdomain=state.subdomain,
                                           ip_whitelist=state.ip_whitelist)
        # Update state in Azure and get queue item in return
        queue_item = state_in_azure.upsert(client_id, ingress_update,
                                           datetime.datetime.now())
        msg.set(queue_item.json())
        response = {
            "success": True,
            "msg": "Added to queue.",
            "poll_url": f"{api_baseurl}/v1/{str(client_id)}/status",
            "data": json.loads(state.json()),
        }
        return func.HttpResponse(json.dumps(response),
                                 status_code=202,
                                 headers=http.response_headers())
    except KeyError:
        return http.not_found_response(
            reason=f"Client with id '{client_id}' does not exist")
    except st.UpdateConflictError as e:
        return http.update_conflict_response(e)
예제 #8
0
def main(req: func.HttpRequest) -> func.HttpResponse:

    # Log to Azure function apps online
    logging.info('Python HTTP trigger function processed a request.')

    # Try retrieve account number
    req_body = req.get_json()
    data = req_body.get('data')
    language = req_body.get('language')

    def dialog_to_prompt(dialog):
        dict_ = {
            "ViewTransactions": "View my last transactions",
            "SummariseTransactions": "Breakdown my spending",
            "MostExpensiveTransaction": "Most expensive transaction last week",
            "ReportTransactionFraud": "Report transaction as fraud",
            "MakeTransfer": "Give money to someone",
            "NewTransferee": "Add a new payee",
            "EditTransferee": "Add a new payee",
            "StandingOrder": "Create standing order",
            "ViewBalance": "How much money do I have",
            "ViewLoans": "Show me my loans",
            "LoanDetails": "Show me my mortgage",
            "LoanOverpayment": "Show me my debts",
            "ManageProfile": "View my Profile",
            "NavigationBank": "Nearest banks to me",
            "BookAppointment": "Closest Lingfield branch to me",
            "ManageCards": "Reset my card pin number",
            "CreatePiggyBank": "Create a new piggy bank",
            "SmashPiggyBank": "Manage my piggy banks",
            "AddToPiggyBank": "Add to my piggy banks",
            "MonthlyAllowancePiggyBank":
            "Change my piggy bank monthly allowance",
            "MonthlySpendingBudget": "Put limits on my spending"
        }
        return dict_.get(dialog)

    def translate_list_of_strings(string_list, to_lang):
        base_url = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0"
        translator_key = "e8662f21ef0646a8abfab4f692e441ab"
        headers = {
            "Ocp-Apim-Subscription-Key": translator_key,
            "Content-Type": "application/json; charset=UTF-8",
            "Content-Length": str(len(string_list)),
        }
        # Construct body
        body = [{"Text": text} for text in string_list]
        # Post request, return
        response = requests.post(url=f"{base_url}&to={to_lang}",
                                 headers=headers,
                                 json=body)
        # Extract translations
        translated_output = []
        for response_dict in response.json():
            translations_array = response_dict['translations']
            first_result = translations_array[0]
            translated_text = first_result['text']
            translated_output.append(translated_text)
        return translated_output

    def get_recommended_prompts(data):
        recommender_url = "http://f91719c7-fa9b-4f2c-84b0-b5e8fc7d8302.uksouth.azurecontainer.io/score"
        response = requests.post(url=recommender_url, json={"data": data})
        recommended_dialogs = json.loads(json.loads(
            response.text)).get('result')
        recommended_prompts = [
            dialog_to_prompt(dialog) for dialog in recommended_dialogs
        ]
        translated_prompts = translate_list_of_strings(recommended_prompts,
                                                       to_lang=language)
        return translated_prompts

    recommended_prompts = get_recommended_prompts(data)
    result = json.dumps({"recommended_prompts": recommended_prompts})
    return func.HttpResponse(body=result, status_code=200)
예제 #9
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    '''
    Purpose:
        Given a free-form address, passes it to Azure Maps
        then returns lat and lon
    
    Inputs:
        json request with an "address" Query parameter
        example:
        {"address": '<ADDRESS STRING>'}
        
    Outputs:
        HTTP 200 + latlon if OK
        HTTP 400 + error message otherwise
    '''
    # Log to Azure function apps online
    logging.info('Python HTTP trigger function processed a request.')

    # Try retrieve address string
    query = req.params.get('address')

    # general error handler - taken from example documentation
    if not query:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            query = req_body.get('address')

    # final check that we have some value
    if not query:
        return func.HttpResponse(body='Could Not Retrieve Address from Input',
                                 status_code=400)

    def query_azure_maps(_query_):
        '''Send query to azure maps service with parameters below'''
        _format_ = 'json'
        _subscription_key_ = 'd5vwJomzaZQjWo1BCYXsNyMOm1QHAxZ9Ie-MkszAzrw'
        _country_set_ = 'US'
        url = f"https://atlas.microsoft.com/search/address/{_format_}?subscription-key={_subscription_key_}&countrySet={_country_set_}&api-version=1.0&query={_query_}"
        response = requests.get(url=url)
        return response

    def extract_coordinates(response):
        '''Extract the best lat+lon match from the Azure maps response'''
        locations = [dict_ for dict_ in response.json()['results']]
        if locations:
            closest = locations[0]
            position = closest.get('position')
            (lat, lon) = position.get('lat'), position.get('lon')
        return (lat, lon)

    # Call our functions above sequentially
    response = query_azure_maps(query)
    (lat, lon) = extract_coordinates(response)

    output = f"{lat}, {lon}"

    # Return OK http response
    return func.HttpResponse(body=output, status_code=200)
def main(req: func.HttpRequest) -> func.HttpResponse:  # API version
    API_VERSION = "0.0.1"

    logging.info(
        f"Python HTTP trigger function processed a request, API version: {API_VERSION}"
    )

    # Allowed domains
    allowed_domains = ["fabrikam.com", "fabricam.com"]

    # Check HTTP basic authorization
    if not authorize(req):
        logging.info("HTTP basic authentication validation failed.")
        return func.HttpResponse(status_code=401)

    # Get the request body
    try:
        req_body = req.get_json()
    except:
        return func.HttpResponse(json.dumps({
            "version":
            API_VERSION,
            "action":
            "ShowBlockPage",
            "userMessage":
            "There was a problem with your request."
        }),
                                 status_code=200,
                                 mimetype="application/json")

    # Print out the request body
    logging.info(f"Request body: {req_body}")

    # Get the current user language
    language = req_body.get(
        'ui_locales'
    ) if 'ui_locales' in req_body and req_body.get('ui_locales') else "default"
    logging.info(f"Current language: {language}")

    # If email claim not found, show block page. Email is required and sent by default.
    if 'email' not in req_body or not req_body.get(
            'email') or "@" not in req_body.get('email'):
        return func.HttpResponse(json.dumps({
            "version":
            API_VERSION,
            "action":
            "ShowBlockPage",
            "userMessage":
            "Email is mandatory."
        }),
                                 status_code=200,
                                 mimetype="application/json")

    # Get domain of email address
    domain = req_body.get('email').split('@')[1]
    logging.info(f"Current doamin: {domain}")

    # Check the domain in the allowed list
    if domain.lower() not in allowed_domains:
        s = ", "
        return func.HttpResponse(json.dumps({
            "version":
            API_VERSION,
            "action":
            "ShowBlockPage",
            "userMessage":
            f"You must have an account from '{s.join(allowed_domains)}' to register as an external user for Contoso."
        }),
                                 status_code=200,
                                 mimetype="application/json")

    # If jobTitle claim is too short, show validation error message so that user can fix error.
    if ('jobTitle' in req_body and req_body.get('jobTitle')
        ):  # use 'if not' (...) to require Job Title
        if len(req_body.get('jobTitle')) < 5:
            return func.HttpResponse(json.dumps({
                "version":
                API_VERSION,
                "status":
                400,
                "action":
                "ValidationError",
                "userMessage":
                "Job Title must contain at least five characters."
            }),
                                     status_code=400,
                                     mimetype="application/json")

    # Input validation passed successfully, return `Allow` response.
    return func.HttpResponse(json.dumps({
        "version": API_VERSION,
        "action": "Continue"
    }),
                             status_code=200,
                             mimetype="application/json")