Returning All Query Results to Alexa Skill - python

I am developing a Web Service using python that would operate as the backend logic for a custom Alexa Skill. I am using the flask, flask-ask(Alexa Skill Kit), and MySQL extensions to develop this Web Service.
This Alexa Skill would allow users to reserve parking spots, check if lots are full, and find parking spots.
I also have a local database where all parking related information is stored.
I'm having an issue where I am only able to return the first result of a query.
Here is the code for one of my intents:
'''This is a Web Service for the *** Parking skill'''
author__ = '*****'
import logging
from flaskext.mysql import MySQL
from flask import Flask, render_template
from flask_ask import Ask, statement, question
mysql = MySQL()
app = Flask(__name__)
app.config.from_object(__name__)
app.config['MYSQL_DATABASE_USER'] = '*****'
app.config['MYSQL_DATABASE_PASSWORD'] = '*****'
app.config['MYSQL_DATABASE_DB'] = '*****'
app.config['MYSQL_DATABASE_HOST'] = '*****'
mysql.init_app(app)
ask = Ask(app, "/")
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
#ask.intent('AvailableParking')
def available(occupancy):
#converts the inputted occupancy variable into all caps, to match the DB schema
occupancy = occupancy.upper()
#creates cursor variable that connects to DB
cursor = mysql.connect().cursor()
#connects to db and executes SQL query that displays all garages where the OCCUPANCY field matches the users slot input (OPEN OR CLOSED)
cursor.execute("SELECT GARAGE_NAME FROM GARAGES WHERE OCCUPANCY = %s", (occupancy,))
#returns the first row of the query results
data = cursor.fetchone()
data = data[0]
return statement(data)
This works as intended. Alexa says "Lot A" when triggering the intent, even thought there are 3 parking lots in total.
I thought to use the MySQL method cursor.fetchall() in place of cursor.fetchone, like so:
data = cursor.fetchall()
return statement(data)
But I receive the error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/flask_ask/core.py", line 767, in _flask_view_func
result = self._map_intent_to_view_func(self.request.intent)()
File "/home/ngrok/ngrok/FETCHALLRETURN", line 46, in available
return statement(data)
File "/usr/local/lib/python2.7/dist-packages/flask_ask/models.py", line 188, in __init__
super(statement, self).__init__(speech)
File "/usr/local/lib/python2.7/dist-packages/flask_ask/models.py", line 51, in __init__
'outputSpeech': _output_speech(speech)
File "/usr/local/lib/python2.7/dist-packages/flask_ask/models.py", line 402, in _output_speech
xmldoc = ElementTree.fromstring(speech)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1311, in XML
parser.feed(text)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1651, in feed
self._parser.Parse(data, 0)
TypeError: Parse() argument 1 must be string or read-only buffer, not tuple
{"context": {"System": {"apiAccessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJhdWQiOiJodHRwczovL2FwaS5hbWF6b25hbGV4YS5jb20iLCJpc3MiOiJBbGV4YVNraWxsS2l0Iiwic3ViIjoiYW16bjEuYXNrLnNraWxsLmY2NDViYTgxLTZmM2QtNDZlNi04MDM1LTI1MTBlYTg5ODNkYiIsImV4cCI6MTUzMTE1MzIxMiwiaWF0IjoxNTMxMTQ5NjEyLCJuYmYiOjE1MzExNDk2MTIsInByaXZhdGVDbGFpbXMiOnsiY29uc2VudFRva2VuIjpudWxsLCJkZXZpY2VJZCI6ImFtem4xLmFzay5kZXZpY2UuQUhFRzdPQ0RLN01TNkdFWkhYTUlTUlFXRkNNTktKVUxHTk1GTkdSVFlWSFk0WFZMSkVWUzRZTFFGSjVFSDVRR0YyREVYQTVVVjI0UzJHNFJNU0tYWFpHVjZFRDY0RktJWkpHVVQyWURVRlZZTzVLVUZLSENDUzVPWUdPTDI3NUU1QjRGRU1XTk5VRVAzUkxPSENFNzRUVTdLSDZBIiwidXNlcklkIjoiYW16bjEuYXNrLmFjY291bnQuQUg0T1FZSVBSQ1NRVEZaR1pIWkVRSFpCU1RISDI1VUE2MjYyNFY1WTdDWTdCSzZDWU9RWjdJN1BMV0s0Tzc0RFpVSzRBMkw0MlpQUjRQV1lFRlJIVzY2MlRPVlVEM1BCT1c0UkxRSjNFSFpVWllTTzM2VkM0NkMzRVdHT1ZPRFlVSVNWNzNPRVRHUkJEUkFTRjc0NEg3VFcyR0pYM01FN0kyWVNGQkFTNjNOUUFGNzNCVUJHUlRSSU5ZQ0tIM0dPWjZZVjNVS0tRM0xZMlFJIn19.WPKBopJc_WAxHJdHsYg6bgqYhEahsIzwCsBm3EUPWdKmqzSmjPTudJH-58a0VndsGc32CxARDhmShy1RxsSGUwacXr-Hb1sMlkHcrKV-I6dUFA9JXgGOHP92WyDBe4NcmZd2evEHGSAlWr7mW3cPpjUKax7INsSWqbziNGneP5DWV7T6FA6S3G-h5BBiX5rVx2SBcfYZ-1ixCom5GvQa8Xe77CGg2zwugd9oIvib6Q9JLfYQrmWcg9qBYfnKfaQsQNYg6I_OJ5fL5YcCmfq5FtfPpPL-k3UWvSiZwFqwch-AUNzu35csmLw9BF3JbVXPxPr-o70OlVWxmOeVEnYAzA", "apiEndpoint": "https://api.amazonalexa.com", "application": {"applicationId": "amzn1.ask.skill.f645ba81-6f3d-46e6-8035-2510ea8983db"}, "device": {"deviceId": "amzn1.ask.device.AHEG7OCDK7MS6GEZHXMISRQWFCMNKJULGNMFNGRTYVHY4XVLJEVS4YLQFJ5EH5QGF2DEXA5UV24S2G4RMSKXXZGV6ED64FKIZJGUT2YDUFVYO5KUFKHCCS5OYGOL275E5B4FEMWNNUEP3RLOHCE74TU7KH6A", "supportedInterfaces": {}}, "user": {"userId": "amzn1.ask.account.AH4OQYIPRCSQTFZGZHZEQHZBSTHH25UA62624V5Y7CY7BK6CYOQZ7I7PLWK4O74DZUK4A2L42ZPR4PWYEFRHW662TOVUD3PBOW4RLQJ3EHZUZYSO36VC46C3EWGOVODYUISV73OETGRBDRASF744H7TW2GJX3ME7I2YSFBAS63NQAF73BUBGRTRINYCKH3GOZ6YV3UKKQ3LY2QI"}}}, "request": {"error": {"message": "An exception occurred while dispatching the request to the skill.", "type": "INVALID_RESPONSE"}, "locale": "en-US", "reason": "ERROR", "requestId": "amzn1.echo-api.request.a7699e3a-71b3-4cf5-8d23-63e45c86a957", "timestamp": "2018-07-09T15:20:12Z", "type": "SessionEndedRequest"}, "session": {"application": {"applicationId": "amzn1.ask.skill.f645ba81-6f3d-46e6-8035-2510ea8983db"}, "new": false, "sessionId": "amzn1.echo-api.session.7c96f3f4-c78f-4c10-9535-9e1e9fe8a21e", "user": {"userId": "amzn1.ask.account.AH4OQYIPRCSQTFZGZHZEQHZBSTHH25UA62624V5Y7CY7BK6CYOQZ7I7PLWK4O74DZUK4A2L42ZPR4PWYEFRHW662TOVUD3PBOW4RLQJ3EHZUZYSO36VC46C3EWGOVODYUISV73OETGRBDRASF744H7TW2GJX3ME7I2YSFBAS63NQAF73BUBGRTRINYCKH3GOZ6YV3UKKQ3LY2QI"}}, "version": "1.0"}
{}
127.0.0.1 - - [09/Jul/2018 15:20:12] "POST / HTTP/1.1" 200 -
Query results are returned in a tuple which apparently is not able to be returned straight to Alexa without some formatting.
Does anyone know how I can return ALL results of a query to Alexa ?

