Installed Celery but it does not implement tasks - django

I,m using Amazon web services. And I'm trying to make Celery work.
Tried to do what the documentation says (http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#configuring-your-django-project-to-use-celery), but when I start celery worker and try to call a task nothing happens, as if there were no task.
Here's my settings.py file:
import os
import djcelery
import djkombu
import sys
import tasks
sys.path.append(os.getcwd())
djcelery.setup_loader()
# Django settings for analogg project.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Nikita', 'bodnarnikita#gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'analoggdb', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/static/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = 'http://analogg.info/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
ADMIN_MEDIA_PREFIX = '/static/admin/'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'analogg.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'analogg.wsgi.application'
TEMPLATE_DIRS = (
"/templates/",
"/home/ubuntu/analogg/templates",
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
)
INSTALLED_APPS += ('djcelery', )
#INSTALLED_APPS += ('djkombu', )
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
CELERY_SEND_TASK_ERROR_EMAILS = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_IMPORTS = ("analogg.tasks", )
#BROKER_URL = 'amqp://guest:guest#localhost:5672/'
#BROKER_BACKEND = "djkombu.transport.DatabaseTransport"
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
This is my views.py file:
# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect, HttpResponse
from django.template import Context, loader, RequestContext
from django.shortcuts import render_to_response
from tasks import parsesob, add
from parsersob import parser
import os, random, string
def index(request):
html = "<html><body>Hello, world!</body></html>"
add.apply_async(args=[id, '23bnn'])
return HttpResponse(html)
This is my tasks.py file:
from celery.decorators import task
from celery.task.schedules import crontab
from parsersob import parser
#from parsersob2 import parser2
from celery import Celery
#celery = Celery('tasks', broker='amqp://rabbitmqprelaunch9176#ip-10-117-81-80//')
#task
def add(id, a1, a2):
f = open('add.txt', 'w')
g = a1 + a2
f.write(g)
f.close()
And this is my celeryconfig.py file being in the same folder with tasks.py, settings.py and views.py:
#BROKER_URL = 'amqp://'
#CELERY_RESULT_BACKEND = 'analoggdb'
#BROKER_URL = "amqp://guest:guest#localhost:5672//"
CELERY_IMPORTS = ("analogg.tasks", )
#CELERY_RESULT_DBURI = "sqlite:///analoggdb.db"
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Europe/Moscow'
CELERY_ENABLE_UTC = True
I'm a newbie, so could anyone please tell me what to do to make it work.
Any help will be greatly appreciated.
UPD:
ubuntu#ip-10-117-81-80:/var/log/apache2$ sudo rabbitmqctl status
Status of node 'rabbit#ip-10-117-81-80' ...
[{pid,849},
{running_applications,[{rabbit,"RabbitMQ","2.7.1"},
{os_mon,"CPO CXC 138 46","2.2.7"},
{sasl,"SASL CXC 138 11","2.1.10"},
{mnesia,"MNESIA CXC 138 12","4.5"},
{stdlib,"ERTS CXC 138 10","1.17.5"},
{kernel,"ERTS CXC 138 10","2.14.5"}]},
{os,{unix,linux}},
{erlang_version,"Erlang R14B04 (erts-5.8.5) [source] [64-bit] [rq:1] [async-threads:30] [kernel-poll:true]\n"},
{memory,[{total,25494568},
{processes,11083752},
{processes_used,11077008},
{system,14410816},
{atom,1124433},
{atom_used,1120234},
{binary,89696},
{code,11134393},
{ets,752120}]},
{vm_memory_high_watermark,0.3999999990304762},
{vm_memory_limit,247544217}]
...done.
The output of running celeryd:
ubuntu#ip-10-117-81-80:~/analogg$ python manage.py celeryd worker --loglevel=info
-------------- celery#ip-10-117-81-80 v3.0.3 (Chiastic Slide)
---- **** -----
--- * *** * -- [Configuration]
-- * - **** --- . broker: amqp://guest#localhost:5672//
- ** ---------- . app: default:0x13c2a90 (djcelery.loaders.DjangoLoader)
- ** ---------- . concurrency: 1 (processes)
- ** ---------- . events: OFF (enable -E to monitor this worker)
- ** ----------
- *** --- * --- [Queues]
-- ******* ---- . celery: exchange:celery(direct) binding:celery
--- ***** -----
[Tasks]
. analogg.tasks.add
. analogg.tasks.parsesob
[2012-07-22 06:24:30,336: WARNING/MainProcess] celery#ip-10-117-81-80 has started.
UPD:
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] mod_wsgi (pid=7411): Exception occurred processing WSGI script '/home/ubuntu/analogg/apache/django.wsgi'.
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] Traceback (most recent call last):
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] response = self.get_response(request)
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 82, in get_response
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] urlconf = settings.ROOT_URLCONF
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 185, in inner
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] return func(self._wrapped, *args)
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] mod_wsgi (pid=7377): Exception occurred processing WSGI script '/home/ubuntu/analogg/apache/django.wsgi'.
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] Traceback (most recent call last):
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] response = self.get_response(request)
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 82, in get_response
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] urlconf = settings.ROOT_URLCONF
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 185, in inner
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] return func(self._wrapped, *args)
[Sun Jul 22 08:10:58 2012] [error] [client 37.110.0.126] AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'

