I am developing a website based on Flask and SQLAlchemy
ssis created by sessionmaker in sqlalchemy.orm
Anime, ActorQuote, AnimeComment are models based on database structure
```
#app.route('/page/<anime_name>', methods=['GET', 'POST'])
def show_page(anime_name):
if request.method == 'GET':
anime = ss.query(Anime).filter_by(anime_name=anime_name).first()
actor_quotes = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
anime_comments = ss.query(AnimeComment).filter_by(anime_id=anime.id).all()
return render_template('page.html', anime=anime, actor_lines=actor_quotes, comments=anime_comments)
As excepted, it would return a page with these arguments -- anime, actor_quotes, anime_comments, and it does, but also throw a Attribute Error.
```
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/windrunner/hiacg/index.py", line 138, in show_page
actor_lines = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
AttributeError: 'NoneType' object has no attribute 'id'
When I use try-except to catch the error, it throws another UnboundLocalError.
```
try:
anime = ss.query(Anime).filter_by(anime_name=anime_name).first()
actor_quotes = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
anime_comments = ss.query(AnimeComment).filter_by(anime_id=anime.id).all()
except AttibuteError:
print 'AttibuteError occurs again!'
What is more strange is the website still works well as nothing happened.
/page/化物语 This shows the page as expected without error.
/page/剑风传奇 This shows the page as expected but with error.
In your line
anime = ss.query(Anime).filter_by(anime_name=anime_name).first()
the variable anime is None if not found (as you said in database empty) and thus the AttributeError when trying to access None.id.
Btw I kindly suggest you to use Flask-SQLAlchemy extension that tackles all the db connection logic and exposes some useful functions such as `.first_or_404'.
With it your code would become
anime = Anime.query.filter_by(anime_name=anime_name).first_or_404()
Related
I'm kind of new to using flask, and I want to cache the result of a function that reads pickled data. I use memoize function from flask_cache as follows:
in model_chacher.py:
from flask_cache import Cache
import pickle
model_cache = Cache(config={'CACHE_TYPE': 'simple'})
class ModelCacher():
#model_cache.memoize(50)
def get_model(self, customer_ID):
with open('/path/to/data.pickle', 'rb') as tf:
model_args = pickle.load(tf)
trained_classifier = model_args[0]
return trained_classifier
in flask_compose.py:
from flask import Flask
from controllers.topic import controller as topic_controller
from models.modelcache.model_chacher import model_cache
app = Flask(__name__)
model_cache.init_app(app)
app.register_blueprint(topic_controller.topic_controller_blueprint)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=80, debug=True)
and I call ModelCacher.get_model(customer_ID) in topic_controller:
from models.modelcache.model_chacher import ModelCacher
...
trained_classifier = ModelCacher.get_model(cls_str)
...
and after running flask_compose.py and sending a request I get the following result:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/controllers/topic/controller.py", line 20, in classify
return ModelCacher.get_model(cls_str)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 528, in decorated_function
cache_key = decorated_function.make_cache_key(f, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 393, in make_cache_key
**kwargs)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 434, in _memoize_kwargs_to_args
elif abs(i-args_len) <= len(argspec.defaults):
TypeError: object of type 'NoneType' has no len()
and my question is: how to properly set up my cache? any help is greatly appreciated.
EDIT: WHAT SOLVED MY PROBLEM:
as #stamaimer pointed out, I create and instance of my ModelCacher and that solved the problem, also I used cached from flask_cache.Cache instead of memoize.
The get_model method your defined is a instance method instead of a class method. You use ModelCacher.get_model(cls_str) when call the method. Try to call it with ModelCacher().get_model(cls_str). Or you can just defined it as a global function.
I am creating a bot with Spark (chat for enterprise), in Python, I use PyGitHub for the librairy.
So when I write "repos" in my room with the bot he has to send me back the list of my repos.
It works fine with my github personnal account but not with my professionnal account.
If you can explain me why ?
here my code:
def gitTest(self, details, message):
url = "https://enter-prise.com"
token = "abcd"
github = Github(token, base_url=url)
for repo in github.get_organization("org").get_repos():
self.answer(details.roomId, markdown=repo.name)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/mflamant/Documents/bot/CiscoSparkPython/testbotforgithub/main.py", line 44, in Main
bot.isRunnable()
File "/home/mflamant/Documents/bot/CiscoSparkPython/testbotforgithub/utils/Compute.py", line 47, in isRunnable
self.spark(message[0], message[1])
File "/home/mflamant/Documents/bot/CiscoSparkPython/testbotforgithub/testbotforgithub.py", line 33, in spark
return self.answer(details.roomId, markdown=self.gitTest(details, message))
File "/home/mflamant/Documents/bot/CiscoSparkPython/testbotforgithub/testbotforgithub.py", line 56, in gitTest
for repo in github.get_organization(adt).get_repos():
File "/usr/local/lib/python2.7/dist-packages/PyGithub-1.35-py2.7.egg/github/Organization.py", line 539, in get_repos
self.url + "/repos",
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Can you explain me what is wrong with my code ? thank you
If gitTest is an instance method, you need to assign to the attribute self.url, not just to the local variable url. So your method should probably look like this:
def gitTest(self, details, message):
self.url = "https://enter-prise.com"
self.token = "abcd"
github = Github(token, base_url=url)
for repo in github.get_organization("org").get_repos():
self.answer(details.roomId, markdown=repo.name)
This is why you pass in the reference to self as the first argument of any instance method.
I'm getting the following when sending a very large POST to a Flask application.
Logs:
restful stderr | /usr/local/lib/python2.7/dist-packages/werkzeug/filesystem.py:63: BrokenFilesystemWarning: Detected a misconfigured UNIX filesystem: Will use UTF-8 as filesystem encoding instead of 'ANSI_X3.4-1968'
BrokenFilesystemWarning)
restful stderr | 172.19.0.5 - - [25/Apr/2017 00:05:40] "POST /ml/source/ HTTP/1.1" 500 -
restful stderr | Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/fish/bizco/ml/restful.py", line 49, in index
job = q.enqueue_call(func=process_request, args=(postObject,), result_ttl=5000, timeout=36000)
File "/usr/local/lib/python2.7/dist-packages/rq/queue.py", line 216, in enqueue_call
job = self.enqueue_job(job, at_front=at_front)
File "/usr/local/lib/python2.7/dist-packages/rq/queue.py", line 282, in enqueue_job
pipe.execute()
File "/usr/local/lib/python2.7/dist-packages/redis/client.py", line 2641, in execute
return execute(conn, stack, raise_on_error)
File "/usr/local/lib/python2.7/dist-packages/redis/client.py", line 2495, in _execute_transaction
connection.send_packed_command(all_cmds)
File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 556, in send_packed_command
(errno, errmsg))
ConnectionError: Error 104 while writing to socket. Connection reset by peer.
Route Code:
#app.route('/zebra/', methods=['GET', 'POST'])
def index():
print "/zebra/ called:")
if request.method == "POST":
state = True
if request.headers['Content-Type'] == 'application/x-msgpack':
print 'Found MsgPack'
postObject = msgpack.unpackb(request.data)
else:
print 'Content type not correct'
state = False
if state == True:
json = jsonify(...)
else:
# return an error
json = jsonify...)
return json
The POST object contains a MessagePack encoded payload, but it never enters my route handler. I see no log statement inside the handler block.
This only seems to happen when the payload is above 200MB. How do I get flask to store handle properly?
I have an email confirmation feature on my Flask application. For this to work, I must create a token which will go in a confirmation link. To create the token I'm using Its Dangerous like so:
from itsdangerous import URLSafeTimedSerializer
ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
token = ts.dumps(email, salt='email-confirm-key')
confirm = url_for('confirm', token=token, _external=True)
After running this, I receive an error stating cannot concatenate 'str' and 'NoneType' objects from the following traceback:
Traceback (most recent call last):
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/pavsidhu/Documents/Web-Development/myapp/myapp/views/confirmation.py", line 62, in resend
activateEmail(email)
File "/Users/pavsidhu/Documents/Web-Development/myapp/myapp/views/functions.py", line 34, in activateEmail
token = ts.dumps(email, salt='email-confirm-key')
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/itsdangerous.py", line 566, in dumps
rv = self.make_signer(salt).sign(payload)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/itsdangerous.py", line 412, in sign
return value + sep + self.get_signature(value)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/itsdangerous.py", line 347, in get_signature
key = self.derive_key()
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/itsdangerous.py", line 334, in derive_key
self.secret_key).digest()
TypeError: cannot concatenate 'str' and 'NoneType' objects
I'm unsure what the issue is, as email is a string and the salt is one too. What could be the problem? Thanks.
The issue is this line:
ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
It looks like your app.config["SECRET_KEY"] is not being set correctly. If you replace that line with this
ts = URLSafeTimedSerializer('test')
You should find that it works. So you need to find out why app.config["SECRET_KEY"] is not being set correctly.
I'm trying to enable "User-Restricted Resource Access" in my eve application with Basic Authentication. http://python-eve.org/authentication.html#user-restricted-resource-access
The Problem is since I enabled it I get for every http request on the API a "500 error"
If I fire up the API without basic authentication params I get a bad credentials error, so the Basic Authentication works fine.
This is the eve DEBUG Output:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/Eve-0.3-py2.7.egg/eve/methods/common.py", line 226, in rate_limited
return f(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Eve-0.3-py2.7.egg/eve/auth.py", line 43, in decorated
if not auth.authorized(roles, resource_name, request.method):
File "/usr/local/lib/python2.7/dist-packages/Eve-0.3-py2.7.egg/eve/auth.py", line 97, in authorized
allowed_roles, resource, method)
**File "/home/maanuel/emberv/eve/run.py", line 12, in check_auth
self.set_request_auth_value(account['_id'])
AttributeError: 'BCryptAuth' object has no attribute 'set_request_auth_value'**
It seems like the set_request_auth_class is missing
I'm using eve 0.3 installed with easy_install
You are reading the documentation about the development version (as stated on all pages at python-eve.org.) One relevant change coming with v0.4 is the way auth tokens are set. So basically, you are applying 0.4-dev syntax to Eve v0.3. You should probably follow these instructions instead.
PS: 0.4 is due for release real soon so you might want to stick with that one, so you don't have to update your code again soon.