Ejemplo n.º 1
0
def main(req: func.HttpRequest, items: func.Out[func.SqlRowList]) -> func.HttpResponse:
    """Sample SQL Output Binding

    See https://aka.ms/sqlbindingsoutput for more information about using this binding

    *IMPORTANT*
        Local Development : You must have v4.x of the Azure Function Core Tools installed, support for earlier versions will be added in a later release.
        Deployed App : The app must be deployed to the EUAP region, support for other regions will be added later.

    See https://github.com/Azure/azure-functions-sql-extension/issues/250 for the current state of Python support for the SQL binding

    These tasks should be completed prior to running :
    1. Update "commandText" in function.json - this should be the name of the table that you wish to upsert values to
    2. Add an app setting named "SqlConnectionString" containing the connection string to use for the SQL connection
    3. Change the bundle name in host.json to "Microsoft.Azure.Functions.ExtensionBundle.Preview" and the version to "[4.*, 5.0.0)"
    4. Update requirements.txt and change the "azure-functions" line to "azure-functions==1.11.3b1" *IMPORTANT* Support for durable functions is not available in this release. A future release will combine SQL bindings and durable functions capabilities.
    5. Add an app setting named "PYTHON_ISOLATE_WORKER_DEPENDENCIES" and set the value to "1" (to ensure that the correct version of the azure-functions library is used)

    Arguments:
    req: The HttpRequest that triggered this function
    items: The objects to be upserted to the database
    """

    # Note that this expects the body to be an array of JSON objects which
    # have a property matching each of the columns in the table to upsert to.
    body = json.loads(req.get_body())
    rows = func.SqlRowList(map(lambda r: func.SqlRow.from_dict(r), body))
    items.set(rows)

    return func.HttpResponse(
        body=req.get_body(),
        status_code=201, # 201 Created
        mimetype="application/json"
    )
Ejemplo n.º 2
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    logging.info(req.get_body())

    name = req.get_body().decode('utf8')
    logging.info(name)

    if name:
        logging.info("Starting process")
        refs = References(name)
        logging.info("Reference object created")
        refs.infer_gender()
        logging.info("Gender inferred")
        refs.infer_ethnicity()
        logging.info("Ethnicity inferred")

        name = {
            **refs.ethnicity_results,
            **refs.gender_results,
            **refs.raw_results
        }

        return func.HttpResponse(
            json.dumps(name),
            mimetype="application/json",
        )
    else:
        return func.HttpResponse(
            "A reference list was not properly identified.", status_code=200)
Ejemplo n.º 3
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('start.')

    if req.method == 'POST':
        logging.info(req.get_body())
        im = Image.open(BytesIO(req.get_body()))

        # exifからGPS情報を取得する
        exif = im._getexif()
        for k, v in exif.items():
            if k in ExifTags.TAGS:
                gps_tag = ExifTags.TAGS[k]

                if gps_tag == 'GPSInfo':
                    # 緯度経度の計算をする
                    lat_deg, lat_min, lat_sec = v[2][0], v[2][1], v[2][2]
                    latitude_n = lat_deg + (lat_min / 60.0) + (lat_sec /
                                                               3600.0)

                    lon_deg, lon_min, lon_sec = v[4][0], v[4][1], v[4][2]
                    longitude_e = lon_deg + (lon_min / 60.0) + (lon_sec /
                                                                3600.0)

                    # "緯度, 軽度" の形にデータ整形
                    logging.info(str(latitude_n) + ', ' + str(longitude_e))
                    return func.HttpResponse(
                        str(latitude_n) + ', ' + str(longitude_e))

    else:
        logging.warning('not arrowed method. ' + req.method)
        return func.HttpResponse('not arrowed method. ' + req.method,
                                 status_code=403)
