Import django setting in a app for test - django

I would like to import django setting in API_script.py in API
the settings are in Agora.settings :
Here is my API_script.py in API :
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Agora.settings")
from django.contrib.auth.models import User
import django
from django.db.models.loading import cache as model_cache
from Profile.models import Profile_User
try :
django.setup()
except :
pass
def check_profile_exist(token):
print(token)
Here is the error that i get :
Traceback (most recent call last):
File "/home/bussiere/WorkspaceSafe/Agora/API/API_script.py", line 3, in <module>
from django.contrib.auth.models import User
File "/usr/local/lib/python3.4/dist-packages/django/contrib/auth/__init__.py", line 7, in <module>
from django.middleware.csrf import rotate_token
File "/usr/local/lib/python3.4/dist-packages/django/middleware/csrf.py", line 14, in <module>
from django.utils.cache import patch_vary_headers
File "/usr/local/lib/python3.4/dist-packages/django/utils/cache.py", line 26, in <module>
from django.core.cache import caches
File "/usr/local/lib/python3.4/dist-packages/django/core/cache/__init__.py", line 34, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 92, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: No module named 'Agora'
And here my tree file :
.
├── Agora
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-34.pyc
│   │   ├── settings.cpython-34.pyc
│   │   ├── urls.cpython-34.pyc
│   │   └── wsgi.cpython-34.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── API
│   ├── admin.py
│   ├── API_script.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │   └── __init__.cpython-34.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-34.pyc
│   │   ├── API_script.cpython-34.pyc
│   │   ├── __init__.cpython-34.pyc
│   │   ├── models.cpython-34.pyc
│   │   └── views.cpython-34.pyc
│   ├── tests.py
│   ├── unit_test.py
│   └── views.py
├── Contact
│   ├── admin.py
│   ├── __init__.py
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-34.pyc
│   │   ├── __init__.cpython-34.pyc
│   │   └── models.cpython-34.pyc
│   ├── tests.py
│   └── views.py
├── Dockerfile
├── generateadm.py
├── IMG_20150928_105102.jpg
├── __init__.py
├── manage.py
├── Message
│   ├── admin.py
│   ├── __init__.py
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-34.pyc
│   │   ├── __init__.cpython-34.pyc
│   │   ├── models.cpython-34.pyc
│   │   └── views.cpython-34.pyc
│   ├── tests.py
│   └── views.py
├── Mock
│   ├── admin.py
│   ├── __init__.py
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-34.pyc
│   │   ├── __init__.cpython-34.pyc
│   │   ├── models.cpython-34.pyc
│   │   └── views.cpython-34.pyc
│   ├── tests.py
│   └── views.py
├── Profile
│   ├── admin.py
│   ├── __init__.py
│   ├── models.py
│   ├── profile_script.py
│   ├── __pycache__
│   │   ├── admin.cpython-34.pyc
│   │   ├── __init__.cpython-34.pyc
│   │   ├── models.cpython-34.pyc
│   │   └── profile_script.cpython-34.pyc
│   ├── tests.py
│   └── views.py
├── Queue
│   ├── admin.py
│   ├── __init__.py
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-34.pyc
│   │   ├── __init__.cpython-34.pyc
│   │   └── models.cpython-34.pyc
│   ├── tests.py
│   └── views.py
├── requierement.txt
├── result.txt
└── runserver.sh
regards and thanks