I'm not quite sure what is the problem here, but here is an example config, that works:
This is located at the end of settings.py:
#CELERY CONFIG
import djcelery
djcelery.setup_loader()
BROKER_HOST = "Host"
BROKER_PORT = "Port"
BROKER_USER = "User"
BROKER_PASSWORD = "Pass"
BROKER_VHOST = "VHost"
CELERY_DEFAULT_QUEUE = "some_queue"
CELERY_DEFAULT_EXCHANGE = "some_exc"
The broker's user/pass/vhost are configured using the rabbitmqctl tool
You can trace the queue/exchange with
rabbitmqadmin get queue="some_queue"
NOTE: It is very useful to track the logs in /var/log/rabbitmq/rabbit#localhost.log or whatever the log file is. This will show you if there is a problem with the connection to RabbitMQ, like wrong credentials, permissions, etc.

Related

robot with django not working in setting up with module not found

I am trying to set up robot framework on django application. I am testing on a skeleton applciation. Following these instructions https://github.com/kitconcept/robotframework-djangolibrary i get error
% robot tests/test.robot
[ ERROR ] Error in file '/Users/user/hci/pipeline/app/tests/test.robot' on line 13: Importing library 'MIDDLEWARE_CLASSES' failed: ModuleNotFoundError: No module named 'MIDDLEWARE_CLASSES'
Traceback (most recent call last):
None
PYTHONPATH:
/Users/user/.pyenv/versions/3.7.2/bin
/Users/user/.pyenv/versions/3.7.2/lib/python37.zip
/Users/user/.pyenv/versions/3.7.2/lib/python3.7
/Users/user/.pyenv/versions/3.7.2/lib/python3.7/lib-dynload
/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages
==============================================================================
Test :: Django Robot Tests
==============================================================================
Scenario: As a visitor I can visit the django default page | FAIL |
Parent suite setup failed:
No keyword with name 'Start Django' found.
------------------------------------------------------------------------------
Test :: Django Robot Tests | FAIL |
Suite setup failed:
No keyword with name 'Start Django' found.
Also suite teardown failed:
No keyword with name 'Stop Django' found.
1 test, 0 passed, 1 failed
==============================================================================
Output: /Users/user/hci/pipeline/app/output.xml
Log: /Users/user/hci/pipeline/app/log.html
Report: /Users/user/hci/pipeline/app/report.html
This is the content of my files
In settings.py I have
"""
Django settings for pipeline project.
Generated by 'django-admin startproject' using Django 3.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-pn)5i&#5u$yix_%r9&t$=ww=3t8ttaxt=qymg#u^4-q#((u_v#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'demo',
'django_jenkins',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'DjangoLibrary.middleware.AutologinAuthenticationMiddleware',
'DjangoLibrary.middleware.FactoryBoyMiddleware',
'DjangoLibrary.middleware.QuerySetMiddleware',
]
MIDDLEWARE_CLASSES = (
'django.contrib.auth.middleware.AuthenticationMiddleware',
'DjangoLibrary.middleware.AutologinAuthenticationMiddleware',
'DjangoLibrary.middleware.FactoryBoyMiddleware',
'DjangoLibrary.middleware.QuerySetMiddleware',
)
ROOT_URLCONF = 'pipeline.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'pipeline.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
In test.robot i have
*** Variables ***
${HOSTNAME} 127.0.0.1
${PORT} 55001
${SERVER} http://${HOSTNAME}:${PORT}/
${BROWSER} firefox
*** Settings ***
Documentation Django Robot Tests
Library Selenium2Library timeout=10 implicit_wait=0
Library MIDDLEWARE_CLASSES ${HOSTNAME} ${PORT} path=pipeline/pipeline manage=pipeline/manage.py settings=pipeline.settings
Suite Setup Start Django and open Browser
Suite Teardown Stop Django and close Browser
*** Keywords ***
Start Django and open Browser
Start Django
Open Browser ${SERVER} ${BROWSER}
Stop Django and close browser
Close Browser
Stop Django
*** Test Cases ***
Scenario: As a visitor I can visit the django default page
Go To ${SERVER}
Wait until page contains element id=explanation
Page Should Contain It worked!
Page Should Contain Congratulations on your first Django-powered page.
I am using python3.7.2
UPDATE
I have updated it but now i get this error
% robot tests/test.robot
==============================================================================
Test :: Django Robot Tests
==============================================================================
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
No changes detected
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
------------------------------------------------------------------------------
Django started (PID: 51422)
------------------------------------------------------------------------------
Scenario: As a visitor I can visit the django default page | FAIL |
Parent suite setup failed:
WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
------------------------------------------------------------------------------
Django stopped (PID: 51422)
------------------------------------------------------------------------------
Test :: Django Robot Tests | FAIL |
Suite setup failed:
WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
1 test, 0 passed, 1 failed
==============================================================================
Output: /Users/user/hci/pipeline/app/output.xml
Log: /Users/user/hci/pipeline/app/log.html
Report: /Users/user/hci/pipeline/app/report.html

Subprocess and os.Popen in django not running under apache with mod_wsgi at Linux Fedora30

I have problem to run Os.Popen and subprocess in django under apache server of linux fedora30
when I deploy django app on apache I can't run below command in linux with django under apache:
command2 = "[ -f /home/mohammad/file_sharing.txt ] || echo 'server IP: '%s'\n\nPath File:'%s'\n\nMount Point:'%s > /home/mohammad/file_sharing.txt " %(IP_Server_File_Sharing,Path_File_Sharing,Mount_Point)
k = os.popen(command2)
command1 = "[ -f /home/mohammad/file_sharing.txt ] && echo 'server IP: '%s'\n\nPath File:'%s'\n\nMount Point:'%s > /home/mohammad/file_sharing.txt " %(IP_Server_File_Sharing,Path_File_Sharing,Mount_Point)
k1 = os.popen(command1)
These are all jobs that do :
1. I use Fedora30
2. Then install and update yum and other packeges such below command:
yum update
sudo systemctl stop firewalld.service
yum install python-pip python-devel python3-pip python3-devel
pip3 install --upgrade pip
pip3 install virtualenv
dnf install httpd
yum install python3-mod_wsgi.x86_64
3. Then make a directory and install Django on virtual env:
mkdir /home/mohammad/myweb1
cd myweb1
virtualenv venv
source venv/bin/activate
4. Then pip install below packages:
asgiref==3.3.1
Django==3.1.5
psycopg2-binary==2.8.6
python-pam==1.8.4
pytz==2020.5
sqlparse==0.4.1
5. Then config other settings of django :
django-admin startproject myproject
cd myproject
python manage.py startapp main
python manage.py collectstatic
python manage.py makemigrations
python manage.py migrate
6. now config settings.py
After these 5 steps I configure settings.py in django:
ALLOWED_HOSTS = ['*']
STATIC_ROOT ='/home/mohammad/myweb1/myproject/main/static/'
7. apache config which make django.conf file in in /etc/httpd/conf.d/ and named django.conf
<VirtualHost *:80>
Alias /static /home/mohammad/myweb1/myproject/main/static
<Directory /home/mohammad/myweb1/myproject/main/static>
Require all granted
</Directory>
<Directory /home/mohammad/myweb1/myproject/myproject>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIApplicationGroup %{GLOBAL}
WSGIDaemonProcess myproject python-path=/home/mohammad/myweb1/myproject python-
home=/home/mohammad/myweb1/venv
WSGIProcessGroup myproject
WSGIScriptAlias / /home/mohammad/myweb1/myproject/myproject/wsgi.py
</VirtualHost>
8. finally I run below command:
setendorce 0
chown -R apache:apache /home/mohammad/myweb1
usermod -a -G mohammad apache
chmode -R 710 /home/mohammad
9. view.py packages:
from django.conf.urls import url
from django.shortcuts import render , get_object_or_404 , redirect
from django.urls.base import resolve
from . models import Main
from django.contrib.auth import authenticate , login, logout , views
from django.http import HttpResponseRedirect
from django.urls import reverse
# import ntplib
from django.contrib.auth.models import User
from datetime import datetime,timezone
from time import ctime , sleep
import pam
import datetime
import os
import subprocess , shlex ,tempfile
from subprocess import Popen
import re
from subprocess import STDOUT , check_output , PIPE
import random
import logging
import subprocess
import io
import collections
10. view.py code of def def file_sharing(request):
if request.method == "POST":
IP_Server_File_Sharing = request.POST.get('IP_Server_File_Sharing')
Path_File_Sharing = request.POST.get('Path_File_Sharing')
Mount_Point = request.POST.get('Mount_Point')
IP = re.compile("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
Pathfile = re.compile("^(/[^/ ]*)+/?$")
MountPoint = re.compile("^(/[^/ ]*)+/?$")
tf_IP = bool(IP.fullmatch(str(IP_Server_File_Sharing)))
tf_Pathfile = bool(Pathfile.fullmatch(str(Path_File_Sharing)))
tf_MountPoint= bool(Pathfile.fullmatch(str(Mount_Point)))
if IP_Server_File_Sharing=="" and Path_File_Sharing=="" and Mount_Point=="" :
### Create the logger
logger = logging.getLogger('User empty file_sharing field and make error')
logger.setLevel(logging.DEBUG)
### Setup the console handler with a StringIO object
log_capture_string = io.StringIO()
ch = logging.StreamHandler(log_capture_string)
ch.setLevel(logging.DEBUG)
### Optionally add a formatter
formatter = logging.Formatter('%(asctime)s - %(message)s ')
ch.setFormatter(formatter)
### Add the console handler to the logger
logger.addHandler(ch)
### Send log messages.
# logger.debug('debug message')
logger.info('User empty file_sharing field and make error')
# logger.warn('warn message')
# logger.error('error message')
# logger.critical('critical message')
### Pull the contents back into a string and close the stream
log_contents = log_capture_string.getvalue()
# log_capture_string.close()
### Output as lower case to prove it worked.
print(log_contents)
b = Main( log1 = log_contents)
b.save()
error = "هیچ فیلدی را خالی نگذارید!!!"
return render(request , 'front/error.html' , {'error':error})
if tf_IP and tf_Pathfile and tf_MountPoint \
and IP_Server_File_Sharing!="" and Path_File_Sharing!="" and Mount_Point!="" :
command2 = "[ -f /home/mohammad/file_sharing.txt ] || echo 'server IP: '%s'\n\nPath File:'%s'\n\nMount Point:'%s > /home/mohammad/file_sharing.txt " %(IP_Server_File_Sharing,Path_File_Sharing,Mount_Point)
k = os.popen(command2)
command1 = "[ -f /home/mohammad/file_sharing.txt ] && echo 'server IP: '%s'\n\nPath File:'%s'\n\nMount Point:'%s > /home/mohammad/file_sharing.txt " %(IP_Server_File_Sharing,Path_File_Sharing,Mount_Point)
k1 = os.popen(command1)
sleep(10)
command_show= "echo 'server IP: '%s'\nPath File:'%s'\nMount Point:'%s " %(IP_Server_File_Sharing,Path_File_Sharing,Mount_Point)
l = os.popen(command_show)
show = l.read()
print('-------------\n', show)
### Create the logger
logger = logging.getLogger('System overwrite file_sharing data in file_sharing.txt')
logger.setLevel(logging.DEBUG)
### Setup the console handler with a StringIO object
log_capture_string = io.StringIO()
ch = logging.StreamHandler(log_capture_string)
ch.setLevel(logging.DEBUG)
### Optionally add a formatter
formatter = logging.Formatter('%(asctime)s - %(message)s ')
ch.setFormatter(formatter)
### Add the console handler to the logger
logger.addHandler(ch)
### Send log messages.
# logger.debug('debug message')
logger.info('System overwrite file_sharing data in file_sharing.txt ')
# logger.warn('warn message')
# logger.error('error message')
# logger.critical('critical message')
### Pull the contents back into a string and close the stream
log_contents = log_capture_string.getvalue()
# log_capture_string.close()
### Output as lower case to prove it worked.
print(log_contents)
b = Main( log1 = log_contents)
b.save()
return render(request , 'front/File_sharing.html' , {'show':show} )
if not tf_IP or not tf_Pathfile or not tf_MountPoint:
### Create the logger
logger = logging.getLogger('One of the field in file sharing page is not math by pattern')
logger.setLevel(logging.DEBUG)
### Setup the console handler with a StringIO object
log_capture_string = io.StringIO()
ch = logging.StreamHandler(log_capture_string)
ch.setLevel(logging.DEBUG)
### Optionally add a formatter
formatter = logging.Formatter('%(asctime)s - %(message)s ')
ch.setFormatter(formatter)
### Add the console handler to the logger
logger.addHandler(ch)
### Send log messages.
# logger.debug('debug message')
logger.info('One of the field in file sharing page is not math by pattern')
# logger.warn('warn message')
# logger.error('error message')
# logger.critical('critical message')
### Pull the contents back into a string and close the stream
log_contents = log_capture_string.getvalue()
# log_capture_string.close()
### Output as lower case to prove it worked.
print(log_contents)
b = Main( log1 = log_contents)
b.save()
error = "تمام فیلد را را به درستی تکمیل کنید"
return render(request , 'front/error.html' , {'error':error})
return render(request , 'front/File_sharing.html' )
11. html code of this project in template directory:
{% extends 'front/master.html'%}
{% load static %}
{% block mainblock %}
<br/>
<div class="box box-danger">
<form role="form" method="POST" action="{% url 'file_sharing' %}">
{% csrf_token %}
<div class="box-header with-border" style="direction:ltr;"><i class="fa fa-fw fa-chevron-circle-right"></i>
<h3 class="box-title">File Sharing</h3>
</div>
<div class="box-body" >
<div class="row">
<div class="col-xs-4" style="direction:ltr;">
<input id="IP_Server_File_Sharing" name="IP_Server_File_Sharing" type="text" class="form-control" placeholder="192.168.0.0" required>
</div>
<div class="col-xs-4" style="direction:ltr;">
<input id="Path_File_Sharing" name="Path_File_Sharing" type="text" class="form-control" placeholder="Path File Sharing" required>
</div>
<div class="col-xs-4" style="direction:ltr;">
<input id="Mount_Point" name="Mount_Point" type="text" class="form-control" placeholder="Mount Point" required>
</div>
<br/>
</div>
<br/>
<div style="direction:ltr;">
<textarea class="form-control" rows="3" placeholder="output">{{show}}</textarea>
<br/>
</div>
<button name="x" value="Submit" type="submit" id="myButton" class="btn btn-primary">ارسال اطلاعات</button>
</form>
</div>
<!-- /.box-body -->
</div>
{% endblock %}
And the logs of apache in /var/log/httpd are:
sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper
[Fri Jan 08 19:44:44.013574 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46632] -----------------------
[Fri Jan 08 19:49:01.449617 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46664] ---------------- None
[Fri Jan 08 19:49:01.449656 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46664] optionsRadios ============= None
/bin/sh: line 4: /home/mohammad/file_sharing.txt: Permission denied
[Fri Jan 08 19:49:31.631038 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] -------------
[Fri Jan 08 19:49:31.631148 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] server IP: 127.0.0.2
[Fri Jan 08 19:49:31.631164 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] Path File:/home/
[Fri Jan 08 19:49:31.631170 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] Mount Point:/ali/
[Fri Jan 08 19:49:31.631181 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674]
[Fri Jan 08 19:49:31.631901 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] System overwrite file_sharing data in file_sharing.txt INFO System overwrite file_sharing data in file_sharing.txt
[Fri Jan 08 19:49:31.631995 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] 2021-01-08 19:49:31,631 - System overwrite file_sharing data in file_sharing.txt
[Fri Jan 08 19:49:31.632003 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674]
Attention these logs are costumized logs that I append to Datebase (postgresql):
[Fri Jan 08 19:44:44.013574 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46632] -----------------------
[Fri Jan 08 19:49:01.449617 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46664] ---------------- None
[Fri Jan 08 19:49:01.449656 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46664] optionsRadios ============= None
[Fri Jan 08 19:49:31.631038 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] -------------
[Fri Jan 08 19:49:31.631148 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] server IP: 127.0.0.2
[Fri Jan 08 19:49:31.631164 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] Path File:/home/
[Fri Jan 08 19:49:31.631170 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] Mount Point:/ali/
[Fri Jan 08 19:49:31.631181 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674]
[Fri Jan 08 19:49:31.631901 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] System overwrite file_sharing data in file_sharing.txt INFO System overwrite file_sharing data in file_sharing.txt
[Fri Jan 08 19:49:31.631995 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674] 2021-01-08 19:49:31,631 - System overwrite file_sharing data in file_sharing.txt
[Fri Jan 08 19:49:31.632003 2021] [wsgi:error] [pid 5258:tid 139771201857280] [remote 127.0.0.1:46674]
finally can any one help me to solve this problem?
I need to run Os.popen and subprocess in django under apache at linux fedora30
can I solve this problem by enable shell_exec? how? Or how can sovle Permission denied that apache access to run my linux command?
Hello and welcome to the community Amirmohammad !
Your question is too verbose, It would be enough to bring the necessary block of code and also your wsgi configuration and just tell the commands that you executed for the permission in this case.
Anyway. You are using mod_wsgi for running your Django application. So I suggest to define ServerName directive (I've name that localhost here) and pass that as a WSGIProcessGroup and it's good to specify user=username directive.
You can edit the mod_wsgi config file in this way:
WSGIDaemonProcess localhost python-path=/home/mohammad/myweb1/myproject user=mohammad
WSGIProcessGroup localhost
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot /home/mohammad/myweb1/myproject/
<Directory /home/mohammad/myweb1/myproject/main/static>
Require all granted
</Directory>
<Directory /home/mohammad/myweb1/myproject/myproject>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess localhost python-path=/home/mohammad/myweb1/myproject user=mohammad
WSGIProcessGroup localhost
Alias /static /home/mohammad/myweb1/myproject/main/static
WSGIScriptAlias / /home/mohammad/myweb1/myproject/myproject/wsgi.py
</VirtualHost>
In such a way, you don't have to chown the file to apache user. It would be your home user (mohammad).
Also you need to run popen with close_fds=True argument to prevent file descriptor inheritance (the Unix topic) .

Django: WSGI, slow when running apps.populate, only runs occasionally

I have a django app running on Apache2 and WSGI. I use PyCharm as my IDE for development.
I have the wsgi python module below, and added a print statement after application = get_wsgi_application(). When watching the logs this process takes about 1 second. What is confusing, is when this gets triggered. I have a page that sends a simple text output. I hit refresh a bunch of times, and this print gets written to the log once. If I wait a few seconds, it gets written on the next page request. If I refresh successively, it does not until I wait for a period again.
My call and response is about 10 milliseconds, but when this is executed (as verified by the print in the log) it takes about a second. This is adding a tremendous amount of unnecessary load to my server and slowing things down. I have it narrowed down to the apps.populate(settings.INSTALLED_APPS) that is called in the django.setup() method. Is there a way I can prevent this from running so often or make it run faster?
Thanks for any guidance, or advice you can offer to figure this out or prevent it.
wsgi.py:
import datetime
import os
import sys
from django.core.wsgi import get_wsgi_application
root_path = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(root_path, 'project_name'))
sys.path.insert(0, root_path)
path = '/var/www/project'
if path not in sys.path:
sys.path.append(path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
start = datetime.datetime.now()
application = get_wsgi_application()
print('Time to Populate: ' + str(datetime.datetime.now() - start))
settings.INSTALLED_APPS:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'report_builder', # Third-party tool
'business', # Internal app
'slab', # Internal app
'file', # Internal app
'training_topic', # Internal app
'item', # Internal app
'person', # Internal app
'employee', # Internal app
'school', # Internal app
'training', # Internal app
'services', # Internal app
'incident', # Internal app
'report', # Internal app
'notice', # Internal app
'county_notification', # Internal app
'utilities.fax', # Internal app
'log', # Internal app
'helptext', # Internal app
'search', # Internal app
'compensation', # Internal app
'data_export', # Internal app
'record_review', # Internal app
)
/var/log/apache2/error.log:
[Tue Apr 25 14:07:22.917665 2017] [wsgi:error] [pid 21810] Time to Populate: 0:00:00.826958
[Tue Apr 25 14:07:34.715745 2017] [wsgi:error] [pid 21817] Time to Populate: 0:00:00.822580
I was using PyCharm IDE and it was saving the files in real time, each save would prompt a recompile and this log would show up. I closed it and reran the tests and everything is fine. It only logs this function when I reload Apache2.

Setup Djangoproject on windows 2012 with Helicon Zoo

We were forced by the company to move our django app from Linux to Windows. I googled and there I found Helicon Zoo is meant to be a good idea to help me setting this up.
I have installed the zoo part as it was described and tried to add my django application which did not work. To be sure I am not having problems with complex stuff in the application I have created a mysite demopage as it was described in the django tutorial so now I have got this folder structure:
C:\inetpub\wwwroot\ZooPythonProject
I have changed the webconfig so it looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<heliconZoo>
<clear />
<application name="python.project">
<environmentVariables>
<add name="VIRTUAL_ENV" value="%APPL_PHYSICAL_PATH%\venv" />
<add name="PATH" value="%APPL_PHYSICAL_PATH%\venv\Scripts;% PATH%" />
<add name="PYTHONPATH" value="%APPL_PHYSICAL_PATH% \venv\lib\site-packages;%APPL_PHYSICAL_PATH%\venv\lib;%APPL_PHYSICAL_PATH%;% APPL_PHYSICAL_PATH%\mysite" />
<!-- <add name="WSGI_APP" value="welcome.application" /> -->
<add name="CONSOLE_URL" value="console" />
<add name="DEPLOY_FILE" value="deploy.py" />
<add name="ERROR_LOG_DIR" value="log" />
<!-- generic wsgi app -->
<!-- django project --> <add name="DJANGO_SETTINGS_MODULE" value="mysite.settings" />
I know that the setting file is taken as if I change the name of the setting file I get a different error message saying that the file cannot be found.
I start IIS and check my logfile it is giving me this error message:
No handlers could be found for logger "django.request"
Traceback (most recent call last):
File "C:\Zoo\Workers\python\zoofcgi.py", line 1069, in <module>
run_django_app(options.django_settings_module, options.django_root)
File "C:\Zoo\Workers\python\zoofcgi.py", line 999, in run_django_app
FCGIServer(WSGIHandler(), app_root=django_root).run()
File "C:\Zoo\Workers\python\zoofcgi.py", line 776, in run
conn.run()
File "C:\Zoo\Workers\python\zoofcgi.py", line 569, in run
self.process_input()
File "C:\Zoo\Workers\python\zoofcgi.py", line 600, in process_input
self._do_stdin(rec)
File "C:\Zoo\Workers\python\zoofcgi.py", line 724, in _do_stdin
self._start_request(req)
File "C:\Zoo\Workers\python\zoofcgi.py", line 697, in _start_request
req.run()
File "C:\Zoo\Workers\python\zoofcgi.py", line 515, in run
protocolStatus, appStatus = self.server.handler(self)
File "C:\Zoo\Workers\python\zoofcgi.py", line 862, in handler
result = self.application(environ, start_response)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\core\handlers\wsgi.py", line 189, in __call__
response = self.get_response(request)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\core\handlers\base.py", line 218, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\core\handlers\base.py", line 261, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\views\debug.py", line 97, in technical_500_response
html = reporter.get_traceback_html()
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\views\debug.py", line 384, in get_traceback_html
return t.render(c)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\base.py", line 209, in render
return self._render(context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\base.py", line 201, in _render
return self.nodelist.render(context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\base.py", line 903, in render
bit = self.render_node(node, context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\debug.py", line 79, in render_node
return node.render(context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\debug.py", line 89, in render
output = self.filter_expression.resolve(context)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\base.py", line 674, in resolve
new_obj = func(obj, *arg_vals)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\template\defaultfilters.py", line 774, in date
return format(value, arg)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\dateformat.py", line 345, in format
return df.format(format_string)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\dateformat.py", line 37, in format
pieces.append(force_text(getattr(self, piece)()))
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\dateformat.py", line 270, in r
return self.format('D, j M Y H:i:s O')
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\dateformat.py", line 37, in format
pieces.append(force_text(getattr(self, piece)()))
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\encoding.py", line 92, in force_text
s = six.text_type(s)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\functional.py", line 141, in __text_cast
return func(*self.__args, **self.__kw)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\__init__.py", line 84, in ugettext
return _trans.ugettext(message)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 323, in ugettext
return do_translate(message, 'ugettext')
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 300, in do_translate
_default = _default or translation(settings.LANGUAGE_CODE)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 206, in translation
_translations[language] = DjangoTranslation(language)
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 116, in __init__
self._add_installed_apps_translations()
File "C:\inetpub\wwwroot\ZooPythonProject\venv\lib\site-packages\django\utils\translation\trans_real.py", line 164, in _add_installed_apps_translations
"The translation infrastructure cannot be initialized before the "
django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.
These are my settings:
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u%196#-06u3np&!y91km4hp#ufn+80%op1$o5hrqp#c!$y-n-h'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = r'C:\inetpub\wwwroot\ZooPythonProject\mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'default': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': 'logs/mylog.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
'request_handler': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': 'logs/django_request.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'DEBUG',
'propagate': True
},
'django.request': {
'handlers': ['request_handler'],
'level': 'DEBUG',
'propagate': False
},
}
}
Does anybody have an idea how to setup this simple django page?
It works if I run it without IIS and Zoo and just do a manage.py runserver, but this is not an option for our production server.
Thanks for your help!
Eve
The problem may (or may not) come from "zoofcgi.py" script. Sorry for inconvenience anyway.
Could you please try a preview release of Zoo v.4 instead: https://github.com/helicontech/zoo/releases It uses different workers for Python application, so your issue may be resolved. Sorry, no documentation yet, but if you already familiar with MS WebPI, then it should be easy to use Zoo for you. After installing it, please, open Applications -> Templates and install "Python sample project". Open it in the browser and there you should find instructions how to put your existing Django project on it.
Sorry, it is still an early beta and applications outside 'Templates' section have not even been tested yet. As I work alone on this project I can't promise fast results, but at least in is open source now and underlying module code that runs applications has not changed significantly, so it is safe to say that if it worked once, then it should work further at least not worse than the previous version.

No module named views django

I'm starting a new django project on windows for the first time. I have worked on ubuntu and debian before with no problems. But on windows I found it a large task just to get it installed. I finally found a installing tutorial which worked perfectly until I started making a way for static media to be shown. I simply couldn't find a way to make it work, not with the standard django static media handler of apache. So I thought I would make the rest of the page first, or atleast get that to work. But when I made a view.py for my urls it kept saying "No module named views.py" in the browser. I looked through the internet and found a lot of solutions and tried them. I put a __init__ file in the directory where the views is. I then tried to debug the views.py by running it in a python shell and came up with this:
Traceback (most recent call last):
File "C:\wamp\www\mysite\veiws.py", line 5, in <module>
from django.shortcuts import render_to_response
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py", line 10, in <module>
from django.db.models.manager import Manager
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python27\lib\site-packages\django\utils\functional.py", line 184, in inner
self._setup()
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is
undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.`
I finally got the enviromental variable to be mysite.settings but even then it didn't work, because it couldn't find or didn't understand it, and when I tried some other things it came back...
my directory looks like this
C:\wamp\www\
-mysite
-static
-top4.png
-__init__.py
-__init__.pyc
-django.wsgi
-settings.py
-settings.pyc
-urls.py
-urls.pyc
-views.py
-wsgi.py
-wsgi.pyc
-templates
-base.html
-start_page
-manage.py
-testmysql.php
-index.php
views.py:
from django.conf import settings
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
def home(request):
return render_to_response('Start_page.html',RequestContext(request))
urls.py
from django.conf.urls import *
from veiws import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^home/$', home),
)
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT})
settings.py
# Django settings for mysite project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'Ocelot', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = 'C:/wamp/www/mysite/static'
STATIC_DOC_ROOT = "C:/wamp/www/mysite/static"
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
#os.path.join(PROJECT_DIR,'static'),
"C:/wamp/www/mysite/static"
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '&16j6qmva-7n00_#i6s17$d^_twu80pzv4l2wbt(^67$4s-c70'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'mysite.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"C:/wamp/www/templates"
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
So I can't get a simple page to work, and I have no idea how to get my static files to just be loaded with apache. All help is deeply appreciated.
EDITTED:
I have tried
set DJANGO_SETTINGS_MODULE = 'mysite.settings'
set DJANGO_SETTINGS_MODULE = 'settings'
wsgi.py
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
sys.path.append('C:/wamp/www/mysite')
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
manage.py
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
i have now tried setting the enviromental user variable but it seemed to delete itself
then i ran python.exe manage.py runserver 8000. witch gave me this error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
443, in execute_from_command_line
utility.execute()
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
69, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "c:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
__import__(name)
File "c:\Python27\lib\site-packages\django\core\management\commands\runserver.
py", line 8, in <module>
from django.core.servers.basehttp import AdminMediaHandler, run, WSGIServerE
xception, get_internal_wsgi_application
File "c:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 26,
in <module>
from django.views import static
File "c:\Python27\lib\site-packages\django\views\static.py", line 95, in <modu
le>
template_translatable = ugettext_noop(u"Index of %(directory)s")
File "c:\Python27\lib\site-packages\django\utils\translation\__init__.py", lin
e 75, in gettext_noop
return _trans.gettext_noop(message)
File "c:\Python27\lib\site-packages\django\utils\translation\__init__.py", lin
e 48, in __getattr__
if settings.USE_I18N:
File "c:\Python27\lib\site-packages\django\utils\functional.py", line 184, in
inner
self._setup()
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 42, in _set
up
self._wrapped = Settings(settings_module)
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 95, in __in
it__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s"
% (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'mysite.settings' (Is it on sys.path?): N
o module named settings
1) Move settings.py to C:\wamp\www\.
2) export DJANGO_SETTINGS_MODULE = 'settings'
If you're on Windows, you can type
set DJANGO_SETTINGS_MODULE = 'settings'
but it will only work until you close the window.
To make it permanent,
a) Start->Settings->Control Panel->System or press Win-Pause
b) Advanced system settings->Environment Variables->New user variable:
c) (name) DJANGO_SETTINGS_MODULE,
(value) settings
then open new terminal window - existing windows are not be affected.
3) Don't debug views.py by running it. It normally doesn't work. Debug through
python manage.py runserver 8000
when you're inside C:\wamp\www\.