Ejemplo n.º 1
0
async def main(req: func.HttpRequest) -> func.HttpResponse:
    # create api client
    line_api = AioLineBotApi(
        channel_access_token="<YOUR CHANNEL ACCESS TOKEN>")

    # get events from request
    parser = WebhookParser(channel_secret="<YOUR CHANNEL SECRET>")
    events = parser.parse(req.get_body().decode("utf-8"),
                          req.headers.get("X-Line-Signature", ""))

    for ev in events:
        # reply echo
        await line_api.reply_message(
            ev.reply_token, TextMessage(text=f"You said: {ev.message.text}"))

    # 200 response
    return func.HttpResponse("ok")
Ejemplo n.º 2
0
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    sess = get_inference_session()

    data = req.params.get("data")

    if data is not None:
        try:
            data = json.loads(data)
            data = inference.predict(sess, np.array([data], dtype=np.float32))
            data = np.argmax(data[0], axis=1)
            data = data.tolist()[0]
        except ValueError:
            data = None

    return func.HttpResponse(json.dumps(inference.format_results(sess, data),
                                        indent=4),
                             status_code=200)
Ejemplo n.º 3
0
def main(req: azf.HttpRequest, file: bytes) -> azf.HttpResponse:
    """
    Read a blob (bytes) and respond back (in HTTP response) with the number of
    bytes read and the MD5 digest of the content.
    """
    assert isinstance(file, bytes)

    content_size = len(file)
    content_md5 = hashlib.md5(file).hexdigest()

    response_dict = {'content_size': content_size, 'content_md5': content_md5}

    response_body = json.dumps(response_dict, indent=2)

    return azf.HttpResponse(body=response_body,
                            mimetype="application/json",
                            status_code=200)
Ejemplo n.º 4
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    return func.HttpResponse(json.dumps([
        {
            'action': 'talk',
            'text':
            'Welcome to the emotion reporting hotline. Please enter 1 if you are happy, or 2 if you are sad.',
            'bargeIn': True,
        },
        {
            'action': 'input',
            'eventUrl':
            [f'https://{req.headers["host"]}/api/emotion_feedback'],
            'maxDigits': 1,
            'timeOut': 10,
        },
    ]),
                             mimetype='application/json')
Ejemplo n.º 5
0
def main(req: func.HttpRequest):

    challenge = req.get_json()

    client = get_client(os.environ[env_constants.MONGO_CONNECTION_STRING])

    # Get the owner id from the JSON an add "enrolledIndividuals"
    owner_id = challenge["ownerId"]

    # Add the enrolled individual to the JSON in the ObjectId form.
    challenge["enrolledIndiviuals"] = [ObjectId(owner_id)]

    # Insert the challenge
    insert_one(client, mongo_constants.GAMIFYRE_DB,
               mongo_constants.collections.CHALLENGE, challenge)

    return func.HttpResponse(status_code=200)
Ejemplo n.º 6
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    random_image, image_name = fetch_image.fetch_random_image()
    image_coded = image_helper.encode_image_base64(random_image)
    image_id = image_helper.get_hash(image_name)

    json_response = {
        'id': image_id,
        'encoded_image': image_coded
    }

    return func.HttpResponse(
        json.dumps(json_response),
        headers={'Access-Control-Allow-Origin': '*'},
        status_code=200,
        mimetype='application/json'
    )
Ejemplo n.º 7
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    image_url = req.params.get('img')
    top = 20
    try:
        top = int(req.params.get('top'))
    except:
        pass
    logging.info('Image URL received: ' + image_url)
    logging.info('with top n: ' + str(top))
    results = predict_image_from_url(image_url, top)

    headers = {
        "Content-type": "application/json",
        "Access-Control-Allow-Origin": "*"
    }

    return func.HttpResponse(json.dumps(results), headers=headers)
