AttributeError: module 'flask.app' has no attribute 'route' - python-3.x

I have autocomplete function as a separate file - autocomplete.py. The autocomplete is being imported into init.py as follows:
from xyzapp.autocomplete import autocomplete
The line that throws error in autocomplete.py is the following:
#app.route('/autocomplete',methods=['GET'])
The structure of the application is using blueprints and looks as follows:
appcontainer
|
|--run.py
|
|
|--xyzapp
|--__init__.py
|--autocomplete.py
|--blueprint_folder_1
|--blueprint_folder_2
|--static
The whole error message looks like this:
#app.route('/autocomplete',methods=['GET'])
AttributeError: module 'flask.app' has no attribute 'route'
Any ideas what I am doing wrong?
UPDATE:
The autocomplete.py looks as follows:
from flask import Flask, render_template, redirect, url_for, request, session, flash, app, Blueprint, jsonify
#app.route('/autocomplete',methods=['GET'])
def autocomplete():
database='backbone_test'
db=client[database]
all_names=list(db.ids.find({},{"current_name":1,"_id":0}))
return json.dumps(all_names)
The __init__.py file looks as follows:
from flask import Flask, render_template, Blueprint, jsonify, session
import jinja2
class MyApp(Flask):
def __init__(self):
Flask.__init__(self, __name__)
self.jinja_loader = jinja2.ChoiceLoader([self.jinja_loader,jinja2.PrefixLoader({}, delimiter = ".")])
def create_global_jinja_loader(self):
return self.jinja_loader
def register_blueprint(self, bp):
Flask.register_blueprint(self, bp)
self.jinja_loader.loaders[1].mapping[bp.name] = bp.jinja_loader
app = MyApp()
from xyzapp.autocomplete import autocomplete
from xyzapp.blueprint_folder_1.some_file import bp_1
app.register_blueprint(bp_1)

In autocomplete.py, it looks like you're importing app from Flask and not from your __init__.py file. Try importing from __init__.py instead.

import Flask first, the initiate your app
from flask import Flask
app = Flask(__name__)

I'm sorry this is a bit of a long shot, I'm not familiar with this way of running a Flask app, but it seems you create your own instance of the Flask class called MyApp and initialise it under the variable app.
I'm not 100% and may be completely wrong, but I think your problem lies in the __init__ of MyApp

Did you import Flask to your.py? Double check and make the addition of missing.

Related

Pytest Flask Application AttributeError: module 'src.api' has no attribute 'test_client'

I am trying a basic Pytest test for a "hello world" flask application
Please see below what I have in the src file
api.py:
from flask import Flask, jsonify
api = Flask(__name__)
#api.route('/')
def hello_world():
return jsonify(message="hello world")
if __name__ == '__main__':
api.run(debug=True)
and this is what I have written for the test
test_api.py
import pytest
from src import api
api.testing = True
client = api.test_client()
def test_route(client):
response = api.get('/')
assert response.status_code == 200
Structure
my_project
__init__.py
src
__init__.py
api.py
test
__init__.py
test_api.py
I run the tests from the root with python -m pytest
The error message I get is
test/test_api.py:13: in <module>
with api.test_client() as client:
E AttributeError: module 'src.api' has no attribute 'test_client'
I am really unsure of how to make this work.
from src import api imports the module of src/api.py
However, you are interested in the global api object that is within the scope of that src.api module
from src.api import api will import the flask application object which should have the test_client method that you are calling.

Flask-SocketIO emit not working from different module?

When I invoke socket.emit('someevent','blahblah') from server.py file, everything works as intended. But when I try to invoke the same method from bot.py, nothing happens.
Code:
server.py:
import eventlet
eventlet.monkey_patch()
import eventlet.wsgi
from flask import Flask, render_template, jsonify, request, abort
from flask_cors import CORS, cross_origin
import threading
from thread_manager import ThreadManager
from flask_socketio import SocketIO, emit, send
cho = Flask(__name__, static_folder="client/dist", template_folder="client/dist")
socketio = SocketIO(cho)
cors = CORS(cho)
threadmanager = ThreadManager() # Start the thread manager
import bot as bot_module
#cho.route('/api/start_bot', methods=['POST'])
#cross_origin()
def startBot():
"""
Begins the execution
:return:
"""
if request.method == 'POST':
request_json = request.get_json()
.... more code
bot = bot_module.Bot(some_args_from_request_above)
bot_thread = threading.Thread(target=bot.run)
bot_thread.start()
if threadmanager.check_thread_status(bot_name):
print('Thread is alive!')
return ok_res
else:
print('Thread seems inactive')
return bad_res
if __name__ == "__main__":
eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 5000)), cho, debug=True)
bot.py
import server
class Bot:
.....
def run(self):
server.socketio.emit('someevent', 'w0w') # <-- nothing happens
I know I'm using the standard threading mechanism but it seems to not be related to threads whatsoever as I can create a random static method inside the Bot class, invoke it before creating a separate thread from the main file and nothing will happen. The thread_manager module contains nothing that would interfere, but I've even removed it completely from the picture and nothing changed. Any clues?
Turns out this was completely related to the circular import. Splitting the app declaration from the entrypoint worked, so that I'd have a third reference file which to import socketio from.

