Flask AttributeError: module object has no attribute 'app' - python-3.x

I am a newbie to flask, and I had below import related AttributeError when flask run in flask_lab folder.
Any help would be appreciated.
Working Directory:
flask_lab
├── __init__.py
├── Pipfile
├── Pipfile.lock
├── README.md
├── tmp
│   ├── __init__.py
│   └── test.py
└── app.py
flask_lab/app.py:
import os
import click
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_lab.tmp.test.demo
app = Flask(__name__)
prefix = 'sqlite:////'
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
flask_lab.tmp.test.demo()
flask_lab/tmp/test.py:
import flask_lab.app
print(flask_lab.app.db)
def demo():
print('yeah!')
Error:
Traceback (most recent call last):
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/bin/flask", line 10, in <module>
sys.exit(main())
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 894, in main
cli.main(args=args, prog_name=name)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 557, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 767, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 293, in __init__
self._load_unlocked()
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 317, in _load_unlocked
self._app = rv = self.loader()
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 377, in load_app
raise_if_not_found=False)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 235, in locate_app
__import__(module_name)
File "/home/huafeng/Desktop/flask_lab/app.py", line 7, in <module>
import flask_lab.tmp.test.demo
File "/home/huafeng/Desktop/flask_lab/tmp/test.py", line 3, in <module>
print(flask_lab.app.db)
AttributeError: module 'flask_lab' has no attribute 'app'
Got complaints from stackoverflow about too many code and not enough details.... more words, more words....

While interpreting app.py if the python interpreter encounters a line import flask_lab.tmp.test.demo then it will start interpreting tmp/test.py immediately. But tmp/test.py again imports flask_lab.
At this point, since the interpreter had already encountered flask_lab, it will start searching for app in that namespace. But it had never reached till that line. Since you had already imported tmp.test before app was defined in the module, there is no flask_lab.app yet and hence the error.
And if you had called tmp.test directly, you would have encountered a circular import error as well.
So the way out is to avoid the circular import scenario. Move the db object to a separate module and call it in both these modules. Flask-SQLAlchemy provides a method called init_app which is meant for such use case.
Lets create a module called common which will contain the common variables.
flask_lab/common.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
flask_lab/app.py:
import os
import click
from flask import Flask
from .common import db
from .tmp.test import demo
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
app = Flask(__name__)
prefix = 'sqlite:////'
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')
db.init_app(app)
demo()
flask_lab/tmp/test.py:
from .common import db
print(db)
def demo():
print('yeah!')
Note that I have also replaced the flask_lab imports with relative imports. They are cleaner. The code inside the package should avoid using the package name in the imports. That way if you change the package name later, you can do so without having to change all the code inside.

Related

TypeError: 'module' object is not iterable in django 4

TypeError: 'module' object is not iterable in django 4
I am getting the above error, it has persisted long enough than at this point I really need help.
I am using pickle to load an ML model, Django to get user input. Below is the error,
my
urls.py file and the views.py file.
Any Help will be highly appreciated.
All Code in my GitHub.
******* When starting the server I get this Error Message *******
(python10_env) D:\Online Drives\MDigital\CIT-Letures\python10_env\smart_health_consult>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\urls\resolvers.py", line 634, in url_patterns
iter(patterns)
**TypeError: 'module' object is not iterable**
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
self.run()
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
self.check(display_num_errors=True)
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\management\base.py", line 438, in check
all_issues = checks.run_checks(
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces
namespaces.extend(_load_all_namespaces(pattern, current))
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\urls\resolvers.py", line 642, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'ml_dp_model.urls' from 'D:\\Online Drives\\MDigital\\CIT-Letures\\python10_env\\smart_health_consult\\ml_dp_model\\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.
Here is the ml_dp_model>urls.py
**** urls.py *****
from django.urls import path
from . import views
#from .views import index
#from .views import predict
urlpartterns = [
path('', views.index, name='index'),
path('result.html', views.predict, name='predict')
]
here is the ml_dp_model>views.py
********* views.py *********
from django.shortcuts import render
# Testing if context can solve circular refference issue.
from django.template import context
# Model related imports
import pandas as pd #install pandas
import pickle
import numpy as np # helps to manipulate the data
# Create your views here.
def index(request):
return render(request, 'index.html')
# importing the models using pickle.
#Loading Naive Bayes Pickle Model load method 1
nb_pickle = open('./models_store/final_nb_model.pickel','rb+')
nb_model = pickle.load(nb_pickle)
#Loading RandomForest Pickle Modal load method 1
rf_pickle = open('./models_store/final_rf_model.pickel', 'rb+')
rf_model = pickle.load(rf_pickle)
#Loading Scala Vector Machine Pickle Model load method 2
svm_model = pickle.load(open('./models_store/final_svm_model.pickel', 'rb+'))
# Disease prediction Function:
def predict(request):
if request.method=='POST':
symptom_index = {}
symptom_index['symptom1'] =float(request.POST.get('symptom1')) # Add data in string format to the dictionary
symptom_index['symptom2'] =float(request.POST.get('symptom2'))
symptom_index['symptom3'] =float(request.POST.get('symptom3'))
user_symptoms = pd.DataFrame({'X':symptom_index}).transpose() #think about changing dictionary to list at this line.
# Using pickle model() to predict
nb_prediction = nb_model.predict(user_symptoms)[0]
rf_prediction = rf_model.predict(user_symptoms)[0]
svm_prediction = svm_model.predict(user_symptoms)[0]
'''
Making final prediction by taking mode of all predicitions
'''
final_prediction = np.mode([rf_prediction, nb_prediction, svm_prediction])
predicted = final_prediction
return render(request,'result.html',{'results':predicted} )
You've got a typo in urls.py
urlpartterns should be urlpatterns :)