Ejemplo n.º 8
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    data = req.get_json()
    user_query = data['message']
    preprocessed_query = map_request.preprocess_query(user_query, format='str')
    store_url = constants.Globals.SEARCH_URL.format(
        preprocessed_query.replace(' ', '%20'))
    response = {
        "reply":
        "Kanskje det er dette du leter etter?",
        "buttons": [{
            "button_type": "link",
            "label": constants.Globals.STORE_NAME,
            "value": store_url
        }]
    }
    return func.HttpResponse(body=json.dumps(response),
                             mimetype="application/json")
Ejemplo n.º 9
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    file_path = ""
    df = pd.read_excel('file_path')
    output = df.to_csv(index=False)

    STORAGEACCOUNTNAME = "*****"
    STORAGEACCOUNTKEY = "*****"
    blobService = BlockBlobService(account_name=STORAGEACCOUNTNAME,
                                   account_key=STORAGEACCOUNTKEY)

    blobService.create_blob_from_text('csv', 'test2.csv', output)
    name = {"test": "test"}

    return func.HttpResponse(
        json.dumps(name),
        mimetype="application/json",
    )
Ejemplo n.º 10
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('HTTP trigger function processing a request')

    img_gif = Image.open(BytesIO(req.get_body()))
    img_byte_arr = BytesIO()
    img_gif.save(img_byte_arr,
                 format='webp',
                 save_all=True,
                 duration=img_gif.info['duration'],
                 optimize=True,
                 quality=100)

    logging.info('HTTP trigger function processed gif to webp')

    return func.HttpResponse(body=img_byte_arr.getvalue(),
                             mimetype='image/webp',
                             status_code=200)
Ejemplo n.º 11
0
def main(req: func.HttpRequest,
         documents: func.DocumentList) -> func.HttpResponse:
    if not documents:
        logging.warning("document not found")
        return "Bad robot! :("
    else:
        logging.info("Found Document, Description=%s", documents[0].to_json())

        resp_headers = {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "Get, Post, Options"
        }

        response = func.HttpResponse(headers=resp_headers,
                                     body=documents[0].to_json())

        return response
Ejemplo n.º 12
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    # Get the request body from previous step in Logic App
    req_body = req.get_json()
    file_name = req_body.get('fileName')
    file_content = req_body['fileContent']['$content']

    # Convert file content to bytes
    file_data = base64.decodebytes(file_content.encode())

    # Generate date time object of the run
    dt = datetime.datetime.now().strftime('%Y-%m-%dT%H-%M-%S')

    # Extract original PDF file name
    pdf_prefix_file_name = ''.join(file_name.split('.pdf')[:1]) + '_'

    # Open multi-page PDF file
    with io.BytesIO(file_data) as open_pdf_file:
        read_pdf = PyPDF2.PdfFileReader(open_pdf_file)

        # Extract each page and write out to individual files
        pdf_list = []
        for i in range(read_pdf.numPages):
            output = PyPDF2.PdfFileWriter()
            output.addPage(read_pdf.getPage(i))

            # Temporarily write PDF to disk
            temp_pdf_fn = pdf_prefix_file_name + str(i + 1) + '_' + dt + str(
                ".pdf")
            with open(temp_pdf_fn, "wb") as outputStream:
                output.write(outputStream)

            # Read back in the PDF to get the bytes-like version
            with open(temp_pdf_fn, 'rb') as temp_pdf_file:
                file_data = base64.b64encode(temp_pdf_file.read()).decode()

                # Record the filename and the bytes-like data of single-page PDF
                ind_pdf = {'fileName': temp_pdf_fn, 'fileContent': file_data}

            pdf_list.append(ind_pdf)

    # Finalize response object
    respObj = {'individualPDFs': pdf_list}

    return func.HttpResponse(body=json.dumps(respObj))
