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.
Related
Hello everyone I will explain my problem as clearly as possible. I have a Flask application and I want to retrieve the uid from the url settings and then check if the user exists in my Firebase Cloud Firestore using an await.
But I have an error, when my application has to process the same request several times in a short time, I have this error:
127.0.0.1 - - [27/Sep/2022 22:37:04] "GET /firestore/petale?uid=user123456789 HTTP/1.1" 200 -
[2022-09-27 22:37:08,883] ERROR in app: Exception on /firestore/petale?uid=user123456789 [GET]
Traceback (most recent call last):
File "C:\Users\HP\IdeaProjects\flaskapp\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\HP\IdeaProjects\flaskapp\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\HP\IdeaProjects\flaskapp\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\HP\IdeaProjects\flaskapp\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "C:\Users\HP\PycharmProjects\flaskapp\routes\petale.py", line 14, in index
loop = asyncio.run(checkUid(uid))
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\HP\PycharmProjects\flaskapp\routes\petale.py", line 21, in checkUid
uid_doc = await document.get()
File "C:\Users\HP\IdeaProjects\flaskapp\lib\site-packages\google\cloud\firestore_v1\async_document.py", line 367, in get
response_iter = await self._client._firestore_api.batch_get_documents(
File "C:\Users\HP\IdeaProjects\flaskapp\lib\site-packages\google\api_core\grpc_helpers_async.py", line 168, in error_remapped_callable
call = callable_(*args, **kwargs)
File "C:\Users\HP\IdeaProjects\flaskapp\lib\site-packages\grpc\aio\_channel.py", line 168, in __call__
call = UnaryStreamCall(request, deadline, metadata, credentials,
File "C:\Users\HP\IdeaProjects\flaskapp\lib\site-packages\grpc\aio\_call.py", line 555, in __init__
self._send_unary_request_task = loop.create_task(
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 436, in create_task
self._check_closed()
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
127.0.0.1 - - [27/Sep/2022 22:37:08] "GET /firestore/petale?uid=user123456789 HTTP/1.1" 500 -
The highlighted error is: RuntimeError: Event loop is closed
You should know that I'm quite new to all the async/await methods, I come from Android with Java and it's not common for me. After several tests I could see that it comes from the line that retrieves the user's document with the await uid_doc = await document.get()
Searching on the internet I could see that people have this problem when they use the asyncio package, but I had not used it in my code. I decided to use it but I still have the same error and I don't know how to fix the problem. I don't really understand how to use asyncio.
import asyncio
from flask import Blueprint, request
from firebase_admin import firestore_async
petale = Blueprint("petale", __name__)
collection = firestore_async.client().collection('xxxx')
#petale.route("/petale", methods=['GET'])
def index():
uid = request.args.get('uid')
asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.run(checkUid(uid))
return loop
async def checkUid(uid):
document = collection.document(uid)
uid_doc = await document.get()
if uid_doc.exists:
return "Exists"
else:
return "Error"
I tried aioflask but there are many problems with it, I tried installing pip install flask[async] but it doesn't work either.
I'm a bit desperate, can you help me?
Thanks a lot!
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'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.
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 have this piece of code which is running perfectly on localhost but throws up this obscure error on GAE:
import_string() failed for 'webapp2_extras.appengine.auth.models.User' . Possible reasons are: - missing __init__.py in a package; - package or module
My import statements:
from webapp2_extras import auth
from webapp2_extras import sessions
from webapp2_extras.auth import InvalidAuthIdError
from webapp2_extras.auth import InvalidPasswordError
Usage of auth's user model:
user = self.auth.store.user_model.create_user(username, password_raw = password, email = email)
if not user[0]: #returns a tuple with [boolean, user_info]
return 'Create user error'
else:
self.set_flash("Thank you for registering. Please login!")
self.redirect(self.auth_config['login_url'])
Full code
UPDATE (Full stack trace)
import_string() failed for 'webapp2_extras.appengine.auth.models.User'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Original exception:
ImportError: No module named ndb
Debugged import:
- 'webapp2_extras' found in '/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/__init__.pyc'.
- 'webapp2_extras.appengine' found in '/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/appengine/__init__.pyc'.
- 'webapp2_extras.appengine.auth' found in '/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/appengine/auth/__init__.pyc'.
- 'webapp2_extras.appengine.auth.models' not found.
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/base/data/home/apps/s~webapp-auth/1.358936463581927371/main.py", line 34, in dispatch
response = super(BaseHandler, self).dispatch()
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~webapp-auth/1.358936463581927371/main.py", line 127, in post
user = self.auth.store.user_model.create_user(username, password_raw = password, email = email)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 701, in __get__
value = self.func(obj)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/auth.py", line 131, in user_model
cls = self.config['user_model'] = webapp2.import_string(cls)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1824, in import_string
return getattr(__import__(module, None, None, [obj]), obj)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/appengine/auth/models.py", line 13, in <module>
from ndb import model
Look similar to this issue which was already fixed by webapp 2.5.1
Make sure you import the latest version of webapp2, by adding those line to your app.yaml file:
libraries:
- name: webapp2
version: latest
As a workaround you can add the following lines to your application:
import sys
from google.appengine.ext import ndb
sys.modules['ndb'] = ndb