Python - no attribute 'as_view' Error

I am trying to write a new python rest api like below,
from flask import Flask
from com.app.Controller import Event1LogicClass
from com.app.Controller import Event2LogicClass
from flask import Flask
from flask_restful import Api
com.app:
app = Flask(__name__)
apiRest = Api(app)
apiRest.add_resource(Event1LogicClass, '/Count/<string:days>')
apiRest.add_resource(Event2LogicClass,'/Count/<string:days>/<string:givenDate>')
if __name__ == '__main__':
app.run(debug = True)
com.app.Controller :
class Event1LogicClass(Resource)
def get(self, days):
return "Event1LogicClass"
com.app.Controller :
class Event2LogicClass(Resource)
def get(self, days, givenDate):
return "Event2LogicClass"
When I select MainClass as main class and run then It gives
resource_func = self.output(resource.as_view(endpoint, *resource_class_args,
AttributeError: module 'com.app.Controller.Event1LogicClass' has no attribute 'as_view'
I want to add multiple rest call in MainClass and call the api functionality depending on class in apiRest.add_resource.
where am I doing wrong?

Flask + Peewee error AttributeError: 'Flask' object has no attribute 'compiler'

What am I doing?
I had been learning from a Flask tutorial (https://blog.miguelgrinberg.com/) and I'm stuck on the ORM section as it uses SQLAlchemy and I want to use Peewee (I use it in another project, and had been working nicely on it).
Noob Problematic
After configuring Peewee and define a BaseModel, and implementing it in a User model, I tried to do a query and got this error instead:
File "/home/atrevino/.local/share/virtualenvs/comparteme-qStpFUrM/lib/python3.6/site-packages/peewee.py", line 2932, in compiler
return self.database.compiler()
AttributeError: 'Flask' object has no attribute 'compiler'
Not sure if this is related to the configuration of my database, but I was able to get the MySQLDatabase object which makes me to think it's doing a connection to the DB properly.
The error above is displayed whenever I try to do something with Peewee's models, for example User.get(User.id == 1) or User.create(username='Name')
This is my test-app and environment configuration
./config.py
import os
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-know'
DATABASE = {
'name': 'comparteme',
'engine': 'peewee.MySQLDatabase',
'user': 'root',
'password': 'whatever',
'host': os.environ.get('DATABASE_URL') or 'mysql://root#localhost:3306'
}
comparteme/__init__.py
import peewee
from flask import Flask
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
db = peewee.MySQLDatabase(app).database
from comparteme import routes
comparteme/models/base_model.py
import peewee
from comparteme import db
class BaseModel(peewee.Model):
class Meta:
database = db
class User(BaseModel):
username = peewee.CharField(unique=True)
I call all this from a flask route:
comparteme/routes.py
from comparteme import app
from comparteme.models.base_model import User
#app.route('/')
#app.route('/index')
def index():
User.create(username='Alan')
return 'returning any string'
To be able to test I have one test.py on my root directory that I added to FLASK_APP environment variable by using export FLASK_APP=test.py.
./test.py
from comparteme import app
After that I just do a regular flask run and open a browser with http://127.0.0.1:5000/ and get the error.
Is this the correct way to configure Peewee?
Thanks in advance !!!

Why do I have to return app in Flask create_app?

from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
#
return app
Hi, I'm learning Flask by reading 'Flask Web Development by Grinberg M'.
The above code is copied from that book.
Could anyone please explain why I need to "return app" in the end?
As far as I know you haven't copied the complete code.
You've probably missed these lines or something similar:
if __name__ == '__main__':
app = create_app('Example')
app.run()
The reason the author returns the app, as #davidism has explained, is that we use the app instance to start our Flask application. Simple as that!
I hope this answers your question.

Resources