Ejemplo n.º 13
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        driver = "{ODBC Driver 17 for SQL Server}"
        server = "kumulus-paoli.database.windows.net"
        database = "test_database"
        user = "******"
        password = "******"
        conn = f"""Driver={driver};Server=tcp:{server},1433;Database={database};
        Uid={user};Pwd={password};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"""

        params = urllib.parse.quote_plus(conn)
        conn_str = 'mssql+pyodbc:///?autocommit=true&odbc_connect={}'.format(
            params)
        engine = create_engine(conn_str, echo=False)
        Model.metadata.create_all(engine)
        session = Session(engine)
    except:
        return func.HttpResponse("Failed to connect")

    name = req.params.get('name')
    description = req.params.get('description')
    price = req.params.get('price')

    if not name:
        return func.HttpResponse("No name given :(")

    if session.query(Product).filter(Product.name == name).first() is None:
        return func.HttpResponse("Name do not exist :(")
    else:
        if not description:
            if not price:
                return func.HttpResponse("No enough stuff :(")
            else:
                session.query(Product).filter(Product.name == name).update(
                    {"price": price}, synchronize_session=False)
        else:
            if not price:
                session.query(Product).filter(Product.name == name).update(
                    {"description": description}, synchronize_session=False)
                return func.HttpResponse("Product updated ):)")
            else:
                session.query(Product).filter(Product.name == name).update(
                    {"description": description}, synchronize_session=False)
                session.query(Product).filter(Product.name == name).update(
                    {"price": price}, synchronize_session=False)
                return func.HttpResponse("Product updated ):)")

    return func.HttpResponse("Product updated ):)")
Ejemplo n.º 14
0
def main(req: func.HttpRequest) -> func.HttpResponse:

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

    def create_welcome_card():
        # Create card
        blue_background = "https://images.unsplash.com/photo-1557683311-eac922347aa1?ixlib=rb-1.2.1&w=1000&q=80"
        bot_icon = "https://i.ibb.co/dmmWb6s/Lingo-Bot-Bare.png"

        card = AdaptiveCard(backgroundImage=blue_background)
        card.add([
            Container(), "<",
            Image(url=bot_icon,
                  spacing="medium",
                  height="130px",
                  horizontalAlignment="center"),
            TextBlock(text=f"Hey! I'm Lingo",
                      spacing="Large",
                      weight="bolder",
                      size="ExtraLarge",
                      horizontalAlignment="center",
                      color="light"),
            TextBlock(text="Your Personal Digital Banking Assistant",
                      weight="bolder",
                      size="Large",
                      horizontalAlignment="center",
                      wrap="true",
                      color="light"),
            TextBlock(text="I can speak more than 70 languages!",
                      weight="bolder",
                      size="Medium",
                      horizontalAlignment="center",
                      wrap="true",
                      color="light"),
            ActionSet(spacing="Large"), "action",
            ActionSubmit(
                title="Help",
                data={"action": "help"},
                iconUrl="https://img.icons8.com/ios/50/000000/help.png")
        ])
        return card.to_json()

    result = create_welcome_card()
    return func.HttpResponse(body=result, status_code=200)
Ejemplo n.º 15
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Getting the results.')

    return_data = {}

    votes = db.votes

    Bob = 0
    Eric = 0
    Marry = 0
    Others = 0
    Total = 0

    Total = votes.find().count()
    Bob = votes.find({'VotedFor': 'Bob'}).count()
    Eric = votes.find({'VotedFor': 'Eric'}).count()
    Marry = votes.find({'VotedFor': 'Marry'}).count()
    Others = Total - Bob - Eric - Marry

    return_data['TotalVotes'] = Total
    return_data['Bob'] = Bob
    return_data['Eric'] = Eric
    return_data['Marry'] = Marry
    return_data['Others'] = Others
    
    return_data = json.dumps(return_data)

    teamsWebHook = os.environ['TeamsWebHook']

    teamsMsg = pymsteams.connectorcard(teamsWebHook)
    teamsMsg.title("Demo Voting Results !")

    teamsSection = pymsteams.cardsection()
    teamsSection.addFact('Timestamp:', datetime.datetime.now().strftime("%m/%d/%Y-%H:%M:%S"))
    teamsSection.addFact('TotalVotes :', Total)
    teamsSection.addFact('Bob :', Bob)
    teamsSection.addFact('Eric :', Eric)
    teamsSection.addFact('Marry :', Marry)
    teamsSection.addFact('Others :', Others)

    teamsMsg.addSection(teamsSection)
    teamsMsg.text("Greeting !")
    teamsMsg.send()

    return func.HttpResponse(body=return_data ,status_code=200)
