Django custom manage.py commands calling functions in app - django

I have a command which is used to download data from an API, and then store it into a local database, it's currently part of my app but I want to add the ability to run it from a manage.py command.
Currently i'm just trying to call it as i would inside my application with the correct arguments but i get an error related to models
Error:
File "C:\xxx\Development\working folder\appdata\globaltags\boughtintags.py", line 2, in <module>
import appdata.boughtin.models as models
AttributeError: 'module' object has no attribute 'models'
Current Code i'm using:
class Command(BaseCommand):
args = '<queryset_uuid queryset_item_uuid>'
help = 'Downloads arbitrary items using a download script'
def handle(self, *args, **options):
for queryset_uuid, queryset_item_uuid in args:
if download_queryset(queryset_uuid=queryset_uuid, queryset_item_uuid=queryset_item_uuid):
self.stdout.write('Successfully downloaded "%s"\n' % queryset_item_uuid)
else:
raise CommandError('Unable to download "%s"\n' % queryset_item_uuid)

Try changing import appdata.boughtin.models as models in boughtintags.py to
from appdata.boughtin import models

Related

Adding command arguments to the Django runserver command and handle() method setup for local secure HTTP server

I'll keep this as vague as possible - as it's quite a broad question.
I'm building a payment system within my Django project - and it would be amazing to be able to run my project over a secure server connections. And now were moving into a more forced secure internet with more emphasis on site security with in browser alerts etc I think this is something that needs to be added to the Django core management commands.
I've started to build this functionality inside an application:
management/commands/runsecureserver.py:
import os
import ssl
import sys
from django.core.servers.basehttp import WSGIServer
class SecureHTTPServer(WSGIServer):
def __init__(self, address, handler_cls, certificate, key):
super(SecureHTTPServer, self).__init__(address, handler_cls)
self.socket = ssl.wrap_socket(self.socket, certfile=certificate,
keyfile=key, server_side=True,
ssl_version=ssl.PROTOCOL_TLSv1_2,
cert_reqs=ssl.CERT_NONE)
I'm now wondering - I have the following class that extends from the BaseCommand class from Django's runserver.py where I add my arguments for specifying cert files etc, an inner_run() function which will mimic a lot of the Django runserver inner_run() with added certificate checks, port configurations etc.
class Command(BaseCommand):
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(**some argument here***)
However, when running:
$ python manage.py runsecureserver
I receive the following error:
NotImplementedError: subclasses of BaseCommand must provide a handle() method
So, it's telling me I need a handle() method...
Q. What is a handle() method in this context, and what should it do?
Q. Is it enough to simply use the existing handle() method from Django's runserver.py?
https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/
Your file must be within /DjangoProject/YouApp/management/commands/
# custom_command.py
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--delta')
parser.add_argument('--alpha')
parser.add_argument('--universe')
def handle(self, *args, **options):
# argument in a dict here :
print(options)
# Do your stuff :)
pass
python manage.py custom_command --universe=42

AttributeError: type object 'DeleteAccount' has no attribute 'DAccount'

I'm using Python 2.7, webapp2 and GAE for developing a web app.
I'm facing a problem which i don't understand, since I know what it means but everything I did seems correct.
I get the error
AttributeError: type object 'DeleteAccount' has no attribute 'DAccount'
when i try to access the URL myappdomain/DeleteAccount/
I imported in the main file the python file DeleteAccount.py
import DeleteAccount
I linked the URL with the relative class DAccount of DeleteAccount
webapp2.Route(r'/DeleteAccount/',DeleteAccount.DAccount)
That's my DeleteAccount.py file
import logging
import webapp2
from webapp2_extras import sessions
import datastore
import FBLogin
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
return self.session_store.get_session()
class DAccount(BaseHandler):
def get(self):
w = self.response.write
logging.info("deleting account")
w('I've deleted the account')
What's wrong? I did what I've done with every other module and everything has worked well with them

How to modify dumpdata generated django json fixture prior to loading into database

I am a relative django newbie. I have a json fixture for the django.contrib.auth.user objects from an existing database that I want to load into my test app. The specific field I want to modify are all the Datetime Fields that do not have UTC offsets built into them. I want to add these UTC offsets using a python script.
I am using the django deserializer but am having no luck and get an error during the deserialization.
File "add_utc_offset_to_fixture.py", line 24, in <module>
for obj in serializers.deserialize("json", json_fixture):
File "/Users/hari/.virtualenvs/bsc2/lib/python2.7/site-packages/django/core/serializers/json.py", line 47, in Deserializer
raise DeserializationError(e)
django.core.serializers.base.DeserializationError: No module named Image
How do I get around this deserialization error, or alternatively how do I modify this fixtures before loading into the database.
I looked into my fixtures and also into the json.py deserializer and do not understand why it needs a module called Image.
My code
# This program reads in a json fixture with naive Datetime field and converts it into a UTC aware Datetime field
# For Documentation on this see https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#time-zones-migration-guide
import sys,os
# Sets the django settings module
dir_two_steps_up_from_me = os.path.join(os.path.split(os.path.dirname(os.path.abspath(__file__)))[-2])
print "Adding %s to sys.path" % dir_two_steps_up_from_me
sys.path.append(dir_two_steps_up_from_me)
from bsc2 import settings
from django.core.management import setup_environ
# Deprecated but still using
setup_environ(settings)
from django.core import serializers
from django.contrib.auth.models import User
json_fixture = None
try:
json_fixture = open(sys.argv[1],"rb")
except IndexError,IOError:
print "Please give json fixture"
exit()
for obj in serializers.deserialize("json", json_fixture):
# Getting deserialization error when this executes
print obj.first_name
# TODO Code to change naive time in last_login to UTC time

Django custom management commands: AttributeError: 'module' object has no attribute 'Command'

I am trying to make a custom management command as show in the docs here: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/
When I try to run the command from my project directory I am experiencing the following error:
AttributeError: 'module' object has no attribute 'Command'
Here is the file:
#event_expiration.py
from django.core.management.base import BaseCommand, CommandError
from app.models import Event
import datetime
class Command(BaseCommand):
help = 'deletes expired events'
def handle(self, *args, **options):
today = datetime.datetime.now()
events = Event.objects.filter(date=datetime.date(2011,11,11))
for e in events:
e.delete()
self.stdout.write('Expired events successfully deleted.')
The command I am running is :
$ python manage.py event_expiration
I've made sure I am adding the event_expiration.py file within management and commands folders and that those folders have init files. those are in one of my app folders.
Am I overlooking something here? Any help is appreciated, thanks!
EDIT:
Fellow SO user Yuji helped me attempt to debug this a bit but we are still stumped. heres what we did:
First, the full traceback and command:
(venv)matt#inspirion14z:~/Dropbox/PROD/ersvp.it$ python manage.py event_expiration
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 70, in load_command_class
return module.Command()
AttributeError: 'module' object has no attribute 'Command'
To see what was going on at django/core/management/init.py", line 70 I placed import pdb; pdb.set_trace() within the file.
While in debug mode we tried:
module.__file__
to check if the module was where expected, and it indeed was, with an output of:
'/home/matt/Dropbox/PROD/ersvp.it/app/management/commands/event_expiration.pyc'
Next, we tried manually importing Command in the shell:
>>> from app.management.commands.event_expiration import Command
Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name Command
Still scratching my head!
I ran into the same issue and the problem was that my command class wasn't called exactly Command, as the docs says. Example:
class Command(NoArgsCommand):
# Do something here
What is your file structure like? It should be like so:
app/
__init__.py
management/
__init__.py
commands/
__init__.py
event_expiration.py
If the structure is as above, try the following:
python manage.py shell
>>> from app.management.commands import event_expiration
>>> dir(event_expiration)
['Account', 'BaseCommand', 'Callback', 'Command', 'CommandError', 'Comment', 'Status', 'User', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'clean_phone_number', 'csv', 'models', 'os', 're']
I've listed the pure output of running dir on a management command of my own. Give that a try, and report back what is available to the module. You might find yourself getting an error at this point, which may help diagnose. I'm suspecting a problem with importing django itself. I'm guessing the python manage.py shell will fail, which will mean it's not a problem with your command, but a problem with the project.
Edit 2:
The fact that check_expiration was visible in your dir output supports my theory that the folder structure is amiss in someway. Unless there's specifically a function named that within your module.
Please do the following and show the output:
cd /path/to/app/
find .
Also, show the entire contents of your event_expiration.py file, and the contents of your management/commands/__init__.py file. Be wary of spaces mixed with tabs as whitespace also.
Printing a queryset directly will also cause this error. For instance, I was trying to do something like this (just testing, not a real use case):
def handle(self, *args, **options):
ppl = People.objects.all()
print(ppl)
Resolution:
def handle(self, *args, **options):
ppl = People.objects.all()
print(str(ppl)) # Convert queryset to string
Conclusion: What works in shell doesn't necessarily work in a management command. Would be nice if someone can point out why.
I got this error by importing the regular click module instead of djclick
my_module/management/commands/run_thing.py
# import click # causes the error because not setup like djclick is
import djclick as click
#click.command()
#click.option("--thing", required=True, prompt=True)
def command(thing):
print(f"hi: {thing}"
Example run:
./manage.py run_thing --thing 123
...
hi: 123

Cron job for Django File

I want to setup a Cron job to run a django file.
What I want to know is django-cron a good option for this? i.e. or are there any other apps that can be used?
If no, how to run a django file through command line ?
admin#ADMIN-PC ~/workspace/bolt (master)
$ python ./log/cron.py
Traceback (most recent call last):
File "./log/cron.py", line 3, in <module>
from account.models import UserProfile
ImportError: No module named account.models
I have set the following variable
admin#ADMIN-PC ~/workspace/bolt (master)
$ export DJANGO_SETTINGS_MODULE=settings
I keep getting these errors as the files that are being referenced have direct imports
from foo.models import *
Any help will be highly appreciated.
Custom Command
from django.core.management.base import BaseCommand, CommandError
import pdb
import datetime
from too.models import UserProfile
from foo.api import end_all_foo_conversations
class Command(BaseCommand):
# in minutes
def handle(self,*args,**options):
print datetime
The error I am getting while trying to run the command is as follows:-
'queryset': self.rel.to._default_manager.using(db).complex_fi
imit_choices_to),
AttributeError: 'str' object has no attribute '_default_manager'
I think you should write a custom management command and run it through manage.py.