I'm writing an app with same extensions as you except for sqlalchemy and using sqlite. My queries come back as objects so I either :
Have a method that loops through the query object to construct a statement for alexa (great for complex msg)
Pass the object to the flask-ask templates.yaml and use a jinja for loop (good for a simple query)

Related

Identifying Location of Error: TypeError: 'NoneType' object is not subscriptable (Python)

I am relatively new to Python, and I am attempting to follow a tutorial on how to build a web application. All my code checks out, however, when I attempt to access the app via localhost, I get the following error: "TypeError: 'NoneType' object is not subscriptable." I'm not sure what the error is referring to in my code, and I would appreciate any pointers as to how to identify and resolve this error.
Code:
Service.py
from models import ToDoModel
class ToDoService:
def __init__(self):
self.model = ToDoModel()
def create(self, params):
self.model.create(params["Title"], params["Description"])
models.py
import _sqlite3
class Schema:
def __init__(self):
self.conn = _sqlite3.connect('todo.db')
self.create_user_table()
self.create_to_do_table()
# Why are we calling user table before to_do table?
# What happens if we swap them?
def create_to_do_table(self):
query = """
CREATE TABLE IF NOT EXISTS "Todo" (
id INTEGER PRIMARY KEY,
Title TEXT,
Description TEXT,
_is_done boolean,
_is_deleted boolean,
CreatedOn Date DEFAULT CURRENT_DATE,
DueDate Date,
UserId INTEGER FOREIGNKEY REFERENCES User(_id)
);
"""
self.conn.execute(query)
def create_user_table(self):
query = """
CREATE TABLE IF NOT EXISTS "User" (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Email TEXT,
CreatedOn Date default CURRENT_DATE
);
"""
self.conn.execute(query)
class ToDoModel:
TABLENAME = "TODO"
def __init__(self):
self.conn = _sqlite3.connect('todo.db')
def create(self, Title, description):
query = f'insert into {self.TABLENAME} ' \
f'(Title, Description) ' \
f'values ("{Title}","{description}")'
result = self.conn.execute(query)
return result
app.py
from flask import Flask, request, jsonify
from Service import ToDoService
from models import Schema
app = Flask(__name__)
#app.route("/todo", methods=["GET", "POST"])
def create_todo():
return jsonify(ToDoService().create(request.get_json()))
if __name__ == "__main__":
Schema()
app.run(debug=True)
Error:
Traceback (most recent call last):
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/micahwilcox/PycharmProjects/todo-flask/venv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/micahwilcox/PycharmProjects/todo-flask/app.py", line 10, in create_todo
return jsonify(ToDoService().create(request.get_json()))
File "/Users/micahwilcox/PycharmProjects/todo-flask/Service.py", line 10, in create
ToDoModel().create(params["Title"], params["Description"])
TypeError: 'NoneType' object is not subscriptable
I am interfacing with the program using Python Shell with the following code:
requests.post("http://localhost:5000/todo",
json={"Title":"my first todo",
"Description":"my first todo"})
requests.get("http://localhost:5000/todo",
json={"Title":"my first todo",
"Description":"my first todo"})
The error comes when I attempt to go to localhost:5000/todo on my browser.
Thanks in advance for any help I receive.
Based on your comment:
The error comes when I attempt to go to localhost:5000/todo on my browser
The error happens when your browser calls the endpoint with a GET request with no body. Then request.get_json() method will return None, and thus params is None and you're trying to do None["Title"] which is obviously an error.