Ejemplo n.º 4
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    message = str(req.get_body())
    payload = json.loads(req.get_body())
    signature = req.headers.get('X-Tfe-Notification-Signature')
    post_response = "I'm here!"

    secret = bytes(os.getenv('SALT', None), 'utf-8')
    hash = hmac.new(secret, req.get_body(), hashlib.sha512)

    if hash.hexdigest() == signature:
        # HMAC verified
        if payload and 'run_status' in payload['notifications'][0]:
            body = payload['notifications'][0]
            print(body['run_status'])
            if body['run_status'] in ON_STATES:
                print(body['run_status'],
                      "Run status indicates turn on the agent.")
                post_response = update_service('on')
            elif body['run_status'] in OFF_STATES:
                print(body['run_status'],
                      "Run status indicates turn off the agent.")
                post_response = update_service('off')

        return func.HttpResponse(json.dumps(post_response),
                                 headers={
                                     "Content-Type": "application/json",
                                     "Access-Control-Allow-Origin": "*"
                                 },
                                 status_code=200)

    return 'Invalid HMAC'
Ejemplo n.º 5
0
async def main(req: func.HttpRequest, starter: str) -> func.HttpResponse:
    try:
        orchest_name = "functionName"
        client = df.DurableOrchestrationClient(starter)

        called_orchest = req.route_params.get(orchest_name)

        client_input = None
        if req.get_body():
            client_input = req.get_json()
        if req.params:
            client_input = dict(req.params)
        if req.params and req.get_body():
            logging.warn("Do not support query params & body in the same time")

        instance_id = await client.start_new(called_orchest, None,
                                             client_input)

        logging.info(f"Started orchestration with ID = '{instance_id}'.")

        return client.create_check_status_response(req, instance_id)

    except Exception as e:
        str_issue = "Client initialisation Issue: {}".format(e)
        logging.error(str_issue, traceback.format_exc())
        return func.HttpResponse(str_issue, status_code=500)
Ejemplo n.º 6
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    logging.info(req.get_body())
    inputreq = json.loads(req.get_body())

    par_entities = inputreq['firstRow']['entities'][0]
    attributies = par_entities['attributes']

    tableStructure = []
    query = "CREATE TABLE " + "[" + par_entities['name'] + "]" + " ("
    datafileLocations = []
    for attribute in attributies:

        if attribute['dataType'] == "int64":
            datatype = "int"
        elif attribute['dataType'] == "string":
            datatype = "nvarchar(350)"
        elif attribute['dataType'] == "guid":
            datatype = "uniqueidentifier"
        elif attribute['dataType'] == "dateTime":
            datatype = "datetime"
        elif attribute['dataType'] == "boolean":
            datatype = "bit"
        elif attribute['dataType'] == "decimal":
            datatype = "float"
        elif attribute['dataType'] == "unclassified":
            attribute['dataType'] = "Byte[]"
            datatype = "varbinary(max)"
        else:
            datatype = "nvarchar(350)"

        query += "[" + attribute['name'] + "] " + datatype + ","
        tableStructure.append({
            "name": attribute['name'],
            "type": attribute['dataType'],
            "typeSQL": datatype
        })

    query = query[:-1]
    query += ")"

    results = []
    results.append({
        "name": par_entities['name'],
        "tableName": "[" + par_entities['name'] + "]",
        "modifiedTime": "null",
        "tableStructure": tableStructure,
        "query": query,
        "datafileLocations": datafileLocations
    })

    d = collections.OrderedDict()
    d['results'] = results

    model_json = json.dumps(d, indent=4)
    logging.info(str(model_json))

    return func.HttpResponse(str(model_json))