Have you appended the django project path to python's path?
e.g.
import os, sys
BASE_PATH="/location/folder/where/manage.py/lives"
sys.path.append(BASE_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = 'Agora.settings'

While the sys.path issues pointed out by other answers is probably your current problem, it seems that for your use case (a script that does "something" on an app) a Django custom command is more well suited.
It is very easy to setup a custom command:
Create the path management/commands in your API folder. Do not forget to add empty __init__.py files in both management and commands folders.
Then create a Python module named for example apiscript.py inside the management/commands folder, with this content:
from django.core.management.base import BaseCommand, CommandError
from Profile.models import Profile_User
class Command(BaseCommand):
help = 'Describe the purpose of your script'
def handle(self, *args, **options):
# do something with Profile_User model
p = Profile_User.objects.get(pk=1)
You have all the Django machinery already set up (no need to call django.setup()) and you can call your script with:
./manage.py apiscript

It is more than likely the case that the project Agora is not on the python path.
There are two ways you can add it to the path depending on your situation.
Firstly: Depending on your OS you can symlink the Agora projects into the python path directory. This is easily done on linux and OSX and not so easy on windows. It will be something like:
ln -s /path/to/Agora /usr/local/lib/python2.7/site-packages/Agora
Secondly: Add the following code before your application code:
import sys
import os
agora_path = os.path.join('/path/to/library')
sys.path.append(agora_path)
# now add your code
# ...

I've used your ideas and made it agnostic :
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
print(BASE_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Agora.settings")
thanks

Related

Python3 Django issues regarding paths and custom decorators

Rather new to Django first time using it. Python is not my strong point in a web context - I'm having issues with my custom decorator I made that will decode the jwt from all requests not really sure what it's looking for.
The error message can be found at the very bottom. Below are what my files look like I'm simply trying to use the verify_token() as a decorator to include my custom token checker when receiving an HTTP request ( please don't recommend simple-jwt or django session token ) ultimately not what we want to do as we're working with legacy tables from other DBS and don't want any abstraction)
decorators.py
from django.core.exceptions import PermissionDenied
import jwt
def verify_token(function):
def wrap(request, *args, **kwargs):
if request:
print('========='.format(request))
jwt.decode(request, 'secret', algorithms=['HS256'])
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
views.py
from .User_Predictions.PredictionService import PredicitonController
from django.http import JsonResponse
from rest_framework.views import APIView
from .decorators import verify_token
class UserPredictions(APIView):
#verify_token
def generate_full_report(request):
_predction = PredicitonController()
results = _predction.compile_complete_predition()
return JsonResponse(results, safe=False)
urls.py
from django.urls import path
from .views import UserPredictions
urlpatterns = [
path('compilePredictions/', UserPredictions.generate_full_report, name='generate_full_report')
]
.
├── Analytics
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-37.pyc
│   │   ├── settings.cpython-37.pyc
│   │   ├── urls.cpython-37.pyc
│   │   └── wsgi.cpython-37.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── authentication
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── biometrics
│   ├── admin.py
│   ├── apps.py
│   ├── bodyfatPrediciton.py
│   ├── Config.py
│   ├── __init__.py
│   ├── models.py
│   ├── templates
│   │   ├── bodyfat.html
│   │   ├── github.html
│   │   └── upload_bodyfat.html
│   ├── tests.py
│   ├── TorsoDimensions.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
├── dump.rdb
├── extraction
│   ├── admin.py
│   ├── apps.py
│   ├── ExtractionQueryService.py
│   ├── ExtractionServices.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │   └── __init__.cpython-37.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-37.pyc
│   │   ├── ExtractionQueryService.cpython-37.pyc
│   │   ├── ExtractionServices.cpython-37.pyc
│   │   ├── __init__.cpython-37.pyc
│   │   ├── models.cpython-37.pyc
│   │   ├── urls.cpython-37.pyc
│   │   └── views.cpython-37.pyc
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── loginServices
│   ├── admin.py
│   ├── apps.py
│   ├── Authentication.py
│   ├── decorators.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │   └── __init__.cpython-37.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-37.pyc
│   │   ├── Authentication.cpython-37.pyc
│   │   ├── __init__.cpython-37.pyc
│   │   ├── models.cpython-37.pyc
│   │   ├── urls.cpython-37.pyc
│   │   └── views.cpython-37.pyc
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
├── models.py
├── nutrition
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── 0002_auto_20191007_0323.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   │   ├── 0001_initial.cpython-37.pyc
│   │   ├── 0002_auto_20191007_0323.cpython-37.pyc
│   │   └── __init__.cpython-37.pyc
│   ├── models.py
│   ├── PredictFood.py
│   ├── __pycache__
│   │   ├── admin.cpython-37.pyc
│   │   ├── __init__.cpython-37.pyc
│   │   ├── models.cpython-37.pyc
│   │   ├── PredictFood.cpython-37.pyc
│   │   ├── serializers.cpython-37.pyc
│   │   ├── urls.cpython-37.pyc
│   │   └── views.cpython-37.pyc
│   ├── serializers.py
│   ├── TempImages
│   ├── templates
│   │   └── food.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── output
**├── predictions**
│   ├── admin.py
│   ├── apps.py
*│   ├── decorators.py*
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │   └── __init__.cpython-37.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-37.pyc
│   │   ├── decorators.cpython-37.pyc
│   │   ├── __init__.cpython-37.pyc
│   │   ├── models.cpython-37.pyc
│   │   ├── urls.cpython-37.pyc
│   │   └── views.cpython-37.pyc
│   ├── tests.py
*│   ├── urls.py*
│   ├── User_Predictions
*│   └── views.py*
├── README.txt
└── TempImages
ERROR MESSAGES
/Development/Backends_HealthApp/mainBackend/ModelBackend/Analytics/predictions/urls.py", line 6, in <module>
path('compilePredictions/', UserPredictions.generate_full_report, name='generate_full_report')
File "/home/travjav/.local/lib/python3.7/site-packages/django/urls/conf.py", line 73, in _path
raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
Not really sure what's going on here - I can use other non-custom decorators with no issues
it was the way the decorator was created.
I changed the function name, but you can see the difference.
from django.core.exceptions import PermissionDenied
import jwt
from functools import wraps
from django.http import HttpResponseRedirect, HttpResponse
def protected_endpoint(function):
#wraps(function)
def wrap(request, *args, **kwargs):
auth = request.headers.get('Authorization').split()[1]
if auth is None:
return PermissionDenied
elif auth is not None:
try:
session_token = jwt.decode(auth, '', 'utf-8')
except jwt.DecodeError:
return HttpResponse('Invalid Token')
if session_token:
return function(request, *args, **kwargs)
else:
return HttpResponseRedirect('/')
return wrap