Getting Error TypeError: create_task() takes from 1 to 2 positional arguments but 3 were given while creating google cloud tasks

from google.cloud import tasks_v2
import json
GCP_PROJECT='test'
GCP_LOCATION='europe-west6'
def enqueue_task(queue_name, payload, process_url):
client = tasks_v2.CloudTasksClient()
parent = client.queue_path(GCP_PROJECT, GCP_LOCATION, queue_name)
task = {
'app_engine_http_request': {
'http_method': 'POST',
'relative_uri': process_url
}
}
if payload is None:
return False
payload = json.dumps(payload)
converted_payload = payload.encode()
task['app_engine_http_request']['body'] = converted_payload
return client.create_task(parent, task)
I keep getting the following error when I try to create a Google Cloud Task.
The Google App Engine Runtime used is python38. It was working fine but suddenly after deployment using gcp CLI it does not work now.
Traceback (most recent call last):
File "/layers/google.python.pip/pip/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/layers/google.python.pip/pip/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/layers/google.python.pip/pip/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/layers/google.python.pip/pip/flask/_compat.py", line 39, in reraise
raise value
File "/layers/google.python.pip/pip/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/layers/google.python.pip/pip/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/srv/main.py", line 153, in sync_request
queue_response = queues.enqueue_task(
File "/srv/queues.py", line 28, in enqueue_task
return client.create_task(parent, task)
TypeError: create_task() takes from 1 to 2 positional arguments but 3 were given
The same thing has just happened to me (on live server :/). Turns out, the Cloud Tasks library has changed significantly with version 2.0.0. You can read what you need to do to upgrade here.
Your problem is in this line:
client.create_task(parent, task)
The updated library requires to either use a dictionary as a positional argument or use keyword arguments. So this should fix it:
client.create_task(parent=parent, task=task)
EDIT: Looking at your code now that I've made this work for myself, you will also have to change the following:
# Before
parent = client.queue_path(GCP_PROJECT, GCP_LOCATION, queue_name)
# After
parent = client.queue_path(project=GCP_PROJECT, location=GCP_LOCATION, queue=queue_name)
and
# Before
'http_method': 'POST',
# After
'http_method': tasks_v2.HttpMethod.POST,

Google Cloud Tasks ImportError: cannot import name 'resource_pb2'

Trying to use the google provided python sample code for adding a task to a Google Cloud Tasks queue. The docs from google are here: https://cloud.google.com/tasks/docs/creating-appengine-tasks
When I attempt to execute the endpoint I get the following error:
ImportError: cannot import name 'resource_pb2'
Has anyone seen an similar issue and know how to get past this?
Thanks in advance for your time :)
-nathan
I have tried adding google-cloud-tasks, google-api, google-cloud to my requirements.txt and running pip install google-cloud-tasks in my virtual environment. I also tried using this code:
from google.cloud import tasks_v2beta3
The results were the same
This is the example code provided by google. I have sent a note to them to let them know the example code does not work.
from google.cloud import tasks_v2
from google.protobuf import timestamp_pb2
# Create a client.
client = tasks_v2.CloudTasksClient()
# TODO(developer): Uncomment these lines and replace with your values.
# project = 'my-project-id'
# queue = 'my-appengine-queue'
# location = 'us-central1'
# payload = 'hello'
# Construct the fully qualified queue name.
parent = client.queue_path(project, location, queue)
# Construct the request body.
task = {
'app_engine_http_request': { # Specify the type of request.
'http_method': 'POST',
'relative_uri': '/example_task_handler'
}
}
if payload is not None:
# The API expects a payload of type bytes.
converted_payload = payload.encode()
# Add the payload to the request.
task['app_engine_http_request']['body'] = converted_payload
if in_seconds is not None:
# Convert "seconds from now" into an rfc3339 datetime string.
d = datetime.datetime.utcnow() + datetime.timedelta(seconds=in_seconds)
# Create Timestamp protobuf.
timestamp = timestamp_pb2.Timestamp()
timestamp.FromDatetime(d)
# Add the timestamp to the tasks.
task['schedule_time'] = timestamp
# Use the client to build and send the task.
response = client.create_task(parent, task)
print('Created task {}'.format(response.name))
return response
I expected the code to add a task to the Cloud Tasks Queue, instead I get this stack trace:
Traceback (most recent call last)
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/athena_nsunderman/posttest-get/main.py", line 134, in TestQueueInsert
from google.cloud import tasks_v2
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/google/cloud/tasks_v2/__init__.py", line 19, in <module>
from google.cloud.tasks_v2 import types
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/google/cloud/tasks_v2/types.py", line 22, in <module>
from google.cloud.tasks_v2.proto import cloudtasks_pb2
File "/home/athena_nsunderman/virtualenv/recharge/lib/python3.5/site-packages/google/cloud/tasks_v2/proto/cloudtasks_pb2.py", line 18, in <module>
from google.api import resource_pb2 as google_dot_api_dot_resource__pb2
ImportError: cannot import name 'resource_pb2'
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
This worked for me:
pip install -U googleapis-common-protos==1.5.10