Ejemplo n.º 7
0
def main_work(req: func.HttpRequest, tc: TimerControl) -> func.HttpResponse:
    global APP_DATA
    if APP_DATA is None:
        logging.info("Reloading page (%s, %s)", str(use_azure_blob),
                     str(preload))
        APP_DATA = AppData(use_azure_blob=use_azure_blob, preload=preload)

    page = Page(APP_DATA)

    if False:
        logging.debug("METHOD: " + str(req.method))
        logging.debug("URL: " + str(req.url))
        logging.debug("HEADERS: " + str(dict(req.headers)))
        logging.debug("PARAMS: " + str(dict(req.params)))
        logging.debug("ROUTE PARAMS: " + str(dict(req.route_params)))
        logging.debug("GET BODY: " + str(req.get_body().decode()))

    # Header example from Azure:
    # HEADERS: {'x-client-port': '51166', 'sec-fetch-site': 'same-origin', 'disguised-host': 'testshkoladocker.azurewebsites.net',
    #           'x-forwarded-for': '82.69.90.27:51166', 'x-appservice-proto': 'https', 'sec-fetch-dest': 'document',
    #           'referer': 'https://testshkoladocker.azurewebsites.net/main', 'sec-fetch-mode': 'navigate',
    #           'accept-language': 'en-US, en; q=0.9, hr; q=0.8, bs; q=0.7, sr; q=0.6, sl; q=0.5',
    #           'host': 'testshkoladocker.azurewebsites.net', 'upgrade-insecure-requests': '1',
    #           'x-arr-ssl': '2048|256|C=US, S=Washington, L=Redmond, O=Microsoft Corporation, OU=Microsoft IT, CN=Microsoft IT TLS CA 5|CN=*.azurewebsites.net',
    #           'was-default-hostname': 'testshkoladocker.azurewebsites.net',
    #           'x-waws-unencoded-url': '/main?op=login_test&login_return=gASVaQAAAAAAAAB9lCiMCXBhZ2VfbmFtZZSMBHRlc3SUjARxX2lklIwAlIwEbF9pZJSMD3k1X2ZyYWN0aW9ucy51a5SMBGxhbmeUjAJ1a5SMB3VzZXJfaWSUaASMBG1lbnWUjAZtb2JpbGWUjAJqc5SJdS4%3D&user_id=Zomebody',
    #           'x-original-url': '/main?op=login_test&login_return=gASVaQAAAAAAAAB9lCiMCXBhZ2VfbmFtZZSMBHRlc3SUjARxX2lklIwAlIwEbF9pZJSMD3k1X2ZyYWN0aW9ucy51a5SMBGxhbmeUjAJ1a5SMB3VzZXJfaWSUaASMBG1lbnWUjAZtb2JpbGWUjAJqc5SJdS4%3D&user_id=Zomebody',
    #           'request-id': '|9fe76d08-44458cf4688911f9.1.',
    #           'accept': 'text/html, application/xhtml+xml, application/xml; q=0.9, image/webp, image/apng, */*; q=0.8, application/signed-exchange; v=b3; q=0.9',
    #           'x-site-deployment-id': 'testshkoladocker', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
    #           'x-client-ip': '82.69.90.27', 'content-length': '0', 'connection': 'close', 'accept-encoding': 'gzip, deflate, br', 'client-ip': '82.69.90.27:51166', 'sec-fetch-user': '******',
    #           'x-arr-log-id': 'd69d498a-19fe-4673-9809-d2aa180c87c5', 'x-forwarded-proto': 'https', 'max-forwards': '10'}

    headers = Headers()
    request = Request(req)

    args = dict()
    if req.method == "POST":
        # Merge body and request parameters
        # TODO: We cannot assume POST will only send json.
        # We should check content type of the POST request.
        try:
            args = json.loads(req.get_body().decode())
        except json.JSONDecodeError:
            pass

    args.update(request.get_query_data())

    args["root"] = "main"
    if "language" not in args.keys():
        args["language"] = "rs"

    with tc.new_section("page_main"):
        page_body = page.main(request, headers, tc, args)

    return func.HttpResponse(page_body,
                             status_code=headers.status_code(),
                             headers=headers.get_headers(),
                             mimetype=headers.content_type())
