Blueprints in Flask "Attribute 'function' object has no attribute 'name' - python

Problem Description
Getting error message when trying to start Flask.
Traceback (most recent call last):
File "./run.py", line 3, in <module>
from app import app
File "/home/xxxxxx/xxxx.xxxxxxx.com/ClientTracker/app/__init__.py", line 13, in <module>
app.register_blueprint(admin)
File "/home/xxxxx/xxxxx.xxxxxxx.com/ClientTracker/env/local/lib/python2.7/site-packages/flask/app.py", line 65, in wrapper_func
return f(self, *args, **kwargs)
File "/home/xxxxx/xxxxx.xxxxxxx.com/ClientTracker/env/local/lib/python2.7/site-packages/flask/app.py", line 958, in register_blueprint
if blueprint.name in self.blueprints:
AttributeError: 'function' object has no attribute 'name'
This is a migration from a simpler hierarchy implementing Blueprints. I'm splitting out the function of the frontend and the admin panel.
I built this step by step and had both sides working fine.
Started migrating (functions and routes). After moving some code, I started getting an error message (basically the same as above, but different line).
Troubleshooting
Searched through related posts on stackO
Initially it was complaining about the second route statement I had. I
started removing code (rolling back) to what I (thought was) a known
good state. However I continued to have issues.
I have it down to the minimum code I believe I need but still getting
errors.
If I remove the registration in the init.py file, the frontend works
perfectly.
Code
#ClientTracker/run.py
#!env/bin/python
from app import app
app.run(host='0.0.0.0', port=8080, debug=False)
#ClientTracker/app/__init__.py
# Import flask and template operators
from flask import Flask, render_template
# Define the WSGI application object
app = Flask(__name__)
# Import a module / component using its blueprint handler variable (mod_auth)
#from app.mod_auth.controllers import mod_auth as auth_module
from app.admin.views import admin
from app.client.views import client
# Register blueprint(s)
app.register_blueprint(admin)
app.register_blueprint(client)
#ClientTracker/app/admin/views.py
from flask import render_template, request, Blueprint
from app import app
import MySQLdb
import datetime
admin = Blueprint(
'admin',
__name__,
url_prefix='/admin',
template_folder='templates',
static_folder='static'
)
#admin.route('/')
def admin():
return "ok"
I'm out of ideas.

Ok, so as seems to happen, I spend an hour looking, another 15 mins composing a question and then after I hit post, I find the answer.
I found a post (https://github.com/pallets/flask/issues/1327) that had the answer.
Basically, you cannot have a function name with the same name as your Blueprint name. Seems obvious now, but certainly stumped me for a while.
In thinking about it, my original "working" state had a dummy function name serving the '/'. When I rolled back, I didn't roll back far enough.
Replaced def admin(): with def admin1(): (will fix this better in prod) and all worked.
I hope this post helps someone else. Please still feel free to comment. As always, the group is always smarter than the individual. Lastly, thanks for reading this far. :-)

Your blueprint name is same with your function name, try to rename the function name instead.
Note that the blue print name and the function name can not be the same.
Make use if this tutorial to learn more about Blueprints, https://realpython.com/flask-blueprint/

Related

RuntimeError: Working outside of application context Error in Flask Server

I am trying to use the flask server, but since I faced an error, I started debugging it and by removing many codes to simplify the code and find finally reached to the following error::
Traceback (most recent call last):
File "C:\Code\SportsPersonClassifier\server\server.py", line 18, in <module>
print(classify_image())
File "C:\Code\SportsPersonClassifier\server\server.py", line 10, in classify_image
response = jsonify(util.classify_image(util.get_b64_for_virat()))
File "E:\Users\Acer\anaconda3\lib\site-packages\flask\json\__init__.py", line 358, in jsonify
if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
File "E:\Users\Acer\anaconda3\lib\site-packages\werkzeug\local.py", line 436, in __get__
obj = instance._get_current_object()
File "E:\Users\Acer\anaconda3\lib\site-packages\werkzeug\local.py", line 565, in _get_current_object
return self.__local() # type: ignore
File "E:\Users\Acer\anaconda3\lib\site-packages\flask\globals.py", line 52, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
This is my code:: in server.py
from flask import Flask, request, jsonify
import util
app = Flask(__name__)
#app.route('/classify_image', methods=['GET', 'POST'])
def classify_image():
response = jsonify(util.classify_image(util.get_b64_for_image()))
return response
if __name__ == "__main__":
print("Starting Python Flask Server For Sports Celebrity Image Classification")
util.load_saved_artifacts()
print(classify_image())
But the exact code works without any error, if I just remove jsonify() from the classify_image() function like this::
def classify_image():
response = util.classify_image(util.get_b64_for_image())
return response
If I write the classify_image function without jsonify it works as expected without error. I tried to solve the problem reading several StackOverflow answers but not working for my code. Please help me solve the problem with jsonify. Thank you.
As the error suggests, and as required by jsonify:
This requires an active request or application context
Calling the function this way via __main__ will not be within a Flask app context. Instead use app.run() to start the dev server, and then navigate to your route.