Celery Cannot find a module in my Django project

I have a Django 2.0 project using celery 4.2.1 and redis 2.10.6. The django project has two apps, memorabilia and face_recognition. I have it all successfully running tasks with django running on my development machine. I uploaded everything to my git server, then installed the apps on my laptop from git, updated all requirements, etc. Both are Ubuntu machines. I am not using django-celery.
When I try to run celery -A MemorabiliaJSON worker -l debug,
I get an exception saying ModuleNotFoundError: No module named 'face_recognition.tasks'
I am not sure how to fix this, as the same code base is running on my development machine.
My file structure is:
├── celery.sh
├── face_recognition
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── tasks.py
│   ├── tests.py
│   └── views.py
├── __init__.py
├── manage.py
├── memorabilia
│   ├── admin.py
│   ├── apps.py
│   ├── fields.py
│   ├── fixtures
│   ├── __init__.py
│   ├── logs
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── storage.py
│   ├── tasks.py
│   ├── templates
│   ├── tests
│   ├── urls.py
│   ├── validators.py
│   ├── views.py
│   ├── widgets.py
├── MemorabiliaJSON
│   ├── celery.py
│   ├── default_images
│   ├── documents
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings
│   ├── static
│   ├── urls.py
│   ├── views.py
│   ├── wsgi.py
├── __pycache__
│   ├── celery.cpython-36.pyc
│   └── __init__.cpython-36.pyc
├── requirements.txt
└── tests
MemorabiliaJSON/celery.py
# http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.apps import apps
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MemorabiliaJSON.settings.tsunami')
app = Celery('MemorabiliaJSON')
app.config_from_object('django.conf:settings', namespace='CELERY')
#app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])
app.autodiscover_tasks()
#app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
(memorabilia-JSON) mark#octopus:~/python-projects/memorabilia-JSON
face_recognition/__init__.py
default_app_config = 'face_recognition.apps.FaceRecognitionConfig'
memorabilia/__init__.py
default_app_config = 'memorabilia.apps.MemorabiliaConfig'
INSTALLED_APPS has these two apps
'memorabilia.apps.MemorabiliaConfig',
'face_recognition.apps.FaceRecognitionConfig',

google cloud pubsub ImportError: cannot import name types

