NameError: name 'ask' is not defined - python

problem with flask ask
#ask.launch issue
am having problem running my python flask script. I am using python 2.7, the error says:
File "C:\Users\user1\AppData\Local\Continuum\anaconda2\Lib\site-packages\hello_lumion.py", line 13, in #ask.launch NameError: name 'ask' is not defined
import logging
import os
from flask import request
from flask import Flask
from flask_ask import Ask, statement, request, context, session, question, version
import requests
#ask.launch
def welcome():
return statement ('Welcome to Foo')
app = Flask(__name__)
ask= Ask(app,"/")
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
#ask.intent("Hello")
def hello():
msg= "hello from lumion"
return statement (msg)
if __name__ == '__main__':
port = 9000
app.run(host='0.0.0.0', port=port)
app.run(debug=True)
any advice on how to overcome this issue?

You are calling ask before it is defined. In your code you have
#ask.launch # ask has not been made
def welcome():
return statement ('Welcome to Foo')
app = Flask(__name__)
ask= Ask(app,"/") # ask gets made here!
You will need to reorder it so when you call ask, it has been defined. Something like:
app = Flask(__name__)
ask= Ask(app,"/") # define it first
#ask.launch # now use it
def welcome():
return statement ('Welcome to Foo')

Related

Python Return multiple variables after pause in function

I have found a piece of flask: https://github.com/pratik55/Python-Flask-dynamic-update- code that dynamically updates the HTML, but it requires a function like time.time() - it outputs, pauses, and outputs again. I would like a custom function to do just this but not with a time value.
I tried something similar to this https://www.geeksforgeeks.org/g-fact-41-multiple-return-values-in-python/ but I could not put a pause in between each output.
The flask code looks like this:
from flask import Flask, jsonify, render_template, request
import webbrowser
import time
app = Flask(__name__)
#app.route('/_stuff', methods = ['GET'])
def stuff():
return jsonify(result=time.time())
#app.route('/')
def index():
return render_template('dy1.html')
if __name__ == '__main__':
app.run()
The result is just a question mark when I replace result=time.time() with something else unless its very explicit like result="hello"
Thanks

how to handle http errors in flask-classful?

I am using flask_classful, no doubt its an amazing extension. now i want to handle http errors like 404, 500 etc. i don't know how to do that in flask-classful. Please Help me !
from flask import Flask, render_template
from flask_classful import FlaskView, route
app = Flask(__name__)
friends = ({'1st' : 'honey', '2nd' : 'ayush'})
class HomeView(FlaskView):
route_base = '/'
def home(self):
return render_template('global.html', title='Flask Claasful')
#route('/new/')
def new_func(self):
return render_template('global.html', title='Flask Classy')
#route('/friends/')
def friends(self):
return friends
HomeView.register(app)
if __name__ == '__main__':
app.run()

python flask before_first_request_funcs

In my python3 flask application I would like to execute a couple of recurring tasks before the first request.
In order to achieve this, I want to make use of the#app.before_first_request_funcs.
Can anyone please give me an example usage of #app.before_first_request_funcs?
Here is my sample code:
import threading
import time
from flask import Flask
app = Flask(__name__)
def activate_job():
def run_job():
while True:
print("recurring task")
time.sleep(3)
thread = threading.Thread(target=run_job())
thread.start()
def activate_job2():
def run_job2():
while True:
print("recurring task2")
time.sleep(3)
thread = threading.Thread(target=run_job2())
thread.start()
#app.after_first_request(activate_job())
#app.before_first_request(activate_job2())
#app.route('/')
def home():
return {"action": "This has done something"}
if __name__ == '__main__':
print(app.before_first_request_funcs)
app.run()
As per the documentation, you should use #app.before_first_request to do what you want.
from flask import Flask
app = Flask(__name__)
def some_func(some_arg):
print('coucou')
# #app.before_first_request(some_func)
#app.route('/')
def home():
return {"action" : "This has done something"}
if __name__ == '__main__':
print(app.before_first_request_funcs)
app.run()
You can see the behavior of the method before_first_request_funcs that is not a decorator by commenting and uncommenting the decorator before_first_request.
If it is commented, it'll print an empty list, and if you uncomment the line, it'll return a list of one element containing the function some_func object (for me, it was [<function some_func at 0x0000021393A0AD90>]).

How does flask know which function to call for a specific web adress?

In the populair web framework flask a basic web page looks like this:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
I am pretty new to python and i was wondering how this exactly works. I get that # is a decorator that decorates the hello function but how does flask that is has to call the underlying hello funtion or even knows it exists, because the code does not run the hello function like this:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
hello()
When i am coding i like to know how something works before i just randomly accept anything. I searched my but off looking for an answer but could not find a pleasent answer. Also i looked in the source code but i was not able to find out how it works
So now the real question: How can i recreate something similair in plain python? So running a function without really calling it in the main code first.
Ps. Sorry for my bad english, it is not my main language.
app.route() remembers the URL ("/") and the function associated with it (hello). Later, app.run() can query that association and invoke hello.
How can i recreate something similair in plain python?
This program might give you an understanding of how hello() is invoked:
class Flask:
def __init__(self):
self.routes = {}
def route(self, path):
def wrapper(fn):
self.routes[path] = fn
return fn
return wrapper
def run(self):
# Networking code goes here.
# Suppose "/" comes in as a request, then this happens:
self.routes["/"]()
app = Flask()
#app.route("/")
def hello():
print("Inside hello")
return "Hello World!"
app.run()
Alternatively, you can examine the flask source: https://github.com/pallets/flask Specifically, app.route() is defined here: https://github.com/pallets/flask/blob/0.12.2/flask/app.py#L1054 and the call to hello() is here: https://github.com/pallets/flask/blob/0.12.2/flask/app.py#L1052

How can I make command line arguments visible to Flask routes?

I am using Flask to build a tool to view data locally in a browser. I want to pass the directory containing the data as a command line argument, and then pass it to the appropriate routing function to do the rendering.
This does what I want, but with global variables:
dataDir = None
def initializeData(pathname):
global dataDir
dataDir = pathname
#app.route('/')
def home():
# Use dataDir as desired
if __name__ == '__main__':
initializeData(sys.argv[1])
app = Flask(__name__)
app.run()
Is there a better way to communicate between the command line and my routes?
Your flask app has a config property. Also, this code will fail with a NameError. You want something like this:
import sys
from flask import Flask
app = Flask(__name__)
#app.route('/')
def home():
return 'You wanted {!r} directory'.format(app.config.get('some_setting'))
if __name__ == '__main__':
app.config['some_setting'] = sys.argv[1]
app.run()
Consider using app.config.from_json('config.json') so that you can configure your env parameters in a json file.

Categories