Ejemplo n.º 8
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    start = time.time()
    logging.info('Python HTTP trigger function processed a request.')

    try:
        # Decode and return request body as JSON
        req_body = req.get_json()
    except ValueError:
        numA, numB = None, None
        pass
    else:
        numA = req_body.get('A')
        numB = req_body.get('B')        

    if numA and numB:
        # Call Common Functions
        sum2 = tools.sum2(numA, numB)
        sub2 = tools.sub2(numA, numB)
        pow2 = tools.pow2(numA, numB)
        div2 = tools.div2(numA, numB)

        dt1 = time.time()-start
        return func.HttpResponse(
            json.dumps({
                'method': req.method,
                'url': req.url,
                'headers': dict(req.headers),
                'params': dict(req.params),
                'get_body': req.get_body().decode(),
                'timer': dt1,
                'return': 'Function App recieved %s and %s' %({numA}, {numB}) ,
                'Sum': sum2,
                'Sub': sub2,
                'Pow': pow2,
                'Div': div2
            })
            )

    else:
        dt1 = time.time()-start
        return func.HttpResponse(
            json.dumps({
                'method': req.method,
                'url': req.url,
                'headers': dict(req.headers),
                'params': dict(req.params),
                'get_body': req.get_body().decode(),
                'timer': dt1,
                'return': 'Please pass numbers A,B to Function App in the request body'
            })
            , status_code=400
        )
Ejemplo n.º 9
0
def main(req: func.HttpRequest) -> func.HttpResponse:

    logging.info(
        'Python createAdvertisement trigger function processed a request.')

    request = req.get_json()

    if request:

        try:

            url = os.environ['MongoDbUdacityExam2']
            client = pymongo.MongoClient(url)
            database = client['udacity-exam-2-db']
            collection = database['advertisements']

            logging.info(request)

            rec_id1 = collection.insert_one(eval(request))

            return func.HttpResponse(req.get_body())

        except:

            logging.info('----------Failed--------')
            return func.HttpResponse('Could not connect to mongodb',
                                     status_code=500)

    else:
        return func.HttpResponse("Please pass name in the body",
                                 status_code=400)
Ejemplo n.º 10
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    #Parse URL Parameters
    request_args = req.params

    http_method = request_args.get('http_method')
    url = request_args.get("url")
    port = request_args.get('port')
    token = request_args.get('token')

    #Build Full URL out of Parameters
    full_url = http_method + '://' + url + ':' + port + '/services/collector/raw'

    #Get Body
    webhook_body = req.get_body()

    #Create URLLib3 Pool Manager
    http = urllib3.PoolManager()
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    #Post Event
    r = http.request('POST',
                     full_url,
                     body=webhook_body,
                     headers={
                         'Content-Type': 'application/json',
                         'Authorization': 'Splunk ' + token
                     })
    return func.HttpResponse(
        body="{\"body\": \"Success\",\"statusCode\": 200}", status_code=200)
Ejemplo n.º 11
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:

        name = req.params.get('name')
        if not name:
            return func.HttpResponse("Please specify a file name",
                                     status_code=400)
        data = req.get_body()
        if not data:
            return func.HttpResponse("Please upload content", status_code=400)
        connect_str: str = 'DefaultEndpointsProtocol=https;AccountName=djbvideoappsto;AccountKey=Q2w9wi3v0JbTMUIV0kMc0K0kRHtWhTciQ4S7ZgdYSHhic59ZMQk/BlQPIFYQ/fft8uPQYymym97GgYxY4dbvOg==;EndpointSuffix=core.windows.net'

        # Create the BlobServiceClient object which will be used to create a container client
        blob_service_client = BlobServiceClient.from_connection_string(
            connect_str)

        # Create a unique name for the container
        container_name = "djbtest"

        container = blob_service_client.get_container_client(container_name)

        container.upload_blob(
            name,
            data,
        )

        return func.HttpResponse(status_code=200)

    except Exception as ex:
        logging.exception('Exception:')
        logging.error(ex)
def main(req: func.HttpRequest) -> func.HttpResponse:

    request = req.get_json()

    if request:
        try:
            # TODO: Update with appropriate MongoDB connection information
            url = "mongodb://*****:*****@neighborlymongodbjmira.documents.azure.com:10255/?ssl=true&replicaSet=globaldb"  
            client = pymongo.MongoClient(url)
            database = client['neighborlydbjmira']
            collection = database['advertisements']

            rec_id1 = collection.insert_one(eval(request))

            return func.HttpResponse(req.get_body())

        except ValueError:
            print("could not connect to mongodb")
            return func.HttpResponse('Could not connect to mongodb', status_code=500)

    else:
        return func.HttpResponse(
            "Please pass name in the body",
            status_code=400
        )
