def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') try: req_body = req.get_json() except ValueError: pass subscription_id = req_body['PartitionKey'] # '40fb353a-d355-4197-b2a5-92e71f07f063' alert_id = req_body['RowKey'] client = SecurityCenter(credentials=credentials, subscription_id=subscription_id, asc_location='eastus') logging.info('REQUEST BODY ----') logging.info(req_body) state = 'NotFound' alerts = client.alerts.list() logging.info('ALERTS CALL MADE') for alert in alerts: alert_dict = alert.as_dict() if alert_dict['name'] == alert_id: logging.info('ALERT FOUND WITH NAME %s AND STATE %s' % (alert_id, alert_dict['state'])) state = alert_dict['state'] return func.HttpResponse( body=json.dumps({ 'name': alert_id, 'state': state }), headers={ "Content-Type": "application/json" }, status_code=200 )
def main(req: func.HttpRequest) -> func.HttpResponse: req_body = req.get_json() pre = np.array(req_body['numpy'])[:-1] granularity = req_body["granularity"] logging.info('Python MLFINC {0}.'.format(granularity)) global modelSet global appConfig if granularity not in modelSet.keys(): modelName = 'lstmProd{0}'.format(granularity) logging.info(modelName) modelSet[granularity] = load_model( io.BytesIO( requests.get( appConfig["config"]["storage"][modelName]).content)) model = modelSet[granularity] pre_x = (pre - np.average(pre, axis=0)) / np.std(pre, axis=0) pre_x = pre_x.reshape(1, pre_x.shape[0], pre_x.shape[1]) if granularity in convolutional: pre_x = pre_x.reshape(pre_x.shape[0], 1, pre_x.shape[1], pre_x.shape[2], 1) pred = model.predict(pre_x) pre_y = np.array([[pre[a][b] for b in range(3, pre.shape[1], 5)] for a in range(pre.shape[0])]) pred = pred[0] * np.std(pre_y, axis=0) + pre_y[pre.shape[0] - 1] print(pred.shape) pred = pred.tolist() print(json.dumps(pred)) return func.HttpResponse(json.dumps(pred)) if name: return func.HttpResponse(f"Hello {name}!") else: return func.HttpResponse( "Please pass a name on the query string or in the request body", status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') if not name: try: req_body = req.get_json() except ValueError: pass else: name = req_body.get('name') if name: return func.HttpResponse( f"Hello, {name}. This HTTP triggered function executed successfully." ) else: # This will raise error because signal only works in main thread # command = ['artifacts', 'universal', 'download', '--organization', 'https://dev.azure.com/infinite-wars/', # '--feed', 'infinite-wars', '--name', 'data-l2-testing-case-v1.0.1776', '--version', '1.0.0', # '--path', '.'] # a = az_cli(command) # logging.info(f"a return {a}") command = [ 'lab', 'get', '-g', 'rg-testing-env-lab', '--name', 'dtl-aladdin-test' ] test = az_cli(command) logging.info(f"test return {test}") logging.info("123456") return func.HttpResponse( "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.", status_code=200)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('JIRA WebHook request received') # Parse the JSON data = json.loads(req.get_body()) # What kind of event was it? ets = data.get("timestamp", None) etype = data.get("webhookEvent", None) logging.info("JIRA event type %s from %s", etype, ets) # Grab the JIRA Ticket Reference jref = extractJiraTicket(etype, data) # What should we send back? message = None if etype == COMMENT_CREATED: message = buildCommentMessage(jref, data) elif etype == ISSUE_UPDATED: message = buildUpdateMessage(jref, data) else: logging.warn("Unhandled event type received from JIRA <%s>", etype) return func.HttpResponse("Invalid event type '%s'" % etype, status_code=400) # Grab the TAWK details (tawkSID, tawkHID) = getTawkDetails(etype, jref, data) if not tawkSID: logging.warn("Tawk Ticket Details missing from JIRA data: %s", data) return func.HttpResponse("No Tawk.To ticket details found, ignoring") logging.info("Matching Tawk.To ticket identified - %s <%s>", tawkHID, tawkSID) # Send the update recordJIRAUpdate(tawkHID, tawkSID, jref, message) # And we're done! return func.HttpResponse("Thank you JIRA! Tawk %s updated" % tawkHID)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Starting insert row.') table_name = req.headers.get('name') if not table_name: #If name wasnt added as header, search for it in the parameters table_name = req.params.get('name') value = req.get_json() if table_name: retrieved_secret = getConnectionString() table_service = TableService(connection_string=retrieved_secret.value) if table_service.exists(table_name): if 'PartitionKey' not in value.keys(): #This is mandatory value['PartitionKey'] = 'reference' if 'RowKey' not in value.keys(): #This is mandatory too value['RowKey'] = '001' try: table_service.update_entity(table_name=table_name, entity=value) except: table_service.insert_entity(table_name=table_name, entity=value) else: ret = dict() ret['result'] = "Please create the table!" return func.HttpResponse(json.dumps(ret), status_code=400) ret = dict() ret['result'] = "Success" return func.HttpResponse(json.dumps(ret), status_code=200) else: ret = dict() ret['result'] = "Please pass a name!!" return func.HttpResponse(json.dumps(ret), status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') req_body = req.get_json() try: webhook = req_body['webhook'] except: return func.HttpResponse("Invalid Call", status_code=400) try: ques = req_body['ques'] except: ques = findques() res = specifictxt(ques, '<div class="question-text latex">') if (res.strip() == ""): return func.HttpResponse("Invalid Question", status_code=404) syntaxes = parse(res) syntaxes = updat(syntaxes) information = extract(syntaxes) headers = {'Content-type': 'application/json'} values = {'content': "Today`s Challenge"} r = requests.post(url=webhook, json=values, headers=headers) for i in range(len(information) - 1): values = {'content': information[i]} r = requests.post(url=webhook, json=values, headers=headers) logging.info(r.status_code) time.sleep(0.25) options_txt = specifictxt( ques, '<div class="dp-solv-details solv-details clearfix mcq logged-out">') op_syn = parse(options_txt) op_syn = updat(op_syn) options = extract(op_syn) out = "Options Are - \n" for i in range(len(options) - 1): out = out + "\t# " + options[i] + "\n" values = {'content': out} r = requests.post(url=webhook, json=values, headers=headers) return func.HttpResponse(f"{out}")
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') # jokes from here: https://www.rd.com/jokes/computer/ tech_jokes = [ 'Don\'t use "beef stew" as a computer password. It\'s not stroganoff.', 'Why are iPhone chargers not called Apple Juice?!', 'Q. Why did the PowerPoint Presentation cross the road? A. To get to the other slide.', 'We\'ll we\'ll we\'ll...if it isn\'t autocorrect.' ] # jokes from here: https://bestlifeonline.com/funny-short-jokes/ silly_jokes = [ 'How do you throw a space party? You planet!', 'Why don\'t scientists trust atoms? Because they make up everything!', 'Q. Where are average things manufactured? A. The satisfactory.', 'Why doesn\'t the sun go to college? Because it has a million degrees!' ] random_jokes = tech_jokes + silly_jokes joke = req.params.get('joke') if not joke: try: req_body = req.get_json() except ValueError: pass else: joke = req_body.get('jokes') if joke == 'tech' or joke == 'silly': rtn_joke = getRandomJoke(tech_jokes if joke == 'tech' else silly_jokes) return func.HttpResponse(rtn_joke, status_code=200) else: rtn_joke = getRandomJoke(random_jokes) return func.HttpResponse(rtn_joke, status_code=200)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') url = req.params.get('url') if not url: try: req_body = req.get_json() except ValueError: pass else: url = req_body.get('url') if url: if is_url_image(url): logging.info( 'guessed from content header that the URL is for an image...') returnObject = {} try: returnObject["description"] = getImageDescription(url) returnObject["tags"] = getImageTags(url) except ComputerVisionErrorException as e: return func.HttpResponse(e.message, status_code=400) # bodyString = json.dumps(returnObject) return func.HttpResponse(body=json.dumps(returnObject), status_code=200, mimetype='application/json') else: logging.warn( 'guessed from content header that the URL is NOT for an image...' ) return func.HttpResponse( body= "URL specified is wrong, not pointing to an img (png/jpeg/jpg)", status_code=400) else: return func.HttpResponse( "Please pass a name on the query string or in the request body", status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('HTTP trigger function processed a request.') # Get Image base64 uri and convert it to png try: req_body = req.get_json() except ValueError: return func.HttpResponse("Error: HTTP Request Body is empty", status_code=400) img_url = req_body['imgURL'] path = Path.cwd() cnn_model = load_learner(path=path, file="model.pkl") if img_url: header, img_b64_data = img_url.split(",", 1) with open("alphabet.png", "wb") as f: try: f.write(base64.b64decode(img_b64_data)) except Exception: return func.HttpResponse( f"Error: Unable to parse data url in request body", status_code=400) # Load up the image and predict alphabet img = open_image("alphabet.png") prediction = cnn_model.predict(img) class_idx = prediction[1].item() predicted_alpha = ALPHABETS[class_idx] logging.info(f"Predicted Alphabet: {ALPHABETS[class_idx]}") else: return func.HttpResponse( f"Error: Request body must have field `imgURL` that contains base64 image uri", status_code=400) res = {"Predicted Alphabet": predicted_alpha} headers = {"Access-Control-Allow-Origin": "*"} return func.HttpResponse(json.dumps(res), mimetype="application/json", headers=headers)
def get(req: func.HttpRequest) -> func.HttpResponse: request: Optional[Union[ContainerGet, Error]] = None if req.get_body(): request = parse_request(ContainerGet, req) if isinstance(request, Error): return not_ok(request, context="container get") if request is not None: metadata = get_container_metadata(request.name, StorageType.corpus) if metadata is None: return not_ok( Error(code=ErrorCode.INVALID_REQUEST, errors=["invalid container"]), context=request.name, ) info = ContainerInfo( name=request.name, sas_url=get_container_sas_url( request.name, StorageType.corpus, read=True, write=True, delete=True, list=True, ), metadata=metadata, ) return ok(info) containers = get_containers(StorageType.corpus) container_info = [] for name in containers: container_info.append( ContainerInfoBase(name=name, metadata=containers[name])) return ok(container_info)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') weight = req.params.get('weight') if not weight: try: req_body = req.get_json() except ValueError: pass else: weight = req_body.get('weight') if weight: #Create recipe dictionary recipe = { "brine time" : str( round(int (weight) * 2.4, 2)) + " hours", "salt" : str(round(int (weight) * 0.05, 2)) + " cups", "water" : str(round(int (weight) * 0.06, 2)) + " gallons", "brown sugar" : str( round(int (weight) * 0.13, 2) ) + " cups", "shallots" : str( round(int (weight) * 0.2, 2)), "garlic" : str( round(int (weight) * 0.4, 2)) + " cloves", "whole peppercorns" : str( round (int (weight) * 0.13, 2)) + " tablespoons", "dried juniper berries" : str( round(int (weight) * 0.13, 2)) + " tablespoons", "fresh rosemary" : str( round(int (weight) * 0.13, 2)) + " tablespoons", "thyme" : str( round(int (weight) * 0.06, 2)) + " tablespoons", "roast time" : str(round(int (weight) * 15, 2)) + " minutes", } recipe_json = json.dumps(recipe) return func.HttpResponse(recipe_json, status_code=200) else: return func.HttpResponse( "This HTTP triggered function executed successfully. Pass a weight in the query string or in the request body for a personalized response.", status_code=200 )
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') if req.method == "GET": return func.HttpResponse("¯\_(ツ)_/¯", status_code=200) elif req.method == "POST": data = req.get_json() new_event_dataframe = pd.json_normalize(data) #connect to azure storage client connect_str = os.environ["sgeventactivity_STORAGE"] blob_service_client = BlobServiceClient.from_connection_string( connect_str) container_client = blob_service_client.get_container_client( "sgeventdata") blob_client = container_client.get_blob_client("sgEventDataHOOK.csv") #download the current csv file and convert bytes datastream to pandas dataframe try: download_stream = blob_client.download_blob() s = str(download_stream.readall(), "utf-8") old_event_data = StringIO(s) current_event_dataframe = pd.read_csv(old_event_data) #concat old and new dataframes, drop duplicates then upload to azure combined_dataframe = pd.concat( [new_event_dataframe, current_event_dataframe]) combined_data = combined_dataframe.to_csv(index=False) blob_client.upload_blob(combined_data, overwrite=True) #if the blob file does not exist create a new one except ResourceNotFoundError as e: new_event_data = new_event_dataframe.to_csv(index=False, header=True) blob_client.upload_blob(new_event_data) return func.HttpResponse("(~_^)", status_code=200)
def main(req: func.HttpRequest) -> func.HttpResponse: id = req.params.get('id') request = req.get_json() if request: try: url = "MyMongoDbConnectionString" # TODO: Update with appropriate MongoDB connection information client = pymongo.MongoClient(url) database = client['legolasprojectdb'] collection = database['advertisements'] filter_query = {'_id': ObjectId(id)} update_query = {"$set": eval(request)} rec_id1 = collection.update_one(filter_query, update_query) return func.HttpResponse(status_code=200) except: 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.') name = req.params.get('name') logging.info(test.addInt(1, 1)) if not name: try: req_body = req.get_json() except ValueError: pass else: name = req_body.get('name') if name: return func.HttpResponse( f"Hello, {name}. This HTTP triggered function executed successfully." ) else: return func.HttpResponse( "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.", status_code=200)
def main(req: func.HttpRequest) -> func.HttpResponse: id = req.params.get('id') request = req.get_json() if request: try: url = "mongodb://*****:*****@az-dev-nu-course2-dba.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@az-dev-nu-course2-dba@" # TODO: Update with appropriate MongoDB connection information client = pymongo.MongoClient(url) database = client['az-dev-nu-course2-db'] collection = database['advertisements'] filter_query = {'_id': ObjectId(id)} update_query = {"$set": eval(request)} rec_id1 = collection.update_one(filter_query, update_query) return func.HttpResponse(status_code=200) except: 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: id = req.params.get('id') request = req.get_json() if request: try: url = "mongodb://*****:*****@db-ae50100a-d375-47d4-b021-5db05c787e89.documents.azure.com:10255/?ssl=true&replicaSet=globaldb" # TODO: Update with appropriate MongoDB connection information client = pymongo.MongoClient(url) database = client['azure'] collection = database['advertisements'] filter_query = {'_id': ObjectId(id)} update_query = {"$set": eval(request)} rec_id1 = collection.update_one(filter_query, update_query) return func.HttpResponse(status_code=200) except: 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( 'UpdateOperationStatus: Python HTTP trigger function processed a request.' ) try: req_body = req.get_json() except ValueError: pass else: subscription_id = req_body.get('subscription_id') operation_id = req_body.get('operation_id') plan_id = req_body.get('plan_id') quantity = req_body.get('quantity') success = req_body.get('success') api = azure_marketplace_api() if api.update_operation_status(subscription_id, operation_id, plan_id, quantity, success): return func.HttpResponse("updated") else: return func.HttpResponse("Failed. See logs for details", status_code=500)
async def main(req: func.HttpRequest) -> func.HttpResponse: logging.info( 'ResolveBearer: Python HTTP trigger function processed a request.') try: req_body = req.get_json() except ValueError: pass else: marketplace_token = req_body.get('bearer') authentication_token = req_body.get('authentication_token') if marketplace_token: api = azure_marketplace_api() data = api.resolve_to_obj(marketplace_token) easy_auth = get_easy_auth_info(authentication_token) retval = resolve_bearer_result(data, easy_auth) json_string = json.dumps(retval, default=lambda o: o.__dict__) return func.HttpResponse(json_string, mimetype='application/json') else: return func.HttpResponse( "Please pass the authentication_token for the resolve in the request body", status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') ciphertext = req.params.get('ciphertext') if not ciphertext: logging.info('No parameters found, checking body...') try: req_body = req.get_json() except ValueError: logging.info('No info found in request body') else: ciphertext = req_body.get('ciphertext') if ciphertext: rot13 = str.maketrans( "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm") translated = str.translate(ciphertext, rot13) return func.HttpResponse(f"Translation: {translated}") else: return func.HttpResponse( "Please pass a ciphertext on the query string or in the request body", status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse: id = req.params.get('id') request = req.get_json() if request: try: url = "mongodb://*****:*****@neighborly3399.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@neighborly3399@" # TODO: Update with appropriate MongoDB connection information client = pymongo.MongoClient(url) database = client['neighborlydb'] collection = database['advertisements'] filter_query = {'_id': ObjectId(id)} update_query = {"$set": eval(request)} rec_id1 = collection.update_one(filter_query, update_query) return func.HttpResponse(status_code=200) except: 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: id = req.params.get('id') request = req.get_json() if request: try: url = os.environ['CosmosDbConnection'] client = pymongo.MongoClient(url) database = client['neighborlydb'] collection = database['advertisements'] filter_query = {'_id': ObjectId(id)} update_query = {"$set": eval(request)} rec_id1 = collection.update_one(filter_query, update_query) return func.HttpResponse(status_code=200) except: 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('Starting bulk insert.') ret = dict() table_name = req.headers.get('name') values = req.get_json() if table_name: retrieved_secret = getConnectionString() table_service = TableService(connection_string=retrieved_secret.value) batch = TableBatch() for i in range(0, len(values['rows'])): batch.insert_entity(values['rows'][i]) table_service.commit_batch(table_name, batch) ret['result'] = "Success" return func.HttpResponse(json.dumps(ret), status_code=200) else: ret['result'] = 'Error' return func.HttpResponse(json.dumps(ret), status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse: id = req.params.get('id') request = req.get_json() if request: try: url = "mongodb://*****:*****@thestorageaccount.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@thestorageaccount@" # TODO: Update with appropriate MongoDB connection information client = pymongo.MongoClient(url) database = client['appdatabase'] collection = database['advertisements'] filter_query = {'_id': ObjectId(id)} update_query = {"$set": eval(request)} rec_id1 = collection.update_one(filter_query, update_query) return func.HttpResponse(status_code=200) except: 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.') logging.info(f"Headers: {req.headers}") logging.info(f"Params: {req.params}") logging.info(f"Route Params: {req.route_params}") logging.info(f"Body: {req.get_body()}") output = {"values": []} name = req.params.get('name') if not name: try: req_body = req.get_json() output = run(req_body) except ValueError: pass else: name = req_body.get('name') if name: return func.HttpResponse(f"Hello {name}!") else: return func.HttpResponse(json.dumps(output), mimetype='application/json')
def main(req: func.HttpRequest) -> func.HttpResponse: id = req.params.get('id') request = req.get_json() if request: try: url = "mongodb://*****:*****@myneighborly-db.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@myneighborly-db@" client = pymongo.MongoClient(url) database = client['myneighborly-db'] collection = database['advertisements'] filter_query = {'_id': ObjectId(id)} update_query = {"$set": eval(request)} rec_id1 = collection.update_one(filter_query, update_query) return func.HttpResponse(status_code=200) except: 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("Summation function processed a request") retVal = {} statusCode = 200 try: req_body = req.get_json() values = req_body.get('values') if not values: raise Exception("programmatic exception") else: summation = 0.0 for value in values: summation += value retVal["summation"] = summation except Exception: retVal[ "message"] = "Please pass a numeric array of \"values\" in order to sum them!" statusCode = 400 return func.HttpResponse(json.dumps(retVal), mimetype="application/json", status_code=statusCode)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info("Python HTTP trigger function processed a request.") req_body = req.get_json() project_info = parse_devops_ticket(req_body) if project_info["ticket_description"] is None: logging.info("Translation is not necessary.") return func.HttpResponse("Translation is not necessary.") translation = translate(project_info["ticket_description"]) if isinstance(translation, KeyError): return func.HttpResponse(f"Key Error: {translation}") logging.info("Updating ticket") update_devops_workitem( text=translation, organization_url=project_info["baseUrl"], project_id=project_info["project_id"], work_item_id=project_info["work_item_id"], ) return func.HttpResponse(translation)
def main(req: func.HttpRequest) -> func.HttpResponse: # Defer the import until triggered so that failure is attached to the response try: import Functions except ModuleNotFoundError: # Try the Azure Functions name if the "natural" name was missing import __app__.Functions as Functions if req.method == "POST": try: payload = req.get_json() except Exception as ex: return func.HttpResponse(f"Invalid request: {ex}", status_code=400) try: return func.HttpResponse( execute_function(Functions, payload), mimetype="application/json", ) except Exception as ex: return func.HttpResponse(f"Invalid request: {ex}", status_code=422) return func.HttpResponse(get_all_metadata(Functions), mimetype="application/json")
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') # This assumes a raw binary upload try: request_body = req.get_body() image= Image.open(io.BytesIO(request_body)) except IOError: return func.HttpResponse( "Bad input. Unable to cast request body to an image format.", status_code=400 ) text = pytesseract.image_to_string(image) if text: return func.HttpResponse(f"{text}") else: return func.HttpResponse( "Please pass an image in the request body", status_code=400 )
def main(req: func.HttpRequest) -> func.HttpResponse: id = req.params.get('id') request = req.get_json() if request: try: url = "mongodb://*****:*****@apollo-udacity-cosmosdb.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@apollo-udacity-cosmosdb@" client = pymongo.MongoClient(url) database = client['neighborly-db'] collection = database['advertisements'] filter_query = {'_id': ObjectId(id)} update_query = {"$set": eval(request)} rec_id1 = collection.update_one(filter_query, update_query) return func.HttpResponse(status_code=200) except: 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)