Unable to get json web token from Flask

I have the below code for app.py:
from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
class User(object):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __str__(self):
return "User(id='%s')" % self.id
users = [
User(1, 'user1', 'abcxyz'),
User(2, 'user2', 'abcxyz'),
]
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
def authenticate(username, password):
user = username_table.get(username, None)
if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
return user
def identity(payload):
user_id = payload['identity']
return userid_table.get(user_id, None)
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'
jwt = JWT(app, authenticate, identity)
#app.route('/protected')
#jwt_required()
def protected():
return '%s' % current_identity
if __name__ == '__main__':
app.run()
When i try to make a post request to get the authentication token from Postman :
http://127.0.0.1:5000/auth
{
"username": "joe",
"password": "pass"
}
I get a peculiar error which i am not able to solve :
(flask-restful) C:\Users\bhatsubh\Projects\flask-restful>python Test.py
* Restarting with stat
* Debugger is active!
* Debugger PIN: 973-755-004
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/Sep/2017 13:38:08] "POST /auth HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1985, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\_compat.py"
, line 33, in reraise
raise value
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\_compat.py"
, line 33, in reraise
raise value
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask_jwt\__init_
_.py", line 115, in _default_auth_request_handler
username = data.get(current_app.config.get('JWT_AUTH_USERNAME_KEY'), None)
AttributeError: 'NoneType' object has no attribute 'get'
I have absolutely no idea what is going wrong. Can someone please help me with this?
make sure have set correct header
Content-Type:application/json
try curl for cross check
$ curl -H "Content-Type: application/json" -X POST -d '{ "username": "joe", "password": "pass" }' http://localhost:5000/auth
I suspect you’re being thrown off by this because there’s a bug in flask-jwt which is throwing up errors rather than providing proper feedback. So it’s hard to know what’s up.
If there are any header errors, it triggers errors rather than a proper response.
Dave B’s suggestion worked for me, setting the header with: Content-Type:application/json
I raised this with the developers, so hopefully, they can patch it up.
Look at https://github.com/vimalloc/flask-jwt-extended or https://github.com/vimalloc/flask-jwt-simple as alternatives to Flask-JWT. They are better designed, up to date, and still maintained (I am the author, so I am of course biased).
try this:
localhost:5000/auth
{ "username": "user1", "password": "abcxyz" }

