I have been stumped and can't seem to figure out why I am receiving an AssertionError. I am currently working on a rest api using the flask_restful lib. I am querying by:
#staticmethod
def find_by_id(id, user_id):
f = File.query.filter_by(id=id).first() #Error is happening here
if f is not None:
if f.check_permission(user_id)>=4:
return f
print f.check_permission(user_id)
FileErrors.InsufficientFilePermission()
FileErrors.FileDoesNotExist()
The error message looks like this:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1531, in handle_user_exception
assert exc_value is e
AssertionError
This is how my File model looks like:
class File(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer)
parts = db.Column(db.Integer)
size = db.Column(db.Integer)
name = db.Column(db.String(100))
def __init__ (self, file_info):
self.user_id = file_info['user_id']
self.parts = file_info['parts']
self.size = file_info['size']
self.name = file_info['name']
#staticmethod
def create(file_info):
return add_to_db(File(file_info))
#staticmethod
def delete(file_id, user_id):
pass
def check_permission(self,user_id):
permission = 0
print 'self.user_id {}'.format(self.user_id)
print 'user_id {}'.format(user_id)
if self.user_id == user_id:
return 7
fs = FileShare.find_by_file_and_user_id(self.id, user_id)
if fs is not None:
permission = fs.permission
return permission
#staticmethod
def find_by_id(id, user_id):
f = File.query.filter_by(id=id).first() #Error is happening here
if f is not None:
if f.check_permission(user_id)>=4:
return f
print f.check_permission(user_id)
FileErrors.InsufficientFilePermission()
FileErrors.FileDoesNotExist()
Any help would be appreciated. Thanks in advance.
Are you sure you want to have an assignment operator instead of comparison in your filter. Try replacing = with == and see if it solves your problem.
f = File.query.filter_by(id == id).first()
Hannu
Although I couldn't figure out why the error occurs, I know how as well as how to prevent it. It is created because the query doesn't pull the live data right after the commit. The way to prevent it is by using db.session.query(). So in my example I would change:
f = File.query.filter_by(id=id).first()
to
f = db.session.query(File).filter_by(id=id).first()
For some reason that works. Although I don't know why.
EDIT: It seems to have to do with the class not receiving updated session. For the time being I recommending using queries within session.
Related
I'm currently using an environment variable to hide my API's key. My unit test that is testing the API route is now failing. However, when the key was hard-coded into the main file, the tests passed. Here is my code:
import os
import requests
key = os.environ.get('key')
def test_code(state, API_BASE_URL):
url = f'https://covid-19-testing.github.io/locations/{state.lower()}/complete.json'
res = requests.get(url)
testing_data = res.json()
latsLngs = {}
for obj in testing_data:
if obj["physical_address"]:
for o in obj["physical_address"]:
addy = o["address_1"]
city = o["city"]
phone = obj["phones"][0]["number"]
location = f'{addy} {city}'
location_coordinates = requests.get(API_BASE_URL,
params={'key': key, 'location': location}).json()
lat = location_coordinates["results"][0]["locations"][0]["latLng"]["lat"]
lng = location_coordinates["results"][0]["locations"][0]["latLng"]["lng"]
latsLngs[location] = {'lat': lat, 'lng': lng, 'place': location, 'phone': phone}
return latsLngs
Here is the unit test:
from unittest import TestCase, mock
from models import db, User
from sqlalchemy.exc import InvalidRequestError
class UserViewTestCase(TestCase):
"""Test views for users."""
def setUp(self):
"""Create test client, add sample data."""
db.drop_all()
db.create_all()
self.app = create_app('testing')
self.client = self.app.test_client()
self.testuser = User.signup('test',
'dummy',
'test123',
'dummytest#test.com',
'password',
None,
"Texas",
None,
None)
self.uid = 1111
self.testuser.id = self.uid
db.session.commit()
def test_map_locations(self):
"""Does the map show testing locations?"""
with self.client as c:
resp = c.get('/location?state=California')
html = resp.get_data(as_text=True)
self.assertEqual(resp.status_code, 200)
self.assertIn('San Francisco', html)
I also think it's important to note that the application runs fine in the browser. It's just that the unit tests are not passing anymore.
UPDATE
Here is the full traceback:
ERROR: test_map_locations (test_user_views.UserViewTestCase)
Does the map show testing locations?
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/build/azaria-dedmon/covid-19/tests/test_user_views.py", line 157, in test_map_locations
resp = c.get('/location?state=California')
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 1006, in get
return self.open(*args, **kw)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/testing.py", line 227, in open
follow_redirects=follow_redirects,
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 970, in open
response = self.run_wsgi_app(environ.copy(), buffered=buffered)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 861, in run_wsgi_app
rv = run_wsgi_app(self.application, environ, buffered=buffered)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 1096, in run_wsgi_app
app_rv = app(environ, start_response)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/travis/build/azaria-dedmon/covid-19/app/__init__.py", line 111, in show_state_locations
latsLngs = test_code(state, API_BASE_URL)
File "/home/travis/build/azaria-dedmon/covid-19/app/refactor.py", line 22, in test_code
params={'key': key, 'location': location}).json()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/requests/models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "/opt/python/3.7.1/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/opt/python/3.7.1/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/opt/python/3.7.1/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I think it's most likely that your test framework is loading just the test_code() function from your test file, and not the fact that key is set up in the main body of the code. Perhaps moving your key = os.environ.get("key") into test_code() will solve your issue.
The environment variable needs to be set in the project's repository in travis CI so that all files have access to it. Here is the documentation on how to achieve this https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-settings
I am creating a simple flask application to store JSON files and read them. The application should return a JSON file I made as a test. Here's the url: http://IP:5000/?room=test&game=test. I got this error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python3/dist-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python3/dist-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python3/dist-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/lib/python3/dist-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python3/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pi/Desktop/python/universalgameserver.py", line 10, in api_set
return json.loads(readJSON(request.args['room'], request.args['game']))
File "/home/pi/Desktop/python/universalgameserver.py", line 17, in readJSON
f = open("~/saves/${room}_${game}.json".format(room, game), "r")
KeyError: 'room'
Printing out the dictionary, it looks like this:
{'room': 'test', 'game': 'test'}
My code looks like this:
from flask import Flask, request
import json
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def api_set():
if request.method == "POST":
writeJSON(request.form['room'], request.form['game'], request.form['json'])
else:
print(dict(request.args))
return json.loads(readJSON(request.args['room'], request.args['game']))
def writeJSON(room, game, json):
f = open("~/saves/${room}_${game}.json".format(room, game), "w")
f.write(json)
f.close()
def readJSON(room, game):
f = open("~/saves/${room}_${game}.json".format(room, game), "r")
contents = f.read()
f.close()
return contents
if __name__ == '__main__':
app.run(host='192.168.0.36')
The KeyError is raised in readJSON during the formatting of:
f = open("~/saves/${room}_${game}.json".format(room, game), "r")
Change it to:
If in Python 2:
f = open("~/saves/{0}_{1}.json".format(room, game), "r")
If in Python 3.6 or newer, using f-string which allows you to easy format:
f = open(f"~/saves/{room}_{game}.json", "r")
And it shall work like magic!
P.S.
Similarly, change in the writeJSON too.
Here I am trying to fetch data from cassandra with filter() where I need to fetch students with more than or equal to 65 marks but I am getting this error can't understand why am I getting this error. I am referring this link. I have also referred similar questions on this but didn't get any solution.
Here is my python code:
from flask import *
from flask_cqlalchemy import CQLAlchemy
app = Flask(__name__)
app.config['CASSANDRA_HOSTS'] = ['127.0.0.1']
app.config['CASSANDRA_KEYSPACE'] = "emp"
db = CQLAlchemy(app)
class Student(db.Model):
uid = db.columns.Integer(primary_key=True)
marks = db.columns.Integer(primary_key=True)
username = db.columns.Text(required=True)
password = db.columns.Text()
#app.route('/merit')
def show_merit_list():
ob = Student.objects.filter(marks >= 65)
return render_template('merit.html', ml = ob)
And this is the error log I am getting:
Traceback (most recent call last)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 2463, in
__call__
return self.wsgi_app(environ, start_response)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 2449, in
wsgi_app
response = self.handle_exception(e)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1866, in
handle_exception
reraise(exc_type, exc_value, tb)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in
reraise
raise value
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 2446, in
wsgi_app
response = self.full_dispatch_request()
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1951, in
full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1820, in
handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in
reraise
raise value
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1949, in
full_dispatch_request
rv = self.dispatch_request()
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1935, in
dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/sudarshan/Downloads/PycharmProjects/try/try1.py", line 67, in show_merit_list
ob = Student.objects.filter(marks >= 65)
NameError: name 'marks' is not defined
Pass self object to your method, hence allowing it to access marks data member.
Change marks to self.marks.
#app.route('/merit')
def show_merit_list(self):
ob = Student.objects.filter(self.marks >= 65)
return render_template('merit.html', ml = ob)
Well finally I found the answer I was forgetting to use allow_filtering(). The code will look like following:
#app.route('/merit')
def show_merit_list():
ob = Student.objects().filter() #all()
ob = ob.filter(Student.marks >= 65).allow_filtering()
return render_template('merit.html', ml = ob)
You need to use Filtering Operators, try:
ob = Student.objects.filter(marks__gte=65)
I'm trying to create a custom validator for one field in the AddSongForm. I used the inline validator and it uses two methods from my Songs class. When I try running the code, I get the following trace back:
form = AddSongForm()
[2017-05-16 13:44:11,547] ERROR in app: Exception on /addsong [POST]
Traceback (most recent call last):
File "C:\Python36-32\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python36-32\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python36-32\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python36-32\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python36-32\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python36-32\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python36-32\lib\site-packages\flask_login\utils.py", line 228, in decorated_view
return func(*args, **kwargs)
File "C:/Users/Pellissari/Desktop/files/projects/Musical 9gag/view.py", line 40, in addsong
if form.validate_on_submit():
File "C:\Python36-32\lib\site-packages\flask_wtf\form.py", line 101, in validate_on_submit
return self.is_submitted() and self.validate()
File "C:\Python36-32\lib\site-packages\wtforms\form.py", line 310, in validate
return super(Form, self).validate(extra)
File "C:\Python36-32\lib\site-packages\wtforms\form.py", line 152, in validate
if not field.validate(self, extra):
File "C:\Python36-32\lib\site-packages\wtforms\fields\core.py", line 204, in validate
stop_validation = self._run_validation_chain(form, chain)
File "C:\Python36-32\lib\site-packages\wtforms\fields\core.py", line 224, in _run_validation_chain
validator(form, self)
File "C:\Users\Pellissari\Desktop\files\projects\app\forms.py", line 20, in validate_song_link
if Songs.get_provider(url) in valid_providers:
TypeError: get_provider() missing 1 required positional argument: 'url'
127.0.0.1 - - [16/May/2017 13:44:11] "POST /addsong HTTP/1.1" 500 -
This is my form class
class AddSongForm(Form):
song_title = StringField('song_title', validators=[DataRequired()])
song_artist = StringField('song_artist', validators=[DataRequired()])
song_genre = StringField('song_genre')
song_link = StringField('song_link', validators=[DataRequired()])
def validate_song_link(form, song_link):
valid_providers = ['youtube.com', 'www.youtube.com', 'soundcloud.com', 'www.soundcloud.com']
url = song_link.data
if Songs.get_provider(url) in valid_providers:
if Songs.get_embed_code(url) is not False:
return True
else:
print("couldn't get your content")
return False
else:
print("unsupported provider")
return False
And here is the class I used the methods
class Songs(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
title = db.Column(db.String(50))
artist = db.Column(db.String(30))
genre = db.Column(db.String(40))
author = db.Column(db.String(40))
timestamp = db.Column(db.DateTime)
likes_num = db.Column(db.Integer)
song_link = db.Column(db.String(120))
def get_provider(self, url):
return urllib.parse.urlsplit(url)[1]
def get_embed_code(self, url):
code = None
vars = {'url': url, 'format': 'json', 'iframe': 'true', 'maxwidth': '450', 'show_comments': 'false'}
provider = self.get_provider(url)
endpoint = "http://"+provider+"/oembed?"
source = endpoint+urllib.parse.urlencode(vars)
try:
request = urlopen(source)
code = json.load(request)['html']
return code
except:
print("impossible to get your content. Check the link")
return False
I'm quite new with Python and this is my first time writing OO code, so I have no idea what could be happening here. Besides the problem, I would be happy if you also could give me some feedback on the code and if there are room to improve in some sense.
I'm not convinced these should be methods on Songs. They don't refer to anything to do with the Song class.
However if you want to keep them as methods, but still want to call them from the class, they need to be classmethods, not instance methods.
#classmethod
def get_provider(cls, url):
return urllib.parse.urlsplit(url)[1]
#classmethod
def get_embed_code(cls, url):
...
provider = cls.get_provider(url)
First of all correct the indentation for the method validate_song_link. It should be like this:
def validate_song_link(form, song_link):
valid_providers = ['youtube.com', 'www.youtube.com', 'soundcloud.com', 'www.soundcloud.com']
url = song_link.data
if Songs.get_provider(url) in valid_providers:
if Songs.get_embed_code(url) is not False:
return True
else:
print("couldn't get your content")
return False
else:
print("unsupported provider")
return False
To solve your problem you can try to change the get_provider method to a class method like this:
#classmethod
def get_provider(cls, url):
return urllib.parse.urlsplit(url)[1]
And then you can call this way:
songs = Songs()
if Songs.get_provider(songs, url) in valid_providers:
if Songs.get_embed_code(url) is not False:
return True
I have the following code:
session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine))
Base = declarative_base()
Base.query = session.query_property()
class CommonBase(object):
created_at = Column(DateTime, default=datetime.datetime.now)
updated_at = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
class Look(Base, CommonBase):
__tablename__ = "looks"
id = Column(Integer, primary_key=True)
def __init__(self):
print "__init__ is run"
Base.__init__(self)
self.feedback = None
def set_feedback(self, feedback):
"""Status can either be 1 for liked, 0 no response, or -1 disliked.
"""
assert feedback in [1, 0, -1]
self.feedback = feedback
def get_feedback(self):
return self.feedback
And I am getting the following error:
Traceback (most recent call last):
File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/web/backend.py", line 94, in wrapped
ret = f(*args, **kwargs)
File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/web/backend.py", line 81, in decorated
return f(*args, **kwargs)
File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/web/backend.py", line 187, in next
json_ret = ge.encode(results) # automatically pulls the tags
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/__init__.py", line 54, in default
jsonable = self.convert_to_jsonable(obj)
File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/__init__.py", line 40, in convert_to_jsonable
image_url=obj.image_url, feedback=obj.get_feedback())
File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/models.py", line 100, in get_feedback
return self.feedback
AttributeError: 'Look' object has no attribute 'feedback'
It seems to me that my __init__ method is not run as I can't see any print statements in my log.
Can someone explain why my __init__ is not run and what can I do for this?
Check out the SQLAlchemy documentation on reconstruction:
The SQLAlchemy ORM does not call __init__ when recreating objects from
database rows. The ORM’s process is somewhat akin to the Python
standard library’s pickle module, invoking the low level __new__
method and then quietly restoring attributes directly on the instance
rather than calling __init__.
If you need to do some setup on database-loaded instances before
they’re ready to use, you can use the #reconstructor decorator to tag
a method as the ORM counterpart to __init__. SQLAlchemy will call this
method with no arguments every time it loads or reconstructs one of
your instances. This is useful for recreating transient properties
that are normally assigned in your __init__:
from sqlalchemy import orm
class MyMappedClass(object):
def __init__(self, data):
self.data = data
# we need stuff on all instances, but not in the database.
self.stuff = []
#orm.reconstructor
def init_on_load(self):
self.stuff = []
When obj = MyMappedClass() is executed, Python calls the __init__
method as normal and the data argument is required. When instances are
loaded during a Query operation as in query(MyMappedClass).one(),
init_on_load is called.