Tests for django app produces template not found error for "render_to_string" when executed via Fabric - django

When I run tests on my remote server using fabric, I get an error saying:
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 138, in find_template
raise TemplateDoesNotExist(name)
TemplateDoesNotExist: index.html
I am trying to render the template as a string using "render_to_string()"
If I login to the server and run tests manually (python manage.py test app), it is working properly. This error occurs while running through fabric.
Here is my fabric code:
from __future__ import with_statement
from fabric.api import local
import os
from fabric.api import *
env.hosts = ['server.com']
production_project_path = '/path/to/production/app/'
def run_remote_test():
run("python %s/manage.py test app"%production_project_path)
Did I miss something?
Note: I am not using virtual environment

Then let's make this official. ;)
In this case, the problem was the fact that manage.py expects to be ran from the project directory, so rewriting the abovestanding as:
from __future__ import with_statement
from fabric.api import local
import os
from fabric.api import *
env.hosts = ['server.com']
production_project_path = '/path/to/production/app/'
def run_remote_test():
with cd(production_project_path):
run("python manage.py test app")
has fixed the issue.

Related

celery 4.4.2 and django 3.0.2 raising self.notregistered error but calling the function in python manage.py shell works fine

I am trying to add celery to my django project.
everything works fine when i run it from the manage.py shell, my celery worker returns the result of the add() function.
when i call this function from my view it raises a not registered error and a module object not callable error on celery/base.py line 1253
celery/app/base.py", line 1253, in loaderreturn get_loader_cls(self.loader_cls)(app=self)
TypeError: 'module' object is not callable
raise self.NotRegistered(key)
celery.exceptions.NotRegistered: 'home.tasks.add'
both are from the apache error log
my home.tasks.py looks like this
from celery import shared_task
from celery.schedules import crontab
from django.db import connection
from django.utils import timezone, translation
#import pandas as pd
from home.models import *
from residence_management.models import *
from sqlalchemy import *
from django.conf import settings
from django.contrib.auth.models import User
from decimal import Decimal
#shared_task
def add(x, y):
return x + y
my view where i call the task has the import: from home.tasks import add
in the view itself i just call add(9, 5) and it fails with the above error (without the #shared_task decorator it works fine).
when calling the function in the shell, even with the #shared_task decorator it works fine, i can start the celery worker without problems as well.
[2020-05-13 08:47:23,862: INFO/MainProcess] Received task: home.tasks.add[f7e50f7d-4e3d-4372-bf3e-e1c7175c7a2a]
[2020-05-13 08:47:23,879: INFO/ForkPoolWorker-8] Task home.tasks.add[f7e50f7d-4e3d-4372-bf3e-e1c7175c7a2a] succeeded in 0.015277621999999713s: 14
any ideas where the problem might be? i use redis for the broker and result backend
You can check docs and comments for shared_task on github https://github.com/celery/celery/blob/9d49d90074445ff2c550585a055aa222151653aa/celery/app/init.py
I think for some reasons you do not run creating of celery app. It is better in this case use explicit app.
from .celery import app
#app.task()
def add(x, y):
return x + y

Cannot import module to begin basic Flask app

So I'm following a beginners tutorial on Flask and for whatever reason am getting an error on what is essentially the very first step.
I first created an "app" directory where I created a python file for "init.py" which contains the following code:
from flask import Flask
app = Flask(__name__)
from app import routes
I then created a "routes.py" python file in the same directory:
from app import app
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
Finally (and this is where the problem stems from), I created a python file named "microblog.py" which is located in the same folder as the "app" directory:
from app import app
I then go to my virtual environment and run (using cmd windows):
set FLASK_APP=microblog.py
So far so good, however when I try to run the following code in cmd:
flask run
I get the following error:
ImportError: cannot import name 'app' from 'app' (C:\Users\Grae_\microblog\app\__init__.py)
If any further clarification is needed, here are my file locations:
C:\Users\Grae_\microblog
C:\Users\Grae_\microblog\app
C:\Users\Grae_\microblog\__init__.py
C:\Users\Grae_\microblog\routes.py
C:\Users\Grae_\microblog\venv
C:\Users\Grae_\microblog\microblog.py
Apologies if this is really obvious, I'm just obviously very new to Flask and have been stuck on this for a while.
Thanks
The issue here is on python package "app". The directory should have a file named __init__.py instead of init.py.
For example, you rename the file init.py to __init__.py and replace content with below code it should work
from flask import Flask
app = Flask(__name__)
def start():
from app import routes
start()
You can do something like this:-
test.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Index!"
#app.route("/hello")
def hello():
return "Hello World!"
#app.route("/members")
def members():
return "Members"
#app.route("/members/<string:name>/")
def getMember(name):
return name</string:name>
if __name__ == "__main__":
app.run()
In command prompt, run the command-
python test.py
Try the URLs in your browser:
http://127.0.0.1:5000/
http://127.0.0.1:5000/hello
http://127.0.0.1:5000/members
http://127.0.0.1:5000/members/Karan/

Flask Application returning ImportError: No module named user_auth.views

I'm in the beginning stages of a Flask application. The problems I'm having is that whenever I attempt to run the application I get:
app/application/___init___.py, line 11 in <module>
from user_auth.views import auth
ImportError: No module named user_auth.views
I have no idea what the problem is. The import for the home.view did this as well, then it stopped and worked fine on the local server. Been trying to figure this out for the longest, there aren't that many moving parts in the application as of yet, so not sure why this is happeninng. File structure and code below:
|app
|-application
|--__ init __.py
|--home
|--user_auth
|----forms.py
|----views.py
|----templates
|----static
My application/__ init __.py file:
from flask import Flask
app = Flask(__name__)
app.config.from_object('_config')
from home.views import home
from user_auth.views import auth
app.register_blueprint(home)
app.register_blueprint(auth)
My application/user_auth/views.py
from flask import Blueprint
auth = Blueprint('auth', __name__,
url_prefix='/user_auth',
template_folder='templates',
static_folder='static')
You're missing an __init__.py file under ./user_auth/ to make user_auth a module.
There's more information about modules in the docs.

Running django unit tests from shell with ipython notebook has strange behavior

I'm using an ipyhton notebook connected to Django shell to run some tests. I am on django 1.4.
First, if I run as configured below sometimes it works perfectly and other times, it just hangs with no output and no errors. I have to completely kill the ipyhton kernel and close all notebooks and try again (when the hang event occurs, all open notebooks stop working)
If i inherit from unittest.TestCase instead of django.test.TestCase it works perfect every time. However, I need the latter so i can use the django's TestCase.client in my actual tests.
NOTE: In both cases I am skipping the test database because I'm getting a failure on a missing celery database. I will cross that bridge at another time.
The notebook:
from django.utils import unittest
from django.test import TestCase
from django.test.utils import setup_test_environment
from django.test.simple import DjangoTestSuiteRunner
class MyTestCase(TestCase):
def test_001(self):
print "ok"
def test_002(self):
self.assertEqual(True , True)
if __name__ == '__main__':
setup_test_environment()
runner = DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True)
suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)
#old_config = runner.setup_databases()
result = runner.run_suite(suite)
#runner.teardown_databases(old_config)
runner.suite_result(suite, result)
In my case, I just created a test_runner function that accepts a test_class parameter, like this:
def test_runner(test_class):
from django.utils import unittest
from django.test.utils import setup_test_environment
from django.test.simple import DjangoTestSuiteRunner
setup_test_environment()
runner = DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True)
suite = unittest.TestLoader().loadTestsFromTestCase(test_class)
result = runner.run_suite(suite)
runner.suite_result(suite, result)
After that, you could just run:
test_runner(MyTestCase)
in ipython notebook.
Make sure to use the one that's provided by django-extensions, by running:
manage.py shell_plus --notebook
Hope that helps.

django import client

i am trying to import the client in django for testing. but when i do, i get this wierd error:
ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
from django.utils import unittest
from django.utils import simplejson as json
from django.test.client import Client
this is how i imported the client so that i could use it for testing. can someone explain this to me please.
Try this:
import os
import sys
sys.path.append('/home/username/www/site_folder')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from django.utils import unittest
from django.utils import simplejson as json
from django.test.client import Client
But replace project with folder name, where your settings.py is
The Client is looking for the settings.py. You could simply load the client by typing this in your project folder:
python manage.py shell
In Pycharm which I use, after following this Running Django tests in PyCharm
my problem was solved.
It's in the file > settings > Django Support, and then select the right settings.