WTForm not submitting to mysql - flush error

I'm completely stuck with the following error when submitting form data form into a mysql database, very grateful for any clues
I get this error:
"sqlalchemy.orm.exc.FlushError FlushError: Instance has a NULL identity key. If this is an auto-generated
value, check that the database table allows generation of new primary
key values, and that the mapped Column object is configured to expect
these generated values. Ensure also that this flush() is not
occurring at an inappropriate time, such aswithin a load() event."
the code is:
from flask import Flask, request,redirect,render_template,flash
from wtforms import Form, TextField, BooleanField
from wtforms.validators import Required
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:#127.0.0.1/Jungle'
class Sighting(db.Model):
__tablename__ = 'Animals'
animal_name = db.Column(db.String, primary_key = True)
animal_type = db.Column(db.String)
scary = db.Column(db.String)
class LoginForm(Form):
animal_name = TextField('Animal')
animal_type = TextField('Type')
scary = BooleanField('Scary')
#app.route('/login',methods = ['GET','POST'])
def login():
form = LoginForm()
if request.method == 'POST':
newanimal = Sighting(animal_name=form.animal_name.data,animal_type=form.animal_type.data,scary=form.scary.data)
db.session.add(newanimal)
db.session.commit()
return redirect('/thanks')
elif request.method == 'GET':
return render_template('login.html', form = form)
#app.route('/thanks',methods= ['GET'])
def thanks():
return render_template('thanks.html')
if __name__ == '__main__':
app.run(debug=True)
If I run something like this in the above code it works and successfully commits into the database:
#app.route('/submit',methods =['GET'])
def submit():
newanimal = Sighting(animal_name='frog',animal_type='amphibian', scary='No')
db.session.add(newanimal)
db.session.commit()
return render_template('thanks.html')
So it seems to be something to do with the form data. The MySQL table is:
CREATE TABLE `Animals` (
`animal_name` varchar(100) DEFAULT NULL,
`animal_type` varchar(100) DEFAULT NULL,
`scary` varchar(100) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8
The database table seems to auto-increment even when one of the failed submissions happens - when you put in a row manually that works its id is a few higher than than the previous one. There's also one row in the table with every field a null.
many thanks in advance!!
(forgive the odd naming schema - its adapted from a tutorial)
sqlalchemy.orm.exc.FlushError
FlushError: Instance <Sighting at 0x10c6552d0> has a NULL identity key. If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the mapped Column object is configured to expect these generated values. Ensure also that this flush() is not occurring at an inappropriate time, such aswithin a load() event.
Traceback (most recent call last)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/tomhalloran/TomDev/FlaskSkint/learnv3.py", line 29, in login
db.session.commit()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/scoping.py", line 149, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 765, in commit
self.transaction.commit()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 370, in commit
self._prepare_impl()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 350, in _prepare_impl
self.session.flush()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 1879, in flush
self._flush(objects)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 1997, in _flush
transaction.rollback(_capture_exception=True)
File "/Library/Python/2.7/site-packages/sqlalchemy/util/langhelpers.py", line 57, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 1967, in _flush
flush_context.finalize_flush_changes()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 387, in finalize_flush_changes
self.session._register_newly_persistent(other)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/session.py", line 1389, in _register_newly_persistent
% state_str(state)
FlushError: Instance <Sighting at 0x10c6552d0> has a NULL identity key. If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the mapped Column object is configured to expect these generated values. Ensure also that this flush() is not occurring at an inappropriate time, such aswithin a load() event.
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.
You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
You created the form, but unless I misread your code, you missed the step that actually populates the form with data from the POST (i.e. from request.form).

Categories

Resources