Django 'migrate' command suggesting errors related to packages

I am new to Django and python and am presently taking a course on full stack web development, after following the course exactly the way it shows I have typed the following code within the models.py file:
from django.db import models
# Create your models here.
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic)
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage)
date = models.DateField()
def __str__(self):
return str(self.date)
And have tried to execute the command:
python manage.py migrate
The following is the error I get when calling this command:
Traceback (most recent call last):
File "C:\Users\Naseem\desktop\my_django_stuff\first_project\manage.py", line 22, in <module>
main()
File "C:\Users\Naseem\desktop\my_django_stuff\first_project\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\apps\config.py", line 224, in create
import_module(entry)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
The following is the settings.py file, installed_apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'first_app',
]
And the admin.py file:
from django.contrib import admin
The course showed the models.py file working without adding anything to admin.py, I am not sure why it is showing these errors.
When using foreign keys in your models, you have to set the on_delete parameter so django knows what to do with the entries when the model entry your foreign key is pointing to is deleted.
You could fix your models.py like this:
# Create your models here.
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.CASCADE)
date = models.DateField()
def __str__(self):
return str(self.date)
You can read more about the different choices you have for this field here and what they are doing.
First of all, in your installed_app list write
INSTALLED_APPS = [
.........
'first_app.apps.FirstAppConfig',
]
insted of just 'first_app'
then in admin.py file add this
from django.contrib import admin
from .models import *
myModels = [models.modelname, models.modelname.......]
admin.site.register(myModels)
then in your cmd first write
python manage.py makemigrations
and then write
python manage.py migrate
Hope this will work.

No current context error after Python 3 migration, should I include more logic?