Flask cache set method throwing KeyError?

In order to cache some data, I am calling cache.set method. However it is throwing KeyError. The error log:
File "D:\Sample_Project\SomeRouter.py", line 176, in run
FetchFeed._prepareCache(f_content, cache, _program, _sprint)
File "D:\Sample_Project\SomeRouter.py", line 197, in _prepareCache
cache.set(cKey, data[last_index:last_index + MAX_DATA_PER_PAGE])
File "c:\python\lib\site-packages\flask_caching\__init__.py", line 254, in set
return self.cache.set(*args, **kwargs)
File "c:\python\lib\site-packages\flask_caching\__init__.py", line 246, in cache
return app.extensions["cache"][self]
KeyError: <flask_caching.Cache object at 0x04F9C8D0>
The server module looks like :
cache_type = 'simple' if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV'] == 'development' else 'uwsgi'
cache = Cache(config={'CACHE_TYPE': cache_type})
app = Flask("MY_PROJECT")
cache.init_app(app)
# some api.route functions
# goes here ....
if __name__ == "__main__":
with app.app_context():
cache.clear()
app.run(host="0.0.0.0")
And SomeRouter module:
from server import cache
#staticmethod
def _prepareCache(data, cache, program):
total_records = len(data)
if total_records > 0:
cKey = FetchFeed \
._constructCacheKey(program)
cache.set(cKey, data)
else:
print("data size is empty.")
Note: I have removed unnecessary codes.
I also put breakpoints, and called cache.set(some_key, some_value) in server module itself. It is returning True, but same cache object is throwing KeyError when imported and used in SomeRouter module. Can it be that the way I am importing an object is wrong? I also tried importing the cache object right before using it, but it did not work. Any idea what is going on here?
The problem was I was accessing cache object outside request context i.e. in "SomeRouter" module, and because of which it was unaware that under which context it is been used.
In server module where request has been received, the cache knows about the app application, but during cache.set(cKey, data) in SomeRouter module, it throws KeyError. This error is justified as mentioned above.
The resolution is to push the application context as below:
from server import app, cache
# Using context
with app.app_context():
cache.set(cKey, data)
This will push a new application context (using the application of app).
All thanks to Mark Hildreth, for his great answer on context in flask

Application ID error with GAE remote API