Ejemplo n.º 16
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('HTTP trigger function processed a request, calling rss2csv')

    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:
        logmsg = f"Processing url: {url}\n"
        interesting = [
            'client-ip', 'x-forwarded-for', 'accept-language', 'user-agent'
        ]
        for key, value in req.headers.items():
            if key in interesting:
                logmsg += f"{key}: {value}\n"
        logging.info(logmsg)

        rc = fetchRSSandOutputCSV(url)

        if 'SLACK_WEBHOOK' in os.environ:
            # if configured send update to Slack room
            slackmsg = f"Feed: {url}\n"
            if 'x-forwarded-for' in req.headers:
                ip = req.headers['x-forwarded-for']
                start = time.time()
                geo = geoIP(ip)
                delta = int((time.time() - start) * 1000)
                logging.info(f"time-geoip: {delta} ms")
                slackmsg += f"Geo: {geo}\n"
            start = time.time()
            stat = requests.post(os.environ['SLACK_WEBHOOK'],
                                 json={'text': slackmsg})
            delta = int((time.time() - start) * 1000)
            logging.info(f"time-slack: {delta} ms")
            logging.info(f"Slack post response {stat.status_code}")
        return rc
    else:
        return func.HttpResponse(
            "Please pass 'url' parameter in query request or body.\n",
            status_code=400)
Ejemplo n.º 17
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    req_body = req.get_json()

    br = mechanize.Browser()
    br.set_handle_robots(False)
    br.open("https://relief.jogno.net/login")

    br.select_form(nr=0)
    br["email"] = req_body.get('email')
    br["password"] = req_body.get('password')
    br.submit()

    page = br.open("https://relief.jogno.net/newnotes/")

    rundate = req_body.get('year') + '-' + req_body.get(
        'month') + '-' + req_body.get('day')
    newurl = page.geturl() + '?d=' + rundate
    br.open(newurl)
    br.select_form(nr=0)
    try:
        temp = br.form.find_control(name="Jog[distance][]")
    except:
        req_body = req.get_json()
        br.form.new_control('text', 'Jog[distance][]', {'value': ''})
        br.form.new_control('text', 'Jog[hour][]', {'value': ''})
        br.form.new_control('text', 'Jog[minute][]', {'value': ''})
        br.form.new_control('text', 'Jog[second][]', {'value': ''})
        br.form.new_control('text', 'Jog[memo][]', {'value': ''})
        br.form.fixup()

    br["Jog[distance][]"] = req_body.get('distance')
    br["Jog[hour][]"] = req_body.get('hour')
    br["Jog[minute][]"] = req_body.get('minute')
    br["Jog[second][]"] = req_body.get('second')
    br["diary"] = req_body.get('diary')
    br["Jog[memo][]"] = req_body.get('memo')
    # br["image_file[]"] = ""
    # br["condition[weight]"] = ""
    # print(br.form)
    br.submit()

    return func.HttpResponse(
        "This HTTP triggered function executed successfully.", status_code=200)