I'm converting a Google App Engine Python 2 project to Python 3
My understanding from reading the documentation I understand the preferred path is to run the main python program directly, skipping dev_appserver.py as was done in the past.
https://cloud.google.com/appengine/docs/standard/python3/tools/local-devserver-command
python3 main.py
--- main.py --
# coding: utf-8
import flask
from flask import request, redirect, url_for
from flask_basicauth import BasicAuth
#from urllib# import urlparse, urlunparse
import config
--- config.py
import model
...
33: CONFIG_DB = model.Config.get_master_db()
--- model/config.py
from __future__ import absolute_import
from google.cloud import ndb
#from oauth2client.contrib.appengine import CredentialsNDBProperty
from api import fields
import config
import model
import util
...
class Config(model.Base, model.ConfigAuth):
...
#classmethod
def get_master_db(cls):
57: return cls.get_or_insert('master')
When running the following trace is prod
Traceback (most recent call last):
File "main.py", line 9, in <module>
import config
File "/home/ffej/cloudpayback/main/config.py", line 33, in <module>
CONFIG_DB = model.Config.get_master_db()
File "/home/ffej/cloudpayback/main/model/config.py", line 57, in get_master_db
return cls.get_or_insert('master')
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/_options.py", line 89, in wrapper
return wrapped(*pass_args, **kwargs)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/utils.py", line 146, in positional_wrapper
return wrapped(*args, **kwds)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/model.py", line 5698, in _get_or_insert
return cls._get_or_insert_async(
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/_options.py", line 89, in wrapper
return wrapped(*pass_args, **kwargs)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/utils.py", line 146, in positional_wrapper
return wrapped(*args, **kwds)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/model.py", line 5811, in _get_or_insert_async
key = key_module.Key(cls._get_kind(), name, parent=parent, **key_args)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/key.py", line 290, in __new__
context = context_module.get_context()
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/context.py", line 96, in get_context
raise exceptions.ContextError()
google.cloud.ndb.exceptions.ContextError: No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context.
Is there additional logic that should be included after migration to start/initialize the datastore?
Thanks,
Jeff
The API for NDB library in Python3 has changed significantly. For developing on localhost you have to:
run DataStore Emulator, since you're not running dev_appserver anymore:
$ gcloud beta emulators datastore start
if you use the new NDB Library, then each NDB operation needs to be wrapped in a context manager:
with ndb_client.context(): # <- you need this line
cls.get_or_insert('master')
edit: instead of wrapping each NDB call with a context manager, you can use a middleware which will wrap the whole request cycle into the NDB context:
class NDBMiddleware:
def __init__(self, app):
self.app = app
self.client = ndb_client
def __call__(self, environ, start_response):
with self.client.context():
return self.app(environ, start_response)
app = Flask(__name__)
app.wsgi_app = NDBMiddleware(app.wsgi_app)

Python Django 3.1 The included URLconf 'mysite.urls' does not appear to have any patterns in it

I'm currently learning django by tutorial.
So I changed my return-renders to class-generic in views.
in URLs I added as_view() and then it gave me an error.
my traceback:
File "D:\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "D:\Anaconda3\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "D:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "D:\Anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check
databases=databases,
File "D:\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "D:\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patter
ns in the file then the issue is probably caused by a circular import.
urls.py:
from django.urls import path
from . import views
app_name = 'myapp'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:id>/', views.DetailView.as_view(), name='detail'),
path('<int:id>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from .models import Question
from django.template import loader
from django.views import generic
class IndexView(generic.listView):
template_name = 'myapp/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')
class DetailView(generic.DetailView):
model = Question
template_name = 'myapp/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'myapp/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, id=question_id)
try:
selected_choice = question.choice_set.get(id=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'myapp/detail.html',
{'question': question,
'error_message': "You didn't select a choice."}
)
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseResponse(reverse_lazy('myapp:results', args=(question_id,)))
I considered other tutorials and threads but found nothing about my subject. I think I missed something about IDs and PKs.
class IndexView(generic.listView): please change it to class IndexView(generic.ListView):. Here you use listView is incorrect.
I got this error message just bcoz of error in code. I didnt specify the class name when imported the models page
from . models import classname
is the right where this class is used in that page
from . models import
is wrong

AttributeError: 'NoneType' object has no attribute 'drivername'