Ejemplo n.º 13
0
def main(req: func.HttpRequest) -> func.HttpResponse:

    request = req.get_json()

    if request:
        try:
            url = "mongodb://*****:*****@proj2cosmodb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@proj2cosmodb@"
 # TODO: Update with appropriate MongoDB connection information
            client = pymongo.MongoClient(url)
            database = client['proj2appdb']
            collection = database['advertisements']

            rec_id1 = collection.insert_one(eval(request))

            return func.HttpResponse(req.get_body())

        except ValueError:
            print("could not connect to mongodb")
            return func.HttpResponse('Could not connect to mongodb', status_code=500)

    else:
        return func.HttpResponse(
            "Please pass name in the body",
            status_code=400
        )
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('project-create request')

    body = req.get_body()

    # validate the call...
    strbody = unquote_plus(body.decode("utf-8"))
    if len(strbody) < 10 or strbody.find('&') < 0 or strbody.find('=') < 0:
        return func.HttpResponse('Call not valid (100)', status_code=200)
    names = dict(x.split('=') for x in strbody.split('&'))

    if not spotchk.spotchk().validate_query2(names):
        return func.HttpResponse('Call not valid (101)', status_code=200)
    # validation complete...let's do something...

    with open(pathlib.Path(__file__).parent /
              'create_pr_dialog.json') as dfile:
        strdialog = dfile.read()

    strdata = "{ 'trigger_id': '" + names[
        'trigger_id'] + "'," + "'view': '" + strdialog + "'}"

    urldialog = "https://slack.com/api/views.open"
    headers = {
        'content-type': 'application/json; charset=utf-8',
        'Authorization': f'Bearer {os.environ["SL_ACCESS_TOKEN_GENERAL"]}'
    }

    # respond to caller...
    r = requests.post(url=urldialog, headers=headers, data=strdata)
    json_response = json.loads(r.text)
    if json_response["ok"] == True:
        return func.HttpResponse()
    else:
        return func.HttpResponse(r.text)
Ejemplo n.º 15
0
def main(req: func.HttpRequest) -> func.HttpResponse:

    request = req.get_json()

    if request:
        try:
            url = "mongodb://*****:*****@azurenanodegreecosmodbproject2.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&maxIdleTimeMS=120000&appName=@azurenanodegreecosmodbproject2@"
            client = pymongo.MongoClient(url,
                                         ssl=True,
                                         ssl_cert_reqs=ssl.CERT_NONE)
            database = client['azurenanodegreecosmodbproject2']
            collection = database['advertisements']

            rec_id1 = collection.insert_one(eval(request))

            return func.HttpResponse(req.get_body())

        except ValueError:
            print("could not connect to mongodb")
            return func.HttpResponse('Could not connect to mongodb',
                                     status_code=500)

    else:
        return func.HttpResponse("Please pass name in the body",
                                 status_code=400)
Ejemplo n.º 16
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    if req.method == 'POST':
        auth = req.headers.get('Authorization').split(' ')[1]
        request_data = req.get_body()
        digest = hmac.new(base64.b64decode(security_token),
                          msg=request_data,
                          digestmod=hashlib.sha256).digest()
        signature = base64.b64encode(digest).decode()

        if auth == signature:
            data = req.get_json()
            message = data['text']
            return func.HttpResponse(
                json.dumps({
                    'type': 'message',
                    'text': _get_jira_link(message)
                }))
        else:
            return func.HttpResponse(
                json.dumps({
                    "type":
                    "message",
                    "text":
                    "Error: message sender cannot be authenticated."
                }))
