Exemple #1
0
 def test_from_directive_call(self):
     ask = Ask()
     fake_stream = _Field()
     fake_stream.__dict__.update({'token':'fake'})
     with patch('flask_ask.core.top_stream', return_value=fake_stream):
         from_buffer = ask._from_directive()
         self.assertEqual(fake_stream, from_buffer)
Exemple #2
0
 def __init__(self, lights_433_server):
     self.server = lights_433_server
     self.ask = Ask(self.server.app, '/switch_alexa')
     self.ask.intent('LightSwitch')(
         lambda location, operation:
             self.perform_switch(location, operation)
     )
     self.ask.intent('AMAZON.HelpIntent')(
         lambda: self.get_welcome_response()
     )
Usage:
Alexa, tell hello world to say hi to {firstname}
Alexa, ask hello world to say hi to {firstname}

Created by: Lee Assam
www.powerlearningacademy.com

Last Modified: 2018-09-02
'''

from flask import Flask, render_template
from flask_ask import Ask, statement, question

app = Flask(__name__)
ask = Ask(app, '/')


@ask.launch
def launch():
    welcome_text = render_template('welcome_text')
    return question(welcome_text)


@ask.intent('AMAZON.FallbackIntent')
def fallback():
    reprompt_text = render_template('ask_name_reprompt')
    return question(reprompt_text)


@ask.intent('HelloWorldIntent')
Exemple #4
0
def get_app():
    app = Flask(__name__)
    app.config.from_object('config.Config')
    redis_client.init_app(app)
    ask = Ask(app, '/alexa')
    return app
Exemple #5
0
from flask import Flask, render_template, redirect, request, url_for, jsonify, session
from flask_ask import Ask, statement, question
from flask_assets import Bundle, Environment
import time
from pyvcapi import *
from nsxapi import *
import configparser

app = Flask(__name__)
app.secret_key = "super secret key"
ask = Ask(app, "/hackathon")

env = Environment(app)
js = Bundle('js/clarity-icons.min.js', 'js/clarity-icons-api.js',
            'js/clarity-icons-element.js', 'js/custom-elements.min.js')
env.register('js_all', js)
css = Bundle('css/clarity-ui.min.css', 'css/clarity-icons.min.css')
env.register('css_all', css)


@app.route('/', methods=['GET', 'POST'])
def homepage():
    if request.method == "POST":
        attempted_username = request.form['username']
        print(attempted_username)
        attempted_password = request.form['password']
        print(attempted_password)
        if attempted_username == "admin" and attempted_password == "password":
            session['logged_in'] = True
            session['wrong_pass'] = False
            session['username'] = request.form['username']
Exemple #6
0
import logging
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
import sys
sys.path.insert(0, "..")

from opcua import Client
from opcua import ua

app = Flask(__name__)
ask = Ask(app, "/")

logging.basicConfig()
logging.getLogger("flask_ask").setLevel(logging.DEBUG)

client = Client("opc.tcp://localhost:4840")


@ask.launch
def new_Produktion():
    logging.info(
        "Read/Write variable with OPC-UA by Amazon Alexa voice command")
    welcome_msg = render_template('welcome')
    return question(welcome_msg)


@ask.intent("YesIntent")
def get_Job():
    client.connect()
    root = client.get_root_node()
    var = client.get_node(
Exemple #7
0
from flask import Flask
from flask_ask import Ask, statement, question, session
import json
import requests
import time
import unidecode

username = ''
password = ''

app = Flask(__name__)
ask = Ask(app, "/shower-thoughts-reader")


def get_headlines():
    user_pass_dict = {
        'user': username,
        'password': password,
        'api_type': 'json'
    }
    sess = requests.Session()
    sess.headers.update({'User-Agent': 'I am testing Alexa: ' + username})
    sess.post('https://www.reddit.com/api/login', data=user_pass_dict)

    time.sleep(1)

    url = 'https://reddit.com/r/showerthoughts/.json?limit=5'
    html = sess.get(url)
    data = json.loads(html.content.decode('utf-8'))

    titles = [
"""
A Flask-Ask based web app version of our Alexa skill
"""
import os
from flask import Flask, Blueprint, redirect, render_template
from flask_ask import Ask, statement, question
from btvpython.meetup import get_next_meetup

ASK_ROUTE = '/ask'
web = Blueprint('web', __name__)
ask = Ask(route=ASK_ROUTE)


@ask.launch
def welcome():
    return question(render_template('welcome'))\
        .reprompt(render_template('prompt'))


@ask.intent('GetNextEvent')
def get_next_event():
    meetup = get_next_meetup('btvpython')
    if meetup:
        return statement(render_template('next_event', **meetup))

    return statement(render_template('sorry'))


@web.route('/')
def default():
    return redirect('https://github.com/voutilad/alexa-btvpython')
Exemple #9
0
" " '''
Created between 06.05.2017 and 16.07.2017