I am trying to use the Remote API in a local Client, following instructions given in Google documentation (https://developers.google.com/appengine/docs/python/tools/remoteapi).
I first tried from the Remote API shell, and everything is working fine. I can connect to my remote datastore and fetch data.
But when I run the following script, which is very similar to Google's example :
#!/opt/local/bin/python2.7
import sys
SDK_PATH = "/usr/local/google_appengine/"
sys.path.append(SDK_PATH)
import dev_appserver
dev_appserver.fix_sys_path()
from google.appengine.ext.remote_api import remote_api_stub
import model.account
def auth_func():
return ('myaccount', 'mypasswd')
remote_api_stub.ConfigureRemoteApi('myappid', '/_ah/remote_api', auth_func)
# Fetch some data
entries = model.account.list()
for a in entries:
print a.name
then I get an error :
Traceback (most recent call last):
File "./remote_script_test.py", line 26, in <module>
entries = model.account.list()
[...]
File "/Developer/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1333, in check_rpc_success
raise _ToDatastoreError(err)
google.appengine.api.datastore_errors.BadRequestError: Application Id (app) format is invalid: '_'
It says my application ID is a plain underscore '_', which is not the case since my app.yaml is correctly configured and when I do a
print app_identity.get_application_id()
from that script I get the correct application ID. I am under the impression that the GAE environment is not properly setup, but I could not figure out how to make it work. Does anyone have a full piece of code that works in this context ?
I am using Mac Os X Mountain Lion.
You may wish to start with remote_api_shell.py and remove stuff until it breaks, rather than add in things until it works.
For instance there's a line after the one you copied: remote_api_stub.MaybeInvokeAuthentication() is that necessary? There may be a number of necessary lines in remote_api_shell.py, maybe better to customize that rather than start from scratch.

AttributeError for SUDS in GAE

I am trying to include the SUDS library in a Python project through Google App Engine.
My code tries the following:
from suds.client import Client
from suds.wsse import *
And, once I've deployed on GAE, I encounter the following error:
File ".../myfile.py", line 13, in <module>
from suds.client import Client
File ".../suds/__init__.py", line 154, in <module>
import client
File ".../suds/client.py", line 25, in <module>
import suds.metrics as metrics
AttributeError: 'module' object has no attribute 'suds'
I've been looking around for a little while, and it seems like SUDS is workable with GAE. I added the fixes outlined here, but that doesn't seem to be the problem. It seems like App Engine doesn't even get to that point.
Any info or suggestions?
I'm using Python 2.7 and SUDS 0.4.
Have you tried doing a simple import suds.client? Also make sure you include the suds folder in your application as App Engine doesn't include it by default. I hope that helps.

Google App Engine with local Django 1.1 gets Intermittent Failures

I'm using the Windows Launcher development environment for Google App Engine.
I have downloaded Django 1.1.2 source, and un-tarrred the "django" subdirectory to live within my application directory (a peer of app.yaml)
At the top of each .py source file, I do this:
import settings
import os
os.environ["DJANGO_SETTINGS_MODULE"] = 'settings'
In my file settings.py (which lives at the root of the app directory, as well), I do this:
DEBUG = True
TEMPLATE_DIRS = ('html')
INSTALLED_APPS = ('filters')
import os
os.environ["DJANGO_SETTINGS_MODULE"] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.1')
from django.template import loader
Yes, this looks a bit like overkill, doesn't it?
I only use django.template. I don't explicitly use any other part of django.
However, intermittently I get one of two errors:
1) Django complains that DJANGO_SETTINGS_MODULE is not defined.
2) Django complains that common.html (a template I'm extending in other templates) doesn't exist.
95% of the time, these errors are not encountered, and they randomly just start happening. Once in that state, the local server seems "wedged" and re-booting it generally fixes it.
What's causing this to happen, and what can I do about it? How can I even debug it?
Here is the traceback from the error:
Traceback (most recent call last):
File "C:\code\kwbudget\edit_budget.py", line 34, in get
self.response.out.write(t.render(template.Context(values)))
File "C:\code\kwbudget\django\template\__init__.py", line 165, in render
return self.nodelist.render(context)
File "C:\code\kwbudget\django\template\__init__.py", line 784, in render
bits.append(self.render_node(node, context))
File "C:\code\kwbudget\django\template\__init__.py", line 797, in render_node
return node.render(context)
File "C:\code\kwbudget\django\template\loader_tags.py", line 71, in render
compiled_parent = self.get_parent(context)
File "C:\code\kwbudget\django\template\loader_tags.py", line 66, in get_parent
raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent
TemplateSyntaxError: Template u'common.html' cannot be extended, because it doesn't exist
And edit_budget.py starts with exactly the lines that I included up top.
All templates live in a directory named "html" in my root directory, and "html/common.html" exists. I know the template engine finds them, because I start out with "html/edit_budget.html" which extends common.html.
It looks as if the settings module somehow isn't applied (because that's what adds html to the search path for templates).
Firstly, although django is now a LOT more compatible with app engine than it once, some major incompatibilities still exist between the two platforms, meaning that you can't just dump a stock copy of django into your appengine directory and have it work out of the box. Things will error in strange ways.
There are a number of projects which aim to improve compatibility between the two projects, the most prominent is app-engine-patch. I highly suggest reading the following article http://code.google.com/appengine/articles/app-engine-patch.html and the rest of the articles located at code.google.com/appengine/articles/ under the django tab.
as for some of you're specific problems, you could try this within your setup script:
#setup django environment
from django.core.management import setup_environ
import settings
setup_envion(settings)
this is what django uses internally for setting up the environment within manage.py and is the accepted best practice for setting up django for use with scripts (like app engine).
I'm having exactly the same issue, and I haven't been able to work around it... though I've noticed it happens a LOT less with the real GAE than it does with the development server I run on my Linux workstation.

Categories