Views.py
def time_consuming_task_caller(time_to_sleep, j):
print ('start', task_id)
# time.sleep(time_to_sleep)
# print('finished', task_id)
def time_consuming_task_caller(time_to_sleep, j):
Process(target=time_consuming_task, args=(time_to_sleep, task_id)).start()
print ('processing...', task_id)
return {'one': 'two'}
def get_task(request):
if request.method == 'GET':
response = time_consuming_task_caller(5,1) # 5 is like time to sleep, 1 is task id.
print(response)
return HttpResponse(json.dumps(response), content_type="application/json")
This causes error at return HttpResponse(json.dumps(response), content_type="application/json") because it prints all three print statements (except the commented one)
Even with time.sleep() commented it causes the error. Ultimate goal is to make it work for processes that may take longer to execute.
EDIT
urls.py
urlpatterns = [
path('api/', get_task ,name='run')
]
Error
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "c:\users\user\appdata\local\programs\python\python36\Lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "c:\users\user\appdata\local\programs\python\python36\Lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
File "D:\Programming\django_project\webapp - Dev\server 3\manager\utils.py", line 1, in <module>
from .models import Task
File "D:\Programming\django_project\webapp - Dev\server 3\manager\models.py", line 2, in <module>
from accounts.models import CustomUser
File "D:\Programming\django_project\webapp - Dev\server 3\accounts\models.py", line 2, in <module>
from django.contrib.auth.models import AbstractUser
File "D:\Programming\django_project\env_django\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "D:\Programming\django_project\env_django\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "D:\Programming\django_project\env_django\lib\site-packages\django\db\models\base.py", line 100, in __new__
app_config = apps.get_containing_app_config(module)
File "D:\Programming\django_project\env_django\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config
self.check_apps_ready()
File "D:\Programming\django_project\env_django\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
from the stack trace you provided the error might also be caused by your models file (which you didn't include).
But the right way to implement such functionality is to use a task runner like
celery
Related
I am not able to access (fetch) those urls mentioned in program
urls.py
from django.conf.urls import include, url
from rest_framework import routers
from imgstore.views import QueryImage
from imgstore.views import ImageActionViewSet
# this is DRF router for REST API viewsets
router = routers.DefaultRouter()
router.register(r'api/v1/imgaction', ImageActionViewSet, r"imgaction")
router.register(r'api/v1/queryimage', QueryImage, r"queryimage")
urlpatterns = [
url(r'', include(router.urls, namespace='imgaction')),
url(r'', include(router.urls, namespace='queryimage'))
]
I receive this error:
Error occured while running server:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/urls/resolvers.py", line 581, in url_patterns iter(patterns)TypeError: 'module' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/root/.pyenv/versions/3.5.7/lib/python3.5/threading.py", line 914, in _bootstrap_innerself.run()
File "/root/.pyenv/versions/3.5.7/lib/python3.5/threading.py", line 862, in runself._target(*self._args, **self._kwargs)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapperfn(*args, **kwargs)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_runself.check(display_num_errors=True)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks,
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checksreturn checks.run_checks(**kwargs)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checksnew_errors = check(app_configs=app_configs)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolverreturn check_method()
File"/root/.pyenv/versions/3.5.7/lib/python3.5/sitepackages/django/urls/resolvers.py", line 398, in checkfor pattern in self.url_patterns:
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/utils/functional.py", line 80, in __get__res = instance.__dict__[self.name] = self.func(instance)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/urls/resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'image_storage.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
And I have no idea about to solve it. What am I missing?
Check the file urls.py that may exist in image_storage django app. It should contain a valid django url configuration and not be empty!
So often times this is caused by some exception when Django's resolvers.py tries to consume your urls.py.
The way I generally solve it is to wrap my entire urls.py file (along with all other urls.py files) in a try-except block, and print the exception that gets caught, which is often much more immediately useful to solving the problem than the default one Django provides.
Good luck!
Well, I am writing a Flask project, but when I tried to python manage.py
The traceback told me that:
Traceback (most recent call last):
File "manage.py", line 5, in <module>
from app import db,create_app
File "/home/humbert/2017-sharing-backend/sharing/app/__init__.py", line 42, in <module>
app.register_blueprint(main_blueprint, url_prefix='/main')
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/app.py", line 64, in wrapper_func
return f(self, *args, **kwargs)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/app.py", line 951, in register_blueprint
blueprint.register(self, options, first_registration)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/blueprints.py", line 154, in register
deferred(state)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/blueprints.py", line 173, in <lambda>
s.add_url_rule(rule, endpoint, view_func, **options))
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/blueprints.py", line 76, in add_url_rule
view_func, defaults=defaults, **options)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/app.py", line 64, in wrapper_func
return f(self, *args, **kwargs)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/app.py", line 1043, in add_url_rule
rule = self.url_rule_class(rule, methods=methods, **options)
TypeError: __init__() got an unexpected keyword argument 'method'
I think my manage.py is right,and I can't figure out the mistake.
The mistake part of __init__.py is that:
from .main import main as main_blueprint
app.register_blueprint(main_blueprint, url_prefix='/main')
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix="/auth")
from . import views
I really need some help, thanks!
I had a similar problem. In my code I had a line
#bp.route('/<init:id>/delete', method=('POST'))
The keyword method needs to be changed to methods(with an s)
I had encountered a similar problem in my code and just had to change the keyword "method" to "methods":
#app.route('/login', methods = ['GET', 'POST'])
I am trying to build a view where forms are loaded dynamically based on the form slug, the available forms are defined in a list of tuples like this, this is meant to speed up development of new forms in a "framework-like" way:
#installed_io.py
forms = [("json",JsonForm),("csv",CsvForm),....]
froms are defined in the forms.py module as usual.
from django import forms
class FileForm(BaseDatasetForm):
file = forms.FileField(label="Opcion 1: Seleccione un archivo", required=False)
text = forms.CharField(widget=forms.Textarea, label="Opction 2: Introduzca el contenido en este campo", required=False)
utils.py defines the function to dynamically select the Form class:
from installed_io import installed_inputs
def get_input_form(slug):
for entry in installed_inputs:
if entry[0] == slug:
return entry[1]
raise NotImplementedError("The required form is not implemented or missing from the installed inputs")
The view is defined in the views.py module of my django app:
#views.py
from utils import get_input_form
#login_required
def add(request, slug):
InputForm = get_input_form(slug)
if request.method == "POST":
form = InputForm(request.POST, request.FILES)
if form.is_valid():
object_id = form.save()
messages.success(request, "Dataset created")
return redirect(reverse("input:dataset", args=[str(object_id.inserted_id)]))
else:
form = InputForm()
return render(request, "datasets/add-form.html", {"form":form})
but I'm getting this import error:
python manage.py runserver
Unhandled exception in thread started by <function wrapper at 0x7fe9c465c398>
Traceback (most recent call last):
File "/home/jesus/workspace/tensorflow-board-django/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/jesus/workspace/tensorflow-board-django/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/jesus/workspace/tensorflow-board-django/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/home/jesus/workspace/tensorflow-board-django/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/jesus/workspace/tensorflow-board-django/venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/jesus/workspace/tensorflow-board-django/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/jesus/workspace/tensorflow-board-django/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/jesus/workspace/tensorflow-board-django/tensorflow_board_django/analysis/models.py", line 2, in <module>
from ..input.forms import SOURCES
File "/home/jesus/workspace/tensorflow-board-django/tensorflow_board_django/input/forms.py", line 2, in <module>
from utils import save_dataset
File "/home/jesus/workspace/tensorflow-board-django/tensorflow_board_django/input/utils.py", line 2, in <module>
from installed_io import installed_inputs
File "/home/jesus/workspace/tensorflow-board-django/tensorflow_board_django/input/installed_io.py", line 1, in <module>
from forms import FileForm
ImportError: cannot import name FileForm
What I've tried:
Changing the import statements using absolute paths
Deleting pyc files
Using dot notation to import modules
Trying to save the installed_input list on init.py
Only moving all the code to the views.py file worked, but I find this solution to be very monolithic and non-pythonic.
Based on the comments on the original post I made the following changes to my code:
instead of importing classes on installed_io module I used strings:
#installed_io.py
forms = [("json","JsonForm"),("csv","CsvForm"),....]
then I changed utils.py to import the class from string:
from installed_io import installed_inputs
def get_input_form(slug):
for entry in installed_inputs:
if entry[0] == slug:
module = importlib.import_module("tensorflow_board_django.io.forms")
class_name = entry[1]
return getattr(module, class_name)
raise NotImplementedError("The required form is not implemented or missing from the installed inputs")
Here is what I have done so far,
1) I installed Django, and started a project using:
django-admin.py startproject helloworld
2) I downloaded django non-rel, djangotoolbox and django-mongodb-engine
I installed these using
sudo python setup.py install
3) Added djangotoolbox to INSTALLED_APPS, and added django_mongodb_engine as database back end engine.
4) I have a sample model like this:
from django.db import models
from djangotoolbox import *
class Post(models.Model):
title = models.CharField()
text = models.TextField()
tags = ListField()
comments = ListField()
5) Started python repl using: python manage.py shell
6) And did this:
from hello.models import Post
post = Post.objects.create(
... title='Hello MongoDB!',
... text='Just wanted to drop a note from Django. Cya!',
... tags=['mongodb', 'django']
... )
I got this error, I don't know how to fix this
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 416, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 546, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 650, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 215, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1675, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 237, in get_compiler
return connection.ops.compiler(self.compiler)(self, connection, using)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/__init__.py", line 703, in compiler
self._cache = import_module(self.compiler_module)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/home/Desktop/helloworld/django_mongodb_engine/compiler.py", line 18, in <module>
from djangotoolbox.db.basecompiler import (
File "/usr/local/lib/python2.6/dist-packages/djangotoolbox-1.4.0-py2.6.egg/djangotoolbox/db/basecompiler.py", line 9, in <module>
from django.db.models.sql.constants import LOOKUP_SEP, MULTI, SINGLE
ImportError: cannot import name LOOKUP_SEP
What am i doing wrong here? how do i fix it?
LOOKUP_SEP was here in Django 1.4, but has been removed in 1.5, so my guess is you are using an olfer version of djangotoolbox.
You probably need to update your packages, try to follow the instructions here: http://django-mongodb-engine.readthedocs.org/en/latest/topics/setup.html
I have this piece of code which is running perfectly on localhost but throws up this obscure error on GAE:
import_string() failed for 'webapp2_extras.appengine.auth.models.User' . Possible reasons are: - missing __init__.py in a package; - package or module
My import statements:
from webapp2_extras import auth
from webapp2_extras import sessions
from webapp2_extras.auth import InvalidAuthIdError
from webapp2_extras.auth import InvalidPasswordError
Usage of auth's user model:
user = self.auth.store.user_model.create_user(username, password_raw = password, email = email)
if not user[0]: #returns a tuple with [boolean, user_info]
return 'Create user error'
else:
self.set_flash("Thank you for registering. Please login!")
self.redirect(self.auth_config['login_url'])
Full code
UPDATE (Full stack trace)
import_string() failed for 'webapp2_extras.appengine.auth.models.User'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Original exception:
ImportError: No module named ndb
Debugged import:
- 'webapp2_extras' found in '/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/__init__.pyc'.
- 'webapp2_extras.appengine' found in '/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/appengine/__init__.pyc'.
- 'webapp2_extras.appengine.auth' found in '/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/appengine/auth/__init__.pyc'.
- 'webapp2_extras.appengine.auth.models' not found.
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/base/data/home/apps/s~webapp-auth/1.358936463581927371/main.py", line 34, in dispatch
response = super(BaseHandler, self).dispatch()
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~webapp-auth/1.358936463581927371/main.py", line 127, in post
user = self.auth.store.user_model.create_user(username, password_raw = password, email = email)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 701, in __get__
value = self.func(obj)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/auth.py", line 131, in user_model
cls = self.config['user_model'] = webapp2.import_string(cls)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1824, in import_string
return getattr(__import__(module, None, None, [obj]), obj)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2_extras/appengine/auth/models.py", line 13, in <module>
from ndb import model
Look similar to this issue which was already fixed by webapp 2.5.1
Make sure you import the latest version of webapp2, by adding those line to your app.yaml file:
libraries:
- name: webapp2
version: latest
As a workaround you can add the following lines to your application:
import sys
from google.appengine.ext import ndb
sys.modules['ndb'] = ndb