I wrote a small program for Google appengine on the python for a standard environment using google-cloud-pubsub. I get an error
ImportError: cannot import name types. I also saw that the problem is still not solved . But maybe someone started a sub-pub in a standard environment?
I install lib: pip installall -t lib google-cloud-pubsub.
In appengine_config.py: vendor.add('lib')
Error accessing the appengine application:
Traceback (most recent call last):
File "/base/alloc/tmpfs/dynamic_runtimes/python27g/7894e0c59273b2b7/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/alloc/tmpfs/dynamic_runtimes/python27g/7894e0c59273b2b7/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/base/alloc/tmpfs/dynamic_runtimes/python27g/7894e0c59273b2b7/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/base/data/home/apps/e~pqcloud-sp/agg2:20180703t012034.410851540172441919/service_main.py", line 5, in <module>
from google.cloud.pubsub_v1 import PublisherClient
File "/base/data/home/apps/e~pqcloud-sp/agg2:20180703t012034.410851540172441919/lib/google/cloud/pubsub_v1/__init__.py", line 17, in <module>
from google.cloud.pubsub_v1 import types
ImportError: cannot import name types
app.yaml:
runtime: python27
api_version: 1
threadsafe: true
service: agg2
handlers:
- url: .*
script: service_main.app
libraries:
- name: webapp2
version: "2.5.1"
- name: jinja2
version: latest
skip_files:
- ^(.*/)?#.*#$
- ^(.*/)?.*~$
- ^(.*/)?.*\.py[co]$
- ^(.*/)?.*/RCS/.*$
- ^(.*/)?\..*$
service_main.py:
import os
import logging
import webapp2
from google.cloud.pubsub_v1 import PublisherClient
logger = logging.getLogger('service_main')
logger.setLevel(logging.WARNING)
class ServiceTaskMainHandler(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write('test')
config = {
'webapp2_extras.sessions': {
'secret_key': 'YOUR_SECRET_KEY'
}
}
MAIN_ROUTE = [
webapp2.Route('/', ServiceTaskMainHandler, name='main'),
]
app = webapp2.WSGIApplication(MAIN_ROUTE, debug=True, config=config)
tree lib/google/cloud/pubsub_v1
lib/google/cloud/pubsub_v1
├── exceptions.py
├── exceptions.pyc
├── futures.py
├── futures.pyc
├── gapic
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── publisher_client_config.py
│   ├── publisher_client_config.pyc
│   ├── publisher_client.py
│   ├── publisher_client.pyc
│   ├── subscriber_client_config.py
│   ├── subscriber_client_config.pyc
│   ├── subscriber_client.py
│   └── subscriber_client.pyc
├── _gapic.py
├── _gapic.pyc
├── __init__.py
├── __init__.pyc
├── proto
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── pubsub_pb2_grpc.py
│   ├── pubsub_pb2_grpc.pyc
│   ├── pubsub_pb2.py
│   └── pubsub_pb2.pyc
├── publisher
│   ├── batch
│   │   ├── base.py
│   │   ├── base.pyc
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── thread.py
│   │   └── thread.pyc
│   ├── client.py
│   ├── client.pyc
│   ├── exceptions.py
│   ├── exceptions.pyc
│   ├── futures.py
│   ├── futures.pyc
│   ├── __init__.py
│   └── __init__.pyc
├── subscriber
│   ├── client.py
│   ├── client.pyc
│   ├── futures.py
│   ├── futures.pyc
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── message.py
│   ├── message.pyc
│   ├── _protocol
│   │   ├── bidi.py
│   │   ├── bidi.pyc
│   │   ├── dispatcher.py
│   │   ├── dispatcher.pyc
│   │   ├── heartbeater.py
│   │   ├── heartbeater.pyc
│   │   ├── helper_threads.py
│   │   ├── helper_threads.pyc
│   │   ├── histogram.py
│   │   ├── histogram.pyc
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── leaser.py
│   │   ├── leaser.pyc
│   │   ├── requests.py
│   │   ├── requests.pyc
│   │   ├── streaming_pull_manager.py
│   │   └── streaming_pull_manager.pyc
│   ├── scheduler.py
│   └── scheduler.pyc
├── types.py
└── types.pyc
The reason your code failed is because App Engine Standard's Python2.7 runtime does not support Pub/Sub Cloud Client Library, only Pub/Sub API Client Library. There's some new code samples showing how to use Pub/Sub with App Engine Standard.
import googleapiclient.discovery
import base64
service = build('pubsub', 'v1')
topic_path = 'projects/{your_project_id}/topics/{your_topic}'
service.projects().topics().publish(
topic=topic_path, body={
"messages": [{
"data": base64.b64encode(data)
}]
}).execute()
Update: Both GAE (Google App Engine) Standard and GAE Flexible Python 3 Runtime support Cloud Pub/Sub Client Library.

Can't make test execute

Folders structure:
.
├── db.sqlite3
├── homepage
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
├── photoarchive
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── somesite
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-34.pyc
│   │   ├── settings.cpython-34.pyc
│   │   ├── urls.cpython-34.pyc
│   │   └── wsgi.cpython-34.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── tests
├── functional_test.py
├── __init__.py
├── __pycache__
│   ├── functional_test.cpython-34.pyc
│   ├── __init__.cpython-34.pyc
│   └── validators.cpython-34.pyc
└── validators.py
functional_test.py
from selenium import webdriver
from django.test import TestCase
import pdb
class HomePageTest(TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
pdb.set_trace()
def tearDown(self):
self.browser.quit()
def test_home_page(self):
#Edith goes to home page.
self.browser.get("http://localhost:8000")
#Edith sees "Hello, world" in the browser title.
estimated_browser_title ="Hello, world"
real_browswer_title = self.browser.title
self.assertIn(estimated_browser_title, real_browswer_title)
I run the test:
(venv) michael#michael:~/workspace/mysite/somesite$ python manage.py test tests
Creating test database for alias 'default'...
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Destroying test database for alias 'default'...
Could you help me understand why my tests are not executed. I set a pdb breakpoint. The interpreter doesn't stop at that breakpoint. Well, tests are ignored.
Could you give me a kick here?
Django's test runner will only discover tests inside apps that are included in INSTALLED_APPS. Rather than putting your code in a functional_test.py file inside a tests directory, you should put it in a file called tests.py inside one of the app directories.

auto importing python classes in flask shell not working as expected

So I have a flask app structured in this manner
calvin % tree -L 3 .
.
├── README
├── alembic
│   ├── README
│   ├── env.py
│   ├── env.pyc
│   ├── script.py.mako
│   └── versions
├── alembic.ini
├── api.sublime-project
├── app
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── admin
│   │   ├── __init__.py
│   │   └── __init__.pyc
│   ├── agencies
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── models.py
│   │   └── models.pyc
│   ├── agents
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── models.py
│   │   ├── models.pyc
│   │   ├── views.py
│   │   └── views.pyc
│   ├── api.py
│   ├── api.pyc
│   ├── auth
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── constants.py
│   │   ├── constants.pyc
│   │   ├── decorators.py
│   │   ├── decorators.pyc
│   │   ├── models.py
│   │   ├── models.pyc
│   │   ├── views.py
│   │   └── views.pyc
│   ├── districts
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── models.py
│   │   ├── models.pyc
│   │   ├── views.py
│   │   └── views.pyc
│   ├── helpers.py
│   ├── helpers.pyc
│   ├── middleware.py
│   ├── middleware.pyc
│   ├── models.py
│   ├── models.pyc
│   ├── properties
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── models.py
│   │   └── models.pyc
│   ├── templates
│   │   └── index.html
│   ├── users
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── models.py
│   │   ├── models.pyc
│   │   ├── views.py
│   │   └── views.pyc
│   └── viewings
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── models.py
│   ├── models.pyc
│   ├── views.py
│   └── views.pyc
├── config.py
├── config.pyc
├── manage.py
├── requirements.txt
├── run.py
└── shell.py
I am setting up my shell so that it auto-imports all the classes located in the models.py files when I execute ./manage.py shell
And this is the script in manage.py that is intended to achieve that (reference flask-script docs)
def _make_context():
from app import models
return dict(app=app, db=db, models=models) # TODO: this is not working appropriately
manager.add_command("shell", Shell(make_context=_make_context))
In my app/models.py, I have import statements from every module, "agencies", "auth" etc etc.
However, when I enter my shell environment, I have to access my classes as models.Users instead of directly Users, which is not what I am expecting. How do I auto-import everything so that I can access the classes directly?
Below is a simplified solution that assumes you're using SQLAlchemy (db.Model). If not, you should only need to change the issubclass if-statement to match your appropriate check of what to import.
from app import db, create_app
import app.models as models
from flask.ext.script import Manager, Shell
app = create_app()
manager = Manager(app)
def make_shell_context():
return_dict = {}
# grab everything we can possibly import from the models module
module_importables = dir(models)
for importable in module_importables:
# if it isn't a class, it'll throw a TypeError exception that importable is not a class
try:
# we only want our SQLAlchemy models
if issubclass(getattr(models,importable),db.Model):
return_dict[importable] = getattr(models,importable)
except TypeError as inst:
pass
return_dict['app'] = app
return_dict['db'] = db
return return_dict
manager.add_command("shell", Shell(make_context=make_shell_context))
if __name__ == '__main__':
manager.run()
Instead of
from app import models
You can do:
from app.models import *
This will import all classes,variables from models. Note: It is usually not recommended to import * but in this case, it could work for you. Ideally, you should do something like:
from app.models import Users, ...and so on