I get this error when i start my app. Obviously it has something with SQLAlchemy. I 've been working this example with help of Corey Schaffer Flask tutorial.
> File "C:\Users\Matea\venv\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Matea\venv\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Matea\venv\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Matea\venv\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\Matea\venv\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Matea\venv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Matea\venv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Matea\venv\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\Matea\venv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Matea\venv\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Matea\myblog\myblog\main\routes.py", line 11, in home
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
File "C:\Users\Matea\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 514, in __get__
return type.query_class(mapper, session=self.sa.session())
File "C:\Users\Matea\venv\lib\site-packages\sqlalchemy\orm\scoping.py", line 74, in __call__
return self.registry()
File "C:\Users\Matea\venv\lib\site-packages\sqlalchemy\util\_collections.py", line 1001, in __call__
return self.registry.setdefault(key, self.createfunc())
File "C:\Users\Matea\venv\lib\site-packages\sqlalchemy\orm\session.py", line 2950, in __call__
return self.class_(**local_kw)
File "C:\Users\Matea\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 143, in __init__
bind = options.pop('bind', None) or db.engine
File "C:\Users\Matea\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 877, in engine
return self.get_engine()
File "C:\Users\Matea\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 896, in get_engine
return connector.get_engine()
File "C:\Users\Matea\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 556, in get_engine
self._sa.apply_driver_hacks(self._app, info, options)
File "C:\Users\Matea\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 830, in apply_driver_hacks
if info.drivername.startswith('mysql'):
AttributeError: 'NoneType' object has no attribute 'drivername'
here is some code:
This is from my init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from myblog.config import Config
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_manager.login_message_category = 'info'
mail = Mail()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
bcrypt.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
from myblog.users.routes import users
from myblog.posts.routes import posts
from myblog.main.routes import main
from myblog.errors.handlers import errors
app.register_blueprint(users)
app.register_blueprint(posts)
app.register_blueprint(main)
app.register_blueprint(errors)
return app
this piece code is from config.py
import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URL')
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = os.environ.get('EMAIL_USER')
MAIL_PASSWORD = os.environ.get('EMAIL_PASS')
I hope that you will help me and if something is missing,please tell me, Thank you!
if you have correctly set the environment variable in the .bash_proflie
export EMAIL_USER='youremail#gmail.com'
export EMAIL_PASS='Yourpassword'
export SQLALCHEMY_DATABASE_URI='sqlite:///site.db'
export SECRET_KEY='secretkeyxxxxxxxxxxxxxxxx'
then try restarting your computer.
if it still fails
*Try to create the database in python *
from your yourflaskapp import db
db.create_all()
If your app is in blueprints
use from yourapp import create_app
app = create_app()
app.app_context().push()
Always refresh your text editor and the terminal after making changes.
Also try to make sure you are running your app in the right directory.
for more info visit on blueprints use
http://flask-sqlalchemy.pocoo.org/2.3/contexts/
#Ivan M, I'm going through the same tutorial and had this problem as well. This happens because instructor moved the database URI and other params into environment variables (see Part 11 at about minute 27). It is a safety measure and good dev practice.
In order to make things work through config file, revert the changes in init.py and update config.py to have the direct link instead of square brackets:
SQLALCHEMY_DATABASE_URI = 'sqlite:///site.db'
UPD: same goes for SECRET_KEY and other params you wish to hard code:
SECRET_KEY = '5791628bb0b13ce0c676dfde280ba245'
I was following the same tutorial and got into this issue while setting up the config.py file as guided by the instructor.
Case with me
I was using PyCharm. PyCharm has the functionality to set project-specific environment variables. This means you can set environment variables w/o modifying .bash or .bash_profile, etc. files.
Mistake I Did
While setting up environment variables, we aren't supposed to have:
Spaces before and after the variable name
Quotes surrounding the value, for example:
sqlite:///site.db ✅
'sqlite:///site.db'❌
Quotes surrounding the variable name, for example:
SQLALCHEMY_DATABASE_URI ✅
'SQLALCHEMY_DATABASE_URI'❌
Spaces before and after the =
Spaces before and after the value
Note: If you are setting environment variables by modifying or creating .bash_profile or similar files, some of the above five points might not apply.
I did the 1st and 2nd mistake. So, silly. 😅
Namaste🙏
Not sure if this helps. I was running into the same problems.
I put print(f'From init {Config.dict}') just below def create_app(config=Config): in init.py & can see config.py attributes from a VS Code bash terminal or from a standalone bash session - all works OK I was running python run.py from Windows terminal using powershell. Works OK from cmd with setting.bat file run first
i had the same issues with that but
installing python-dotenv it solves the issues
pip3 install python3-dotenv
or else if it doesn't then the terminal suggest to go with sudo
try with sudo as admin then it'll
it'll work after installing env
and i'll suggest one more thing....like if any guy didn't setup the environment then setup first in bashprofile for both the 'EMAIL_USER' and for 'EMAIL_PASS' and same goes for those SECRET KEY and SQLALCHEMY
to do this you have to go to your nano editor and make these environment
for LINUX
nano .bash_profile (enter then it'll take you to the nano editor)
export DB_USER="Your email"
export DB_PASS="Your password"
export SECRET_KEY="your secret key"
export SQLALCHEMY_DATABASE_URI="sqlite:///site.db"
In Bash do this
export SQLALCHEMY_DATABASE_URI='sqlite:///site.db'
and in Windows Set
SECRET_KEY
xxxx14cae56bab7xxxxxxxxxxxxx
SQLALCHEMY_DATABASE_URI
sqlite:///site.db
save everything then close terminal and close editor and restart your terminal and editor. It will work.
In my case with pyCharm only hardcoding helped or a better solution is:
import os
from dotenv import load_dotenv
load_dotenv()
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URL')
And put your vars in .env file.
.env
SQLALCHEMY_DATABASE_URI=sqlite:///site.db
Had this issue many times. The reason was Python doesn't recognize your .env file.
You can install python-dotenv by pipenv install python-dotenv.
and then
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URL')
will work.

Resources