def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        # log the encoded message
        logging.info(f"Encoded body: {req.get_body()}")
        # decode hex values
        message = unquote(req.get_body().decode())
        # log the decoded message
        logging.info(f"Decoded body: {message}")
        # split the message at markdown= or text=
        content_type, message = message.split('=', 1)
        # split the message at the timestamp
        time_stamp, message = message.split('|')
        # remove extraneous white space characters from the timestamp
        time_stamp = time_stamp.replace("+", " ")
        # convert the message from a string to a datetime object
        time_stamp = datetime.strptime(time_stamp.strip(), '%m/%d/%Y %I:%M:%S %p')
        # convert from UTC to EST
        time_stamp = time_stamp - timedelta(hours=4)
        # assemble the final message
        message = f"{content_type}={time_stamp.strftime('%m/%d/%Y %I:%M:%S %p')} | {message.strip()}"
        # correct space formatting
        message = message.replace(" ", "+")
        # Teams does not support em dash characters in webhooks
        message = message.replace("—", "--")
        # Teams does not support % characters in webhooks
        message = message.replace("%", "percent")
        # Teams does not support ° characters in webhooks
        message = message.replace("°", "degress ")
        # PRTG converts '<' to '{' so revert
        message = message.replace("{", "<")
        # PRTG converts '>' to '}' so revert
        message = message.replace("}", ">")
        # log the final message
        logging.info(f"Final body: {message}")
        if message:
            post = requests.post(
                WEBEX_WEBHOOK_URL, data=message.encode('utf-8'),
                headers={'Content-Type': 'application/x-www-form-urlencoded'}
            )
            return func.HttpResponse(post.reason, status_code=post.status_code)
    except Exception as e:
        # log the exception
        logging.info(f"Error: {e}")
        # log the final message for debugging
        logging.info(f"Final body: {message}")
Ejemplo n.º 19
0
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}!")
    else:
        return func.HttpResponse(
            print (response)
            "Please pass a name on the query string or in the request body",
            status_code=400
        )
Ejemplo n.º 20
0
def main(req: func.HttpRequest, rating: func.DocumentList) -> str:
    logging.info('Python HTTP trigger function processed a request.')
    logging.info(req.params["ratingId"])
    if not rating:
        logging.warning("rating item not found")
        return func.HttpResponse(f"Not foound", status_code=404)
    else:
        logging.info("Found rating item, Notes=%s", rating[0]['UserNotes'])
        data = {
            "id": rating[0]["id"],
            "userId": rating[0]["userId"],
            "ProductId": rating[0]["ProductId"],
            "timestamp": rating[0]["timestamp"],
            "locationName": rating[0]["locationName"],
            "Rating": rating[0]["Rating"],
            "UserNotes": rating[0]["UserNotes"],
        }
        return json.dumps(data)
def main(req: func.HttpRequest) -> func.HttpResponse:
    num_of_rows = req.params.get('num_of_rows')
    num_of_cols = req.params.get('num_of_cols')

    start = time()
    tmpl = PageTemplate(BIGTABLE_ZPT)

    data = {}
    for i in range(num_of_cols):
        data[str(i)] = i

    table = [data for x in range(num_of_rows)]
    options = {'table': table}

    data = tmpl.render(options=options)
    latency = time() - start

    return func.HttpResponse(str(latency))
Ejemplo n.º 22
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    id = req.route_params.get("id")
    logging.info(f"Requesting crowdedness for restaurant: {id}")

    total_capacity = random.randint(10, 20)
    crowdedness = random.random()
    current_visitors = int(total_capacity * crowdedness)
    days_visitors = random.randint(4 * current_visitors, 12 * current_visitors)

    return func.HttpResponse(
        body=json.dumps(
            {
                "crowdedness": crowdedness,
                "last_hour": current_visitors,
                "last_day": days_visitors,
            }
        )
    )
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    post = req.get_json()
    logging.info(post['video'])
    # get messages via url
    youtube_messages = get_chat_replay('https://www.youtube.com/watch?v=xxxxxxxxxxx')
    twitch_messages = get_chat_replay('https://www.twitch.tv/videos/xxxxxxxxx')

    # get messages via id
    youtube_messages = get_youtube_messages('xxxxxxxxxxx')
    twitch_messages = get_twitch_messages('xxxxxxxxx')

    
    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
    )