def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        func_response = {}
        status_code = 400
        logging.info('****** ADF Meta Extractor API ******')
        req_body = req.get_body().decode()
        payload = json.loads(req_body)
        requested_api_name = payload.get('api_name')
        if requested_api_name not in AVAILABLE_API_LIST:
            invalid_req_mesg = f"Invalid API name. Available APIs : {str(AVAILABLE_API_LIST)}"
            return func.HttpResponse(invalid_req_mesg,
                                     mimetype='application/json',
                                     status_code=400)

        if requested_api_name == 'GetDatasets':
            logging.info(f"Invoking {requested_api_name} API")
            func_response = get_pipelines(payload)
        elif requested_api_name == 'GetTriggers':
            logging.info(f"Invoking {requested_api_name} API")
            func_response = get_triggers(payload)
        output_json = json.dumps(func_response)
        status_code = func_response['status_code']
        return func.HttpResponse(output_json, status_code=status_code)
    except Exception as e:
        return func.HttpResponse(str(e), status_code=400)
Ejemplo n.º 18
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    conn_str = os.environ["DBConnectionString"]

    try:

        body = req.get_body().decode("utf-8")
        logging.info(body)

        values = parse_form_values(body)

        if not is_right_message(values["Body"]):
            return func.HttpResponse(
                f'Text the word "subscribe" if you would like to be added to the SLO Coronavirus Tracker texting list.'
            )

        with subscriber_repo.SubscriberRepository(conn_str) as repo:
            success = repo.add_subscriber(values["From"])

            if not success:
                return func.HttpResponse(
                    f'This number is already subscribed to the SLO Coronavirus Tracker. Reply "stop" to unsubscribe at any time.'
                )

            return func.HttpResponse(
                f'Added phone number {values["From"]} to the SLO Coronavirus Tracker. Reply "stop" to unsubscribe at any time.'
            )

    except Exception as e:
        logging.error(e)
        return func.HttpResponse(
            "Sorry, something went wrong while processing your request")
Ejemplo n.º 19
0
def main(req: func.HttpRequest) -> func.HttpResponse:

    param = req.route_params.get("parem")

    if param == "status" or param == "producer/status":
        return func.HttpResponse("STATUS : Everything's working 1",
                                 status_code=200,
                                 headers={
                                     "ABSA-Spline-API-Version": "1",
                                     "ABSA-Spline-Accept-Request-Encoding":
                                     "gzip"
                                 })

    logging.info('Python HTTP trigger function processed a request.')

    try:
        # Get body of request
        req_body = req.get_body()
    except ValueError:
        pass
    else:
        try:
            req_body_unzip = gzip.decompress(req_body)
        except OSError:
            pass

        spline_JSON = req_body_unzip.decode()

        # Convert Spline input Json to Apache Atlas output
        purview_lineage = convert_Spline_to_Purview(spline_JSON)

        # Upload to Purview
        uploadPurview(purview_lineage)

    return func.HttpResponse("Everything's working", status_code=200)
Ejemplo n.º 20
0
def main(req: func.HttpRequest, cmdl: bytes, cvec: bytes, clbl: str,
         nmdl: bytes, guid: str) -> func.HttpResponse:
    logging.info('Executing GraphQL function.')

    queue = QueueClient.from_connection_string(
        os.environ['AzureWebJobsStorage'], 'predictions')

    try:
        query = req.get_body().decode()
    except ValueError:
        pass

    if query:
        schema = Schema(Query)
        context = CACHE_MANAGER.get(guid, cmdl, cvec, clbl, nmdl)
        results = schema.execute(query, context=context)
        response = responses.graphql(results)

        # Write response to azure queue storage
        message = responses.storage(results)
        if message:
            queue.send_message(message, time_to_live=-1)

        return response
    else:
        return responses.bad_request(
            'Please pass a GraphQL query in the request body.')
