I'm designing a project in Flask with Python that utilizes IBM Watson's Speech-to-Text feature. All I'm trying to do for now is load a FLAC file (0001.flac), interpret the file through Watson, and print the results to my console. I have the following code written thus far (I replaced my username and password for the example):
from werkzeug import secure_filename
import pprint, json, os
from watson_developer_cloud import SpeechToTextV1
. . .
speech_to_text = SpeechToTextV1(
username='My username is here',
password='My password is here')
with open(os.path.join(os.path.dirname(__file__), '0001.flac'), 'rb') as audio_file:
speech_to_text.set_detailed_response(True)
outthis = speech_to_text.recognize(
audio_file, content_type='audio/flac', timestamps=True)
pprint.pprint(json.dumps(outthis.getResult(), indent=2))
And here is my output:
[2018-09-13 11:46:36,553] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\ehill\source\repos\FlaskWebProject1\FlaskWebProject1\FlaskWebProject1\views.py", line 31, in home
pprint.pprint(json.dumps(outthis.getResult(), indent=2))
AttributeError: 'DetailedResponse' object has no attribute 'getResult'
According to the Watson documentation (https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/python.html?python#introduction) I should be able to receive information through getResult on a DetailedResponse object. What am I doing wrong?
I am seeing the same thing from our CI environment, which runs "pip install" from a clean environment. It looks like a breaking changed introduced with watson_developer_cloud v2.0.0 (https://pypi.org/project/watson-developer-cloud/2.0.0/#changes-for-v2.0).
I've addressed for the time being by forcing version 1.7.1 until I can go look deeper at the code changes. It looks like it might be a small-ish change (from a response.get to a response.get_result, but I cannot be sure of that).
FYI - here's the list of breaking changes in 2.0 release: https://github.com/watson-developer-cloud/python-sdk/wiki/Migration
To adhere to PEP8 conventions for function and variable names, the getResult method was renamed to get_result in v2.0.
Related
I'm attempting to write a Lambda function in Golang (doing development on my MacBook with Docker Desktop running) following this quick-start. I perform the following steps:
Ran "sam init --runtime go1.x --name testing" to generate a function from the template.
Ran "make deps" to go get dependencies.
Ran "make build" to build the code that was generated to hello-world/hello-word.
Ran "sam local start-api".
Everything looks like it starts correctly:
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
2019-11-16 10:39:19 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
But when I curl the endpoint, I get a 502 and I see an error:
2019-11-16 10:39:23 Exception on /hello [HEAD]
Traceback (most recent call last):
File "/usr/local/Cellar/aws-sam-cli/0.31.0/libexec/lib/python3.7/site-packages/flask/app.py", line 2317, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/Cellar/aws-sam-cli/0.31.0/libexec/lib/python3.7/site-packages/flask/app.py", line 1840, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/Cellar/aws-sam-cli/0.31.0/libexec/lib/python3.7/site-packages/flask/app.py", line 1743, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/Cellar/aws-sam-cli/0.31.0/libexec/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/usr/local/Cellar/aws-sam-cli/0.31.0/libexec/lib/python3.7/site-packages/flask/app.py", line 1838, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/Cellar/aws-sam-cli/0.31.0/libexec/lib/python3.7/site-packages/flask/app.py", line 1824, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/Cellar/aws-sam-cli/0.31.0/libexec/lib/python3.7/site-packages/samcli/local/apigw/local_apigw_service.py", line 172, in _request_handler
route = self._get_current_route(request)
File "/usr/local/Cellar/aws-sam-cli/0.31.0/libexec/lib/python3.7/site-packages/samcli/local/apigw/local_apigw_service.py", line 236, in _get_current_route
raise KeyError("Lambda function for the route not found")
KeyError: 'Lambda function for the route not found'
2019-11-16 10:39:23 127.0.0.1 - - [16/Nov/2019 10:39:23] "HEAD /hello HTTP/1.1" 502 -
What am I missing?
Late to the party on this one and you've probably resolved it already. Without seeing any code, it looks like you've made a HEAD request, rather than a GET request and I suspect you have no route for the HEAD method, only GET.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Error description
I would fire up the server program, and fire a request (GET) at the path /test_connection which is the path used by the client to test the server IP address btw. The server would then respond by printing out the traceback below in the console, the one line in particular that I can't get my head around is NameError: name 'user_id' is not defined as the variable is not even included in the response function for the path /test_connection (connection_test()). I know the error is on the server side as it will print out 'INTERNAL SERVER ERROR: 500' on the client code, so I didn't feel the necessity to include the client code.
Additional info:
Python version: 3.7
OS: Windows 10
Server Library: Flask
Traceback from error:
Traceback (most recent call last):
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\sccre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "E:\USB Stick Files\Programming\Python\Chat Room Thingy\server.py", line 19, in connection_test
message_dict[user_id]
NameError: name 'user_id' is not defined
Server code
from flask import Flask, request
from threading import Thread
import json
app = Flask(__name__)
message_dict = {}
ids = -1
#app.route('/test_connection')
def connection_test():
global ids
print('Connection tested from: {}'.format(request.remote_addr))
ids += 1
id_sent = str(ids)
return '{}'.format(id_sent)
#app.route('/new_message', methods=['POST'])
def new_message():
global message_dict
message_text = request.form['message']
user_id = request.form['id']
try:
message_dict[user_id]['message'] = message_text
except:
message_dict[user_id] = None
message_dict[user_id]['message'] = message_text
return '0'
#app.route('/chat')
def chat():
return json.dumps(message_dict)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Any help with this would be greatly appreciated.
Oscar.
Okay, The code is working completely fine to me.
Try one of the following :
1.Change your current File ( copy the contents to another )
2.Make the variable global.
3.Run the file directly from command prompt/shell (sometimes helpful)
4.Make sure your interpreter is ok
I have spent quite a bit of time stying to resolve this issue, i have googled and gone through posts with no success. I have a python script which works just fine on my macOsx computer, but i needed to run the script online so i am using digitalOcean for that.
I have an HTTP request, where i post data using postman to a Flask Application
#app.route('/addtransaction', methods = ['POST'])
def add_transaction():
data = request.get_json()
private = account.get_private_key()
public = account.get_public_key()
transaction = account.create_transaction(data)
string_transaction = str(transaction)
signature = ecdsa.sign(string_transaction, private, curve=curve.secp256k1,
hashfunc=ecdsa.sha256)
index = blockchain.add_transaction(public, transaction, signature,
string_transaction)
#Broadcast the transaction to the Peer Network
#First create the transaction object
trans_object = {'sender_id': public,
'transaction': transaction,
'signature': signature,
'string_transaction': string_transaction }
#Then broadcast using the Transaction Publisher we created above
peerServer.broadcast_transaction(trans_object, transaction_pu)
is_valid = ecdsa.verify(signature, string_transaction, public,
curve.secp256k1, ecdsa.sha256)
transaction_id = transaction['transaction_id']
response = {'message': f'Transaction id: {transaction_id} will be
added to block {index}',
'transaction_details': string_transaction, 'signature_valid':
is_valid }
return jsonify(response), 201
I get the error during the Broadcast Transaction method when i try to run the jsondumps - Method below
def broadcast_transaction(self, transaction, publisher):
j_transaction = json.dumps(transaction, sort_keys=True)
publisher.send_json(j_transaction)
print(f'Just broadcasted transaction: {j_transaction}')
return
I get the error TypeError: Object of type 'Point' is not JSON serializable
Full report:
Traceback (most recent call last):
File "/home/matshidiso/blockchainProjects/blockchain/myprojectenv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/matshidiso/blockchainProjects/blockchain/myprojectenv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/matshidiso/blockchainProjects/blockchain/myprojectenv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/matshidiso/blockchainProjects/blockchain/myprojectenv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/matshidiso/blockchainProjects/blockchain/myprojectenv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/matshidiso/blockchainProjects/blockchain/myprojectenv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "pythonBlockchain.py", line 330, in add_transaction
peerServer.broadcast_transaction(trans_object, transaction_pu)
File "pythonBlockchain.py", line 211, in broadcast_transaction
j_transaction = json.dumps(transaction, sort_keys=True)
File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'Point' is not JSON serializable
I am confused because this same script runs just fine on my personal macbook without errors, which leads me to think that perhaps the problem is with the operating system. What am i missing here?
Is there differences running a python script on a macbook and ubuntu server?
I'm running a flask app with python, part of which uses XML data retrieved from a third-party API. I use minidom to parse the XML within the python script.
Relevant python code:
from xml.dom import minidom
import requests
usa_xml = requests.get(URL_HERE)
usa_parsed = minidom.parseString(usa_xml.content)
The script goes on to locate and display values from the XML. Running the python script on my local machine, everything works as it should. Having put a repository up on pythonanywhere, the parsing fails with the same XML data.
Error traceback:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.4/dist-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/jshorty/OwlWire/owlwire.py", line 65, in select
usa_parsed = minidom.parseString(usa_xml.content)
File "/usr/lib/python3.4/xml/dom/minidom.py", line 1970, in parseString
return expatbuilder.parseString(string)
File "/usr/lib/python3.4/xml/dom/expatbuilder.py", line 925, in parseString
return builder.parseString(string)
File "/usr/lib/python3.4/xml/dom/expatbuilder.py", line 223, in parseString
parser.Parse(string, True)
xml.parsers.expat.ExpatError: no element found: line 29, column 7
Since it's failing with the same XML that would work otherwise, it doesn't seem like this is an issue with the XML itself. I'm stumped at where to start looking for the problem- I'm using all the default modules pre-installed on pythonanywhere, could this be an issue of different versions of minidom?
The error is always at line 29, column 7, so here is a link to one instance of the XML I'm accessing: http://ebird.org/ws1.1/data/obs/region_spp/recent?rtype=country&r=US&sci=surnia%20ulula&back=30&maxResults=1&includeProvisional=true
My guess is that you're using a free account. Free accounts on PythonAnywhere have restricted Internet access, you can only access sites that are on the whitelist:
https://www.pythonanywhere.com/wiki/403ForbiddenError
https://www.pythonanywhere.com/whitelist/
You'll see that if you adjust your code to do a:
usa_xml = requests.get(URL_HERE)
print(usa_xml)
You'll probably see a
<Response [403]>
403 being forbidden.
We (the PythonAnywhere team) are usually happy to add sites with a public API to the whitelist. ebird.com looks fine, I'll see if I can get that added. For anyone else with a similar request, don't hesitate to get in touch with us if you see a 403!
I am trying to get Flask-SQLAlchemy working and running in to some hiccups. Take a look at the two files I'm using. When I run gwg.py and goto /util/db/create-all it spits out an error no such table: stories. I thought I did everything correct; can someone point out what I'm missing or whats wrong? It does create data.db but the file shows as 0Kb
gwg.py:
application = Flask(__name__)
db = SQLAlchemy(application)
import models
# Utility
util = Blueprint('util', __name__, url_prefix='/util')
#util.route('/db/create-all/')
def db_create_all():
db.create_all()
return 'Tables created'
application.register_blueprint(util)
application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
application.debug = True
application.run()
models.py:
from gwg import application, db
class Story(db.Model):
__tablename__ = 'stories'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(150))
subscribed = db.Column(db.Boolean)
def __init__(self, name):
self.name = name
self.subscribed = False
def toggle_subscription(self):
self.subscribed = False if self.subscribed else True
Edit
Here is the function that seems to be triggering the error but it shouldn't because I specifically go to /util/db/create-all first and then reload /. Even after the error I go to /util/db/create-all and then / and still get the same error
#application.route('/')
def homepage():
stories = models.Story.query.all()
return render_template('index.html', stories=stories)
Stacktrace
sqlalchemy.exc.OperationalError
OperationalError: (OperationalError) no such table: stories u'SELECT stories.id AS stories_id, stories.name AS stories_name, stories.subscribed AS stories_subscribed \nFROM stories' ()
Traceback (most recent call last)
File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\kylee\Code\GWG\gwg.py", line 20, in homepage
stories = models.Story.query.all()
File "C:\Python27\lib\site-packages\sqlalchemy\orm\query.py", line 2104, in all
return list(self)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\query.py", line 2216, in __iter__
return self._execute_and_instances(context)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\query.py", line 2231, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 662, in execute
params)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 761, in _execute_clauseelement
compiled_sql, distilled_params
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 874, in _execute_context
context)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1024, in _handle_dbapi_exception
exc_info
File "C:\Python27\lib\site-packages\sqlalchemy\util\compat.py", line 163, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 867, in _execute_context
context)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\default.py", line 324, in do_execute
cursor.execute(statement, parameters)
OperationalError: (OperationalError) no such table: stories u'SELECT stories.id AS stories_id, stories.name AS stories_name, stories.subscribed AS stories_subscribed \nFROM stories' ()
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
Brought to you by DON'T PANIC, your friendly Werkzeug powered traceback interpreter.
The issue here is one a gotcha in the Python import system. It can be simplified to the following explanation...
Assume you have two files in a directory...
a.py:
print 'a.py is currently running as module {0}'.format(__name__)
import b
print 'a.py as module {0} is done'.format(__name__)
b.py:
print 'b.py is running in module {0}'.format(__name__)
import a
print 'b.py as module {0} is done'.format(__name__)
The results of running python a.py are the following...
a.py is currently running as module __main__
b.py is running in module b
a.py is currently running as module a
a.py as module a is done
b.py as module b is done
a.py as module __main__ is done
Notice that when a.py is run, the module is called __main__.
Now think about the code you have. In it, your a.py script creates your application and db objects. However, those values are not stored in a module called a, they are stored in a module called __main__. Therefore, b.py tries to import a, it is NOT importing the values that you just created a few seconds ago! Instead, since it doesn't find module a, it creates a NEW module, running a.py a SECOND TIME and storing the results into the module a.
You can use print statements like what I have shown above to hopefully guide you through the entire process to see exactly what's going on. The solution is to make sure that you are only calling a.py ONCE, and when b.py imports a it will import the same values as a.py rather than importing it a second time.
The easiest way to fix this would be to create a python script that is just for running the application. Remove the application.run() from the end of gwg.py, and add the following script...
main.py:
from gwg import application
application.run()
Then run using python main.py.