@authors: phil, ck12, Delta4s2Cyclone
'''

from flask import Flask
from flask_ask import Ask, statement, question, session
from afinn import Afinn
import json
import requests
import operator
#import unidecode

app = Flask(__name__)
ask = Ask(app, "/worldnews")

# Sentiment Analysis with AFINN
afinn = Afinn()


# NYT functions
def get_headlinesHome():
    sess = requests.Session()
    url = "http://api.nytimes.com/svc/topstories/v2/home.json?api-key=3b9ad549cdbe4d2b9e8d14a03d67ef3e"
    html = sess.get(url)
    data = json.loads(html.content.decode('utf-8'))
    titles = []
    result = data['results']

    # announce new headline (e.g. "second headline:")
db.commit()

q = queue.Queue()
q.put("0.0")

ser1 = serial.Serial('/dev/rfcomm0', 9600)
ser2 = serial.Serial('/dev/rfcomm1', 9600)

print("it paired")

ino1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ino2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ino3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

app = Flask(__name__)
ask = Ask(app, "/switch")

print('------ ', datetime.now(),
      ' Program started')  #Will print when program initially runs

print("Waiting for data...")


# Sends the switch number, then a '-', then a '1' for high or a '0' for low
def switch1_on():  #Turns on switch 1
    print('switch 1 has turned on')
    ser1.write('<1-1>'.encode('utf-8'))


def switch1_off():  #Turns off switch 1
    print('switch 1 has turned off')
Exemple #11
0
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
import json
import requests
import time
import unidecode

app = Flask(__name__)

ask = Ask(app, "/xLuisApp")


@ask.launch
def start_skill():
    welcome_message = "Hello Luis How are you?"
    return question(welcome_message)


@ask.intent("GoodIntent")
def share_headlines():
    return statement("Thats good")


@ask.intent("BadIntent")
def no_intent():
    bye_text = "Okay..."
    return statement(bye_text)


if __name__ == "__main__":
    app.run(debug=True)
Exemple #12
0
#!/usr/bin/env pythonw

#################################
# TOTO Analyzer using Alexa 	#
# Goh Khee Teck			#
# pydot4 class			#
#################################

from toto_analyzer import get_past_results, get_last_drawn_num_rows
from flask import Flask
from flask_ask import Ask, statement, question

app = Flask(__name__)
ask = Ask(app, "/toto_analyzer")


@app.route("/")
def hompage():
    return """
		This is a tool developed as part of the 'Python for Data, Ops and Things' course.\n
		It collect and analyse data from Singapore pool.
		"""


@ask.launch
def start_skill():
    welcome_message = "Hello kheeteck, do you like to know the latest toto results ?"
    return question(welcome_message)


@ask.intent("YesIntent")
Exemple #13
0
from flask import Flask, Response, jsonify
from flask_ask import Ask, statement
from flask_assistant import Assistant, tell
from flask_cors import CORS
import meetup_utils

app = Flask(__name__)

app.config['ASSIST_ACTIONS_ON_GOOGLE'] = True

cors = CORS(app)
assist = Assistant(app, route='/google')
ask = Ask(app, route='/alexa')

@app.route('/<group_name>')
def group_details(group_name: str) -> Response:
    "xv"
    Returns general meetup group details
    """
    group = meetup_utils.get_group(group_name)
    return jsonify(meetup_utils.extract_details(group))


@app.route('/<group_name>/next')
def next_meetup_endpoint(group_name: str) -> Response:
    """
    Returns details on the next meetup for a group
    """
    group = meetup_utils.get_group(group_name)
    title, time, count = meetup_utils.next_meetup(group)
    return jsonify({'title': title, 'time': time, 'count': count})
Exemple #14
0
class Record:
    def __init__(self, name, brewery):
        self.name = name
        self.brewery = brewery

    def __str__(self):
        return '{} by {}'.format(self.name, self.brewery)


url = 'https://www.beeradvocate.com/lists/new/'
source = requests.get(url)
soup = bs.BeautifulSoup(source.text, 'lxml')

app = Flask(__name__)
ask = Ask(app, "/new-beer-toppers")


@ask.launch
def start_skill():
    return find_top_beers()


@ask.intent("YesIntent")
def find_top_beers():
    return statement(
        "Here are the top 10 rated beers added within the last year: {}".
        format(stringify_records(get_records())))


@ask.intent("NoIntent")
#Railway API - http://railwayapi.com/api/

from flask import Flask
from flask_ask import Ask, statement, question, session

import json
import requests
import time
import unidecode
import datetime

app = Flask(__name__)
ask = Ask(app, "/train_route")
api_key = '6dg3lgmg'


def date_convert(date):
    year1 = datetime.datetime.strptime(date, '%Y-%m-%d').year
    month1 = datetime.datetime.strptime(date, '%Y-%m-%d').month
    day1 = datetime.datetime.strptime(date, '%Y-%m-%d').day
    newdata1 = " "
    if (month1 < 10):
        newdate1 = retstr = "{}0{}{}".format(year1, month1, day1)
    else:
        newdata1 = "{}{}{}".format(year1, month1, day1)
    return newdate1


def get_live_train_status(trainnumber, doj):
    r = requests.get(
        "http://api.railwayapi.com/live/train/{}/doj/{}/apikey/{}/".format(
Exemple #16
0
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
import json
import requests
import time
import unidecode
import random
import pandas as pd

app = Flask(__name__)
ask = Ask(app, "/health")

list_of_challenges = [
    [
        'Complete 20 push-ups!',
        'https://previews.123rf.com/images/logo3in1/logo3in11609/logo3in1160900004/62275155-step-instruction-for-push-up-of-woman-cartoon-illustration-about-work-out-.jpg'
    ],
    [
        'Complete 10 squats!',
        'http://www.parallelcodemotifs.org/file/2018/05/quick_online_demo_of_the_squat_position.jpg'
    ],
    [
        'Go for a quick walk!',
        'https://s3.envato.com/files/246953810/1920x1080.jpg'
    ],
    [
        'Get up and stretch with some leg lunges',
        'https://cdn-img.health.com/sites/default/files/styles/large_16_9/public/1512670961/carrie-underwood-hot-moves-illustration.jpg?itok=iDs-LOX2&1512671216'
    ],
    [
        'Complete 3 neck rolls, both ways',
Exemple #17
0
from src import app
from flask import Flask, request, redirect, make_response, render_template
from flask_ask import Ask, statement, question, session
import requests
import json

ask = Ask(app, "/ipl")

url = "https://data.julep91.hasura-app.io/v1/query"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer db710c4b45facbfb0b422a58888bd7bf7b64781b1cbbfa1e"
}
query_match_result = '''{{
    "type": "select",
    "args": {{
        "table": "matches",
        "columns": [
            "winner"
        ],
        "where": {{
            "team1": {{
                "$eq": "{}"
            }},
            "team2": {{
                "$eq": "{}"
            }},
            "date":{{
                "$eq": "{}"
            }}
        }}
Exemple #18
0
from flask import Flask
from flask_ask import Ask, statement, question, session

import json
import requests
import time
import unidecode

app = Flask(__name__)
ask = Ask(app, "/reddit_reader")


def get_headlines():
    user_pass_dict = {
        'user': '******',
        'passwd': 'YOUR_REDDIT_PASSWORD',
        'api_type': 'json'
    }
    sess = requests.Session()
    sess.headers.update({'User-Agent': 'Alexa Test'})
    sess.post('https://www.reddit.com/api/login', data=user_pass_dict)
    time.sleep(1)
    url = 'https://reddit.com/r/programming/.json?limit=3'
    html = sess.get(url)
    data = json.loads(html.content.decode('utf-8'))
    titles = [
        unidecode.unidecode(listing['data']['title'])
        for listing in data['data']['children']
    ]
    title_info = ""
    count = 0
import requests
import logging
import json
import time

# Set global variables
name = 'Rodolfo'

log = logging.getLogger()
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
logging.getLogger("flask_ask").setLevel(logging.DEBUG)

# Create Flask, Ask apps
app = Flask(__name__)  # Standard Flask app
ask = Ask(app, "/reddit_python")  # App endpoint


# App route
@app.route("/")
def homepage():
    return "Hey there {}! Flask is running with no problems!".format(name)


# Alexa initial message (starting app...)
@ask.launch
def start_skill():
    welcome_msg = "Hi! Would you like to hear any Python toppics on Redit?"
    return question(welcome_msg)

Exemple #20
0
    host="localhost",  # your host, usually localhost
    user="******",  # your username
    passwd="12345678",  # your password
    db="userDb")  # name of the data base

####GLOBALS#### Should probably make this a class if we got time...
ingredients = []
steps = []
currentTitle = ""
currentStep = 0
recipeOptions = []
currentRecipe = 0
currentDoc = ""
#Flask App stuff
app = Flask(__name__)
ask = Ask(app, "/alexa_cooks")


#Returns wheter or not the table is empty
def dbEmpty():
    cur = db.cursor()
    cur.execute("SELECT * FROM user")
    result = cur.fetchall()
    print(result)
    return len(result) == 0


#Updates db, Inserts if empty, Updates if there is data
def updateDb():
    cur = db.cursor()
    global currentStep
Exemple #21
0
"""Faraday Control Center Alexa Skill"""
from flask import Flask
from flask_ask import Ask, statement, question
from faradayapi import get_workspaces, get_users, get_activities, get_vulns, get_vulns_count
import hackernewsapi
import netsecapi

APP = Flask(__name__)
ASK = Ask(APP, "/control_center")


@APP.route('/')
def homepage():
    """Default skill funcion"""
    return "Faraday Control Center Alexa Skill"


@ASK.launch
def start_skill():
    """Welcome skill"""
    welcome_message = 'Faraday Control Center is online'
    return question(welcome_message)


@ASK.intent("NoIntent")
def no_intent():
    """Abort skill"""
    bye_text = 'Faraday Control Center Shutting Down'
    return statement(bye_text)

import requests
import logging
import json
import time

# Set global variables
name = 'Rodolfo'

log = logging.getLogger()
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
logging.getLogger("flask_ask").setLevel(logging.DEBUG)

# Create Flask, Ask apps
app = Flask(__name__)  # Standard Flask app
ask = Ask(app, "/poke_info")  # App endpoint


# App route
@app.route("/")
def homepage():
    return "Hey there {}! Flask is running with no problems!".format(name)


# Alexa initial message (starting app...)
@ask.launch
def start_skill():
    welcome_msg = "Hi, would you like me to give you any Pokemon's info?"
    return question(welcome_msg)

import logging
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
import json
import requests
import time
import unidecode
app = Flask(__name__)
ask = Ask(app, "/news_reader")

logging.getLogger("flask_ask").setLevel(logging.DEBUG)


def get_headlines():
    user_pass_dict = {
        'user': '******',
        'passwd': '1234wasdf',
        'api_type': 'json'
    }
    sess = requests.Session()
    sess.headers.update({'User-Agent': 'I am testing Alexa: Adwait'})
    time.sleep(1)
    sess.post('https://www.reddit.com/api/login', data=user_pass_dict)
    url = 'https://www.reddit.com/r/worldnews/.json?limit=10'
    html = sess.get(url)
    data = json.loads(html.content.decode('utf-8'))
    titles = [
        unidecode.unidecode(listing['data']['title'])
        for listing in data['data']['children']
    ]
    titles = '...'.join([i for i in titles])
Exemple #24
0
# natalexa.py
# Margaret Gorguissian
# 8/16/2017

import logging
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
import astro.py

app = Flask(__name__)
ask = Ask(app, "/")
logging.getLogger("flask_ask").setLevel(logging.DEBUG)

@ask.launch
def launch():
    return ## get_new_fact() #TO CHANGE

@ask.intent(#'GetNewFactIntent') #TO CHANGE
def get_new_fact(): #TO CHANGE
    # EDIT
    return #TO CHANGE

@ask.intent('AMAZON.HelpIntent')
def help():
    help_text = render_template('help')
    return question(help_text).reprompt(help_text)

@ask.intent('AMAZON.StopIntent')
def stop():
    bye_text = render_template('bye')
    return statement(bye_text)
from flask import Flask
from flask_ask import Ask, statement, question
import json
import time
import requests
import unidecode



from my_weather import give
from playyoutube import youtubeBot
from aws_watcher import extractPrice

app = Flask(__name__)
ask = Ask(app,"/app_name")

@app.route('/')
def homepage():
    return "hi bro...your time has begin"


@ask.launch
def start_skill():
    welcome_message = "*******msg*****"
    return question(welcome_message)

@ask.intent("nikal")
def nikalab():
    return statement("jara hu")

Exemple #26
0
import logging, os
from flask import Flask
from flask_ask import Ask, request, session, question, statement
import paho.mqtt.client as mqtt

app = Flask(__name__)
ask = Ask(app, '/alexa')
client = mqtt.Client("kitchen")

#logging.getLogger('flask_ask').setLevel(logging.DEBUG)

mqtt_server = os.environ['MQTT_SERVER']


@app.route('/')
def homepage():
    return "Uh oh, spaghettios"


@ask.intent('KitchenOff')
def switch_off():
    client.publish("cmnd/home/kitchen/POWER", "off")
    speech_text = "Yes Dear"
    return statement(speech_text)


@ask.intent('KitchenOn')
def switch_on():
    client.publish("cmnd/home/kitchen/POWER", "on")
    speech_text = "Yes Dear"
    return statement(speech_text)
Exemple #27
0
class AlexaServer(object):

    def __init__(self, lights_433_server):
        self.server = lights_433_server
        self.ask = Ask(self.server.app, '/switch_alexa')
        self.ask.intent('LightSwitch')(
            lambda location, operation:
                self.perform_switch(location, operation)
        )
        self.ask.intent('AMAZON.HelpIntent')(
            lambda: self.get_welcome_response()
        )

    def match_location(self, location):
        """
        We will mutate the score a bit to add +0.1 to the jaro distance
        for starting with the same letter. Alexa's speech processing system
        really sucks at this.

        location -- the location to match against
        """
        if location:
            matches = []
            for switch_id, switch_func in self.server.switches.items():
                similarity = jaro(location, switch_id)
                if location[0].lower() == switch_id[0].lower():
                    similarity += 0.1
                matches += [(similarity, switch_id, switch_func)]
            matches.sort(key=lambda x: x[0], reverse=True)
            if matches[0][0] >= _MATCH_THRESHOLD:
                return matches[0][1:]
        raise ActionParseError("I didn't understand the location. "
                               "Could you please repeat?")

    def match_operation(self, operation):
        if operation.lower() in ('on', 'up', 'in'):
            return 'on'
        elif operation.lower() in ('off', 'down', 'out'):
            return 'off'
        raise ActionParseError("I didn't understand the operation. "
                               "Could you please repeat?")

    def perform_switch(self, location, operation):

        try:
            resolved_location = self.match_location(location or "")
            resolved_operation = self.match_operation(operation or "")
        except ActionParseError as ape:
            return question(str(ape)).simple_card(_CARD_TITLE, str(ape))

        switch_id, switch_func = resolved_location
        try:
            r = switch_func(resolved_operation)
            text = "%s %s!" % (
                switch_id.replace('_', ' ').title(), resolved_operation)
            status = int(r.status.split(' ')[0])
            if status < 200 or status > 299:
                raise Exception(status)
        except Exception:
            text = "I had problems communicating with your device!"
        return statement(text).simple_card(_CARD_TITLE, text)

    def get_welcome_response(self):
        text = "Ask me to turn your lights on and off!"
        return statement(text).simple_card(_CARD_TITLE, text)
from flask import Flask
from flask_ask import Ask, statement, question, session
from hackernews import HackerNews
import requests
import time
import unidecode
import os

app = Flask(__name__)
ask = Ask(app, "/hackernews_reader")
hn = HackerNews()


def get_posts():
    top_story_ids = hn.top_stories(limit=10)
    for story in top_story_ids:
        stories = hn.get_item(story)
    return stories
    #top_iter = hn.get_top_stories(limit=10) # get top 10 stories
    #top_iter = '... '.join([i for i in top_iter])
    #return top_iter


@app.route('/')
def homepage():
    return "Ay this ish working"


@ask.launch
def start_skill():
    welcome_message = 'Hi there, would you like to hear the top ten news stories from Hacker News?'
Exemple #29
0
""" Main intent handler for the button slam alexa skill
"""
from flask import Flask, render_template
from flask_ask import Ask, session, statement, question
from bs4 import BeautifulSoup as bs
import requests
# import boto3
# import logging

app = Flask(__name__)
ask = Ask(app)
# log = logging.getLogger()

MAIN_MENU_STATE = 'main_menu'
DILEMMA_STATE = 'dilemma'
# STAT_STATE = 'stat'

QUESTION_STATEMENT = 'question'
QUESTION_STATEMENT_REPROMPT = 'question_reprompt'
STATS_STATEMENT = 'stats'
STATS_STATEMENT_REPROMPT = 'stats_reprompt'
STARTING_STATEMENT = 'starting_statement'
STARTING_STATEMENT_REPROMPT = 'starting_statement_reprompt'
EXPLAIN_STATEMENT = 'explain_the_game'
EXPLAIN_STATEMENT_REPROMPT = 'explain_the_game_reprompt'
DONE_STATEMENT = 'done_playing'


@ask.launch
def launched():
    """ When the skill is first launched, present the user with the
Exemple #30
0
#!/usr/bin/env python3
# See Flask Ask
# https://flask-ask.readthedocs.io/en/latest/

from flask import Flask, json, render_template
from flask_ask import Ask, request, question, statement, context, audio

app = Flask(__name__)
ask = Ask(app, "/itsfriday")


#Health check
@app.route('/')
def homepage():
    return "Its Friday is online"


# Command to create audio:
# ffmpeg -y -i infile.mp3 -ar 16000 -ab 48k -codec:a libmp3lame -ac 1 -filter:a "volume=2" outfile.mp3

itsfriday = "https://PATH_TO_SOUND/itsfriday_48k.mp3"

# See here for SSML syntax
# https://developer.amazon.com/en-US/docs/alexa/custom-skills/speech-synthesis-markup-language-ssml-reference.html


@ask.launch
def launch():
    print("Intent: ItsFriday")
    return statement("<speak><audio src='" + itsfriday + "'/> </speak>")
from flask import Flask
from flask_ask import statement, question, Ask, session
import time
import os

app = Flask(__name__)
ask = Ask(app, "/webhook")


@ask.launch
def handle_launch():
    message = "Hello there, how can I help you ?"
    return question(message)


@ask.intent("AnimalInfoIntent")
def handle_animalInfoIntent():
    result = "This is demo joke on animals"
    return statement(result)


@ask.intent("AMAZON.FallbackIntent")
def handle_fallbackIntent():
    result = "Sorry, I couldn't get that, thank you"
    return statement(result)


if __name__ == '__main__':
    app.run(debug=True)
Exemple #32
0
from flask import Flask
from flask_ask import Ask, statement
from src.dmx_in_jail_status import dmx_status

app = Flask(__name__)
ask = Ask(app, '/alexa/dmx')


@ask.launch
def start_skill():
    message, jailbool = dmx_status()
    status = "Free as a bird!" if jailbool is False else 'In the clink.'
    return statement(message).simple_card("DMX Incarceration status:", status)


@ask.intent('Any')
def any_intent():
    return start_skill()


if __name__ in "__main__":
    app.run(debug=True, host='0.0.0.0')
Exemple #33
0
#Some errors exist
from flask import Flask
from flask_ask import Ask, statement, question, session
import json, urllib
import time
import requests
from nutritionix import Nutritionix

nix = Nutritionix(app_id="app_id", api_key="app")

app = Flask(__name__)
ask = Ask(app, "/food_name")


def get_info(food):
    url = "https://api.nutritionix.com/v1_1/search/food?results=0:10&fields=item_name,brand_name&appId=app_id&appKey=app_key"
    f = urllib.urlopen(url)
    values = json.load(f)
    f.close()
    results = []
    for i_n in values['hits']['i_n']['fields']:
        results.append[{
            values['hits']['i_n']['fields']['item_name'],
            values['hits']['i_n']['fields']['brand_name']
        }]
    results = '... '.join([i for i in results])
    return results


results = get_info("dosa")
print(results)