Ejemplo n.º 21
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    # Grab the required params
    image = req.params.get('image')
    if not image:
        try:
            req_body = json.loads(req.get_body().decode())
        except ValueError:
            raise
        else:
            image = req_body.get('image')

    if image:
        # We decode the image, get a random angle, rotate the image and encode it back
        decoded_image = image_helper.decode_image_base64(image)
        random_rotate_angle = randint(0, 10) * constants.ROTATE_ANGLE_DEFAULT
        image_rotated_bytes = image_helper.rotate_image(
            decoded_image, random_rotate_angle)
        encoded_image = image_helper.encode_image_base64(image_rotated_bytes)

        # This is our response
        json_response = {'encoded_image': encoded_image}

        return func.HttpResponse(json.dumps(json_response),
                                 headers={'Access-Control-Allow-Origin': '*'},
                                 status_code=200,
                                 mimetype='application/json')

    else:
        return func.HttpResponse(
            'Please pass an image in the query string or the body',
            headers={'Access-Control-Allow-Origin': '*'},
            status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    # name = req.params.get('name')
    pdf = HTML(string=req.get_body().decode('utf-8')).write_pdf()

    return func.HttpResponse(pdf)
def main(req: func.HttpRequest) -> func.HttpResponse:

    #print("Get into the funciton with ", req.params['data'])
    request = req.get_json()
    #print ('json part of your request is: ',request)
    if request:
        try:
            url = os.environ['myMongoDbconnectionString']
            client = pymongo.MongoClient(url)
            database = client['neighborlydB']
            collection = database['advertisements']

            rec_id1 = collection.insert_one(
                eval(request))  #no need to use eval as json can be imported

            return func.HttpResponse(req.get_body())

        except ValueError:
            print("could not connect to mongodb")
            return func.HttpResponse('Could not connect to mongodb',
                                     status_code=500)

    else:
        return func.HttpResponse("Please pass name in the body",
                                 status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    # first check for a valid call
    body = req.get_body()

    strbody = unquote_plus(body.decode("utf-8"))
    if len(strbody) < 10 or strbody.find('&') < 0 or strbody.find('=') < 0:
        return func.HttpResponse('Rebuild site delayed 200ms', status_code=200)

    names = dict(x.split('=') for x in strbody.split('&'))

    if not spotchk.spotchk().validate_query2(names):
        return func.HttpResponse('Rebuild site delayed 200ms', status_code=200)

    gh = github.OWASPGitHub()
    respond_url = names['response_url']
    logging.info("Building staff projects and milestones json files")
    headers = {'content-type': 'application/json'}
    data = {
        'response_type': 'ephemeral',
        'text': 'Rebuilding staff projects and milestones...ignore timeouts'
    }

    # respond to caller...
    msg = json.dumps(data)
    r = requests.post(url=respond_url, headers=headers, data=msg)

    helperfuncs.build_staff_project_json(gh)

    return func.HttpResponse(f"Projects and milestones built!")
Ejemplo n.º 25
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('AZ Function Post Request for Prediction')

    try:
        image_bytes = req.get_body()
        #logging.info(f'{image_bytes}')

        content_type = req.headers.get("Content-Type")
        formdatadecoder = MultipartDecoder(image_bytes, content_type)

        # assumes there is only one part (our file) being uploaded
        for part in formdatadecoder.parts:
            resp_body = predict(part.content)
            break

        return func.HttpResponse(status_code=200,
                                 headers={"Content-Type": "application/json"},
                                 body=json.dumps(resp_body))

    except Exception as e:
        raise e
        logging.error(e)
        return func.HttpResponse(
            "Either you did not post a compatible image or an unknown error occurred.",
            status_code=400)

    return func.HttpResponse()
Ejemplo n.º 26
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    global all_nodes
    all_nodes = {}
    logging.info("Python HTTP trigger function processed a request.")
    try:
        req_body = req.get_body()
        req_dict = json.loads(req_body)
        map_entities(req_dict)
        # dumped = jsonpickle.encode(clusters)
        # headers = {
        #     "Content-type": "application/json",
        #     "Access-Control-Allow-Origin": "*",
        # }
        # return func.HttpResponse(dumped, status_code=200, headers=headers)

        filename = f"{req_dict['name']}.png"
        with open(filename, "rb") as f:
            mimetype = mimetypes.guess_type(filename)
            return func.HttpResponse(f.read(), mimetype=mimetype[0])
    except Exception as e:
        logging.info(e)
        print(e)
        headers = {
            "Content-type": "text/plain",
            "Access-Control-Allow-Origin": "*"
        }
        return func.HttpResponse("Something went wrong!",
                                 status_code=500,
                                 headers=headers)
def main(req: func.HttpRequest) -> func.HttpResponse:
    post_data = req.get_body().decode("utf-8")
    post_dict = urllib.parse.parse_qs(post_data)

    token = post_dict.get('token')[0]

    if token != os.environ["SL_TOKEN_GENERAL"]:
        return func.HttpResponse(
            body='Invalid token',
            status_code=400
        )

    text = post_dict.get('text')[0]
    command = post_dict.get('command')[0]
    response_url = post_dict.get('response_url')[0]

    if command == '/contact-lookup':
        contact_lookup(text, response_url)

    if command == '/contact-details':
        contact_details(text, response_url)

    if command == '/stripe-details':
        stripe_details(text, response_url)

    return func.HttpResponse(
        body='',
        status_code=200
    )
def main(req: func.HttpRequest,
         rpmsg: func.Out[func.QueueMessage]) -> func.HttpResponse:
    logging.info('chapter-report request')

    body = req.get_body()

    # validate the call...
    strbody = unquote_plus(body.decode("utf-8"))
    if len(strbody) < 10 or strbody.find('&') < 0 or strbody.find('=') < 0:
        return func.HttpResponse('Call not valid (100)', status_code=200)
    names = dict(x.split('=') for x in strbody.split('&'))

    if not spotchk.spotchk().validate_query2(names):
        return func.HttpResponse('Call not valid (101)', status_code=200)
    jsonstr = strbody
    # validation complete...let's do something...
    resp = 'Report request received. You will receive a message when available.'

    #add this to the queue, it will be picked up by the chapter-process function
    if 'chapter-report' in jsonstr:
        rpmsg.set(jsonstr)

    headers = {"Content-Type": "application/json;charset=utf-8"}

    return func.HttpResponse(resp, headers=headers)
Ejemplo n.º 29
0
def main(req: func.HttpRequest,
         cosmosdb: func.Out[func.Document]) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    data = json.loads(req.get_body())
    if 'text' not in data:
        logging.error("Validation Failed")
        raise Exception("Couldn't create the todo item.")

    timestamp = str(time.time())

    item = {
        'id': str(uuid.uuid1()),
        'text': data['text'],
        'checked': False,
        'createdAt': timestamp,
        'updatedAt': timestamp,
    }
    cosmosdb.set(func.Document.from_json(json.dumps(item)))

    return func.HttpResponse(body=json.dumps(item),
                             status_code=200,
                             headers={
                                 "Access-Control-Allow-Origin":
                                 "*",
                                 "Access-Control-Allow-Headers":
                                 "Content-Type",
                                 "Access-Control-Allow-Methods":
                                 "OPTIONS,GET,PUT,POST,DELETE"
                             })
Ejemplo n.º 30
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Analyze Receipt function processed a request.')

    file_sent = None

    API_ENDPOINT = os.environ['API_ENDPOINT']
    API_KEY = os.environ['API_KEY']
    INFO_TABLE = os.environ['INFO_TABLE']
    IMG_CONTAINER = os.environ['IMG_CONTAINER']
    CONNECTION_STRING = os.environ['STORAGE_CONNECTION_STRING']

    try:
        file_sent = req.get_body()
    except ValueError:
        pass

    if file_sent:
        result, status_code = analyze_receipt(file_sent, API_ENDPOINT, API_KEY)
        if status_code == 200:
            save_receipt(file_sent, result, INFO_TABLE, IMG_CONTAINER,
                         CONNECTION_STRING)
            logging.info("Saved file info.")
        else:
            logging.warning(
                f"Did not save file info, status code: {status_code}")
        return func.HttpResponse(result, status_code=status_code)
    else:
        return func.HttpResponse("Please pass a file in the request body",
                                 status_code=400)