Ejemplo n.º 24
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    temp_image = "/tmp/image.jpeg"
    image_data = req.get_body()
    f = open(temp_image, 'wb')
    f.write(image_data)
    print("Image Written to", temp_image)

    predicted_bus_number = bus_project.check_bus_number(temp_image)
    if predicted_bus_number != "-1" and predicted_bus_number != "-2":
        predict_string = "Bus " + predicted_bus_number + " is Coming Now!\n"
    elif predicted_bus_number == "-1":
        predict_string = "No Bus Detected in Image\n"
    else:
        predict_string = "Could Not Read Bus Number on Bus"

    return func.HttpResponse(predict_string, status_code=200)
Ejemplo n.º 25
0
def main(req: func.HttpRequest, doc:func.DocumentList) -> func.HttpResponse:
    
    logging.info('Python HTTP trigger function processed a request.')
 
    users_json = []

    for user in doc:
        user_json = {
           "id": user['id'],
           "name": user['name']
        }
        users_json.append(user_json)

    return func.HttpResponse(
            json.dumps(users_json),
            status_code=200,
            mimetype="application/json"            
    )
Ejemplo n.º 26
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    tweet_id = req.params.get('tweet_id')
    logging.info(f'Tweet id: {tweet_id}.')
    try:
        status = api.get_status(tweet_id,
                                include_entities=True,
                                tweet_mode='extended')
        (valid, resp) = filter_tweet(status)
        if not valid:
            return resp
        response = process_image(status)
        if response is None:
            return func.HttpResponse(f"No image attached")
        return post_tweet(response, tweet_id)
    except Exception as e:
        logging.error(f'btw: {e}')
        raise e
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    # getting request params
    urls = getParam("urls", req)
    entity_id = getParam("entity_id", req)
    org_id = getParam("org_id", req)

    # creating in&out in storage

    # preparing data from storage

    # invokation of the queuers
    for current in urls:
        urllib.request.urlopen(current)

    # return function result
    return func.HttpResponse("done")
Ejemplo n.º 28
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    TAG = "convert_excel_to_csv.__init__.main"

    LogHelper.log_info(TAG,
                       'Python HTTP trigger function processed a request.')

    request_params = req.get_json()

    convert_helper = ConvertHelper()
    blob_account = os.environ["BlobStorageAccount"]
    blob_key = os.environ["BlobStorageKey"]
    convert_helper.connect_to_blob(blob_account, blob_key)

    convert_helper.convert_excel_to_csv(request_params)
    blob_name = request_params['blob_input']['blobname']
    message_string = "Convert blob %s successfully" % blob_name
    return_json = "{ \"message\" : \"%s\" }" % message_string
    return func.HttpResponse(return_json, status_code=200)
Ejemplo n.º 29
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    cnx = mysql.connector.connect(user=DB_USER,
                                  password=DB_PASSWORD,
                                  host=DB_HOST,
                                  port=3306,
                                  database=DB_NAME)
    cursor = cnx.cursor()
    cursor.execute("SELECT nombre FROM `personas`")
    results = cursor.fetchall()

    resp = ""

    for row in results:
        resp += '\n >> ' + str(row[0])

    return func.HttpResponse(f"Personas:{resp}")
Ejemplo n.º 30
0
def main(req: func.HttpRequest, documentsin: func.DocumentList,
         documentsout: func.Out[func.Document]) -> func.HttpResponse:

    body = list()
    body_bag = {"messages": body}
    for doc in documentsin:
        d = dict()
        for keep in ['user_name', 'key', 'color', 'effect', 'text']:
            d[keep] = doc[keep]
        body.append(d)
        logger.info(body)

        doc['read'] = 'T'
        documentsout.set(func.Document.from_dict(doc))
        body_bag = {"messages": body}
    return func.HttpResponse(body=json.dumps(body_bag),
                             headers={"Content-type": "application/json"},
                             status_code=200)