Is it possible to manage model data without running the server? - python

Suppose I have a python module written to do some clean job and daily maintenance. It has no view or template but simply a command line tool. Is it possible to interact with the models and db regardless of whether the server is on?

Yes you can.
Look into the management commands shell and dbshell
You would just do
python manage.py shell #You can call any method, modify Model objects, ...
and
python manage.py dbshell #Gives direct access to the database via command line
And this does not need the server to be running.

Related

How to Create Django Application Backup Automatically

I have developed a web application in Python and Django and need to back up the data daily. Currently, Postgres is used as DBMS.
To perform the backup I discovered the django-dbbackup module, but to use it, I need to run the command python manage.py dbbackup.
How do I automatically back up every day at a certain time?
If you are on Linux set up a cron job by following this example: Running a cron job at 2:30 AM everyday
On Windows is similar setup a schedule task using their wizard.
The command you’ll want to use is
python manage.py dbbackup

Django: Run a script right after runserver

Context:
I have a table on the database that uses values from an external database. This external database updates its values periodically.
Problem:
In order to update my database everytime i start the server, I want to run a script right after the runserver.
Potential Solution:
I have seen that it is possible to run a script from a certain app, which is something I'm interested in. This is achievable by using the django-extensions:
https://django-extensions.readthedocs.io/en/latest/runscript.html
However, this script only runs with the following command:
python manage.py runscript your_script
Is there any other way to run a script from an app and execute it right after the runserver command? I am open to suggestions!
Thanks in advance
Update
Thanks to #Raydel Miranda for the remarks, I feel i left some information behind.
My goal is, once I start the server I'm planning to open a socket to maintain my database updated.
You can execute the code in the top-level urls.py. That module is imported and executed once.
urls.py
from django.confs.urls.defaults import *
from your_script import one_time_startup_function
urlpatterns = ...
one_time_startup_function()
I would recommend to use something like this, lets say you have the script like this:
# abc.py
from your_app.models import do_something
do_something()
Now you can run this script right after runserver(or any other way you are running the django application) like this:
python manage.py runserver & python manage.py shell < abc.py
FYI, it will only work if you have bash in your terminal (like in ie Linux, MacOs).
Update
After reading you problem carefully, I think running a script after runserver might not be the best solution. As you said:
This external database updates its values periodically.
So, I think you need some sort of perodic task to do this update. You can use cronjob or you can use Celery for this.
Running the script after runserver don't seem a very good idea, the main reason is that you will have a window since the server is running (and available for users) till you finish synchronizing your data. Also if you synchronize using a script after runserver you won't get updates from the external db after that.
The best solution for this is to configure multiple databases, you can use the external database with only read access. This way your views will provide really updated data.
On the other hand ...
If want use something like a script is better to write a Django custom command (this way you don't have to deal with initializing django settings and other issues) and execute it using cron or celery as #ruddra states in his/her answer.
Said this, you should see this: https://docs.djangoproject.com/en/2.1/topics/db/multi-db/
This may help.
you can edit yourapp/apps.py
class MyAppConfig(AppConfig):
name = 'myapp'
def ready(self):
# update my database here
pass

Database Api Python/django

I am working on a tutorial on Django
When I invoke the interactive shell to access the database API using the command python manage.py shell, I receive the following prompt
In [1]:from music.models import Album, Song
In [2]: Album.objects.all()
Then the next line gives me this
OperationalError: no such table: music_album
Like the error says, it means that your database has no tables that correspond to these models.
Typically that means that you forgot to migrate your database. By running:
python manage.py makemigrations
Django will construct files (in someapp/migrations/) these files describe the steps that have to be carried out such that tables are constructed with the correct columns, or later in the progress columns can be renamed, tables removed, new tables constructed. If you run the command, you will see new files popping up that describe these migrations.
But now you still did not migrate the database itself, you only constructed the files. It is for example possible that you want to add custom migrations yourself. In case the migration files are correct, you can run
python manage.py migrate
to change the database accordingly.
In order to run the migrations, the database has to be specified correctly in the settings.py file. But since you obtain an OperationalError that complains about the table not being found, I think this has already been handled (correctly).
See the Django topic on migrations [Django-doc] for more information.
Configure your database connection in your settings.py and, after creating Django models, you have to execute two commands:
python manage.py makemigrations
python manage.py migrate
Then tables will be created in the database and you will be able to use then in the shell

Access Django from outside Django shell in real Python

I run Django through a Python 3.4 virtualenv and I want to make some cronjob scripts that will access models and save.
I can do this through the Django shell python manage.py shell will initiate the Django shell. From there I can do from polls.models import Poll, Choice and make a new Poll and save it into the DB.
How can I do this through the regular Python shell?
Your best bet is probably to create a management command. You can run it from the command line by calling (python manage.py ) and from within the script you can access any django functions or models.
For further instructions on how see here https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

How to View My Postgres DB Schema from Command Line

So I have my Django app running and I just added South. I performed some migrations which worked fine locally, but I am seeing some database errors on my Heroku version. I'd like to view the current schema for my database both locally and on Heroku so I can compare and see exactly what is different. Is there an easy way to do this from the command line, or a better way to debug this?
From the command line you should be able to do heroku pg:psql to connect directly via PSQL to your database and from in there \dt will show you your tables and \d <tablename> will show you your table schema.
locally django provides a management command that will launch you into your db's shell.
python manage.py dbshell
django also provides a management command that will display the sql for any app you have configure in your project, regardless of the database manager (SQLite, MySQL, etc) that you're using:
python manage.py sqlall <app name>
Try it! It could be usefull!

Categories

Resources