How to call a function before a django app start? - django

In my django project i have to check if a database/table exist before starting application, i don't know how is better insert the code for check.
I try to add in views.py into login function a try except block but i was try to find an elegant and more effective solution.
Thanks in advance

To check before the app starts then you can use the AppConfig.ready() function. This gets called before the application starts, but after your project has started. If you want to check before the project starts then you will have to hook into the method you use to start your project, eg within wsgi.py or even manage.py
AppConfig.ready() docs Note that the docs specifically say
avoid interacting with the database in your ready() implementation.
But your use case may justify doing this.
The ready function is called when you run the commands from manage.py eg
manage.py shell / manage.py migrate / etc
It won't get called when your site is visited of course. If you want to run a DB check in response to a visitor action then that code should go into your view
You put the ready() function in your apps.py:
from django.apps import AppConfig
from django.db import connection
class MyAppConfig(AppConfig):
name = 'MyApp'
def ready(self):
print("i am the ready function and the database test code goes here")
# put your test code here, eg you could read all the tables from sqlite
with connection.cursor() as cursor:
cursor.execute("SELECT name FROM sqlite_master;")
rows=cursor.fetchall()
print (rows)

You can write your custom django admin commands and run it by using python manage.py your_command right before calling python manage.py runserver. There are detailed examples at the official documentation.
One of the advantages of using commands is that testing commands are fairly easy. Django has a package for calling commands django.core.management.call_command which enables funtionally test your command.

Related

Django run function periodically in background

I have a function that fetches data and needs to be run periodically.
All I care about is running it every 30 seconds.
I searched and found the following options -
celery
django-apscheduler
Apscheduler
I have tried Apscheduler using BackgroundScheduler and it has this problem that it'll run a new scheduler for each process.
I am completely new to scheduling functions and have no idea which one I should use or if there is a better way.
I experienced a similar issue and solved it by creating a custom management command and scheduling it on the web server.
Within the root of the app, create management/commands directory:
some_app/
__init__.py
models.py
management/
commands/
dosomething.py
tests.py
views.py
// dosomething.py
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Description of the action here'
def handle(self):
print('Doing something')
return
To confirm if it's working, run python manage.py dosomething
The scheduling itself depends on which web server you are using. In my case it was Heroku and I used their Scheduler add-on.

How I can run a telegram bot with the Django project?

Now, to run the bot through Django, I first use the python manage.py runserver command and then follow the link to launch a view with my bot. Can you tell me if there is an easier way to start my bot automatically when starting a Django project?
Actually, you can use a management command to run your bot with something like
python manage.py runbot
All Django context, including DB and settings, will be available
Reference to management command page:
https://simpleisbetterthancomplex.com/tutorial/2018/08/27/how-to-create-custom-django-management-commands.html
Maybe is a little late but you can do the following:
create the bot.py file in the same folder where manage.py is.
inside the bot.py make sure you import the following:
import django
import os
os.environ['DJANGO_SETTINGS_MODULE'] = '{Folder where your settings are}.settings'
django.setup()
and in order to run you just type python bot.py

Shell script to update DB via flask

I got started with flask and I tried out the Flaskr example. On the execution of a certain python script, I would like to update one row of my database.
I am a newbie here and would like to understand: am I going to update the DB from inside that python script or I am going to wait for a signal from the flask WSGI script:
I have referred to this thread but am not sure how I am going to interact with the external script. Any help or hints are appreciated.
WSGI handles HTTP requests/responses. A script won't be issuing those. Instead, import your Flask app in the script and make an application context:
from my_project import my_app
ctx = my_app.app_context()
ctx.push()
# ... my code
db.session.commit()
ctx.pop()
Relevant docs: http://flask.pocoo.org/docs/appcontext/, http://flask.pocoo.org/docs/shell/
Or consider using Flask-Script to add command line functions to your application, if the function doesn't need to be a separate script.

Validating django models on runserver command

I want to create some custom validation on models when I do python manage.py runserver command.
Can I do this somehow?
Well, the problem in fact is that you want to run some custom code when your server starts up.
Two possibilities:
Use wsgi.py as suggested by this post. This seems to be the more elegant solution.
Put all your code inside some __init__.py file. Be warn that this code will be executed any time you import that package (for example, when you run a django command)

How to execute a python program by a button click on html page generated by django

I created a Django project to launch a htmlpage which has a button with name run test. I would like to run a python script file hello.py(located outside the django project) when the button is clicked. I am quite new to this scripting.
Can anyone help me with this question as soon as possible? Your help would be appreciated.
My django project consists of following files:
TestProject(project folder)
myapp(folder)
int.py
admin.py
models.py
tests.py
urls.py
views.py
Templates(folder)
index.html
Testproject(folder)
int.py
urls.py
settings.py
views.py
wsgi.py
admin.py
manage.py
The python script file-helllo.py is located C:/hello.py
There are two basic approaches you could take to do this:
(1) Run the script as a subprocess (i.e. execute a separate program outside of your django application) - this is documented in the Python docs on subprocesses. Below is a brief example, you will need to go through the docs to understand exactly how you want to call your script (i.e. to handle return codes, output to stdout and stderr, etc)
import subprocess
subprocess.call(["python", "C:/hello.py"])
(2) If there is a specific function in this script that you could call, then you could add the directory containing the python script to sys.path, and then import the script and call the relevant function. This is detailed in this stack overflow question, and would be arguably the cleaner approach (As a sidenote, would advise moving hello.py to a more suitable location, the root of your C: drive probably isn't the right place to store scripts).
import sys
sys.path.append("C:/")
from hello import function_to_call
function_to_call()
If you are struggling to put together the web page that allows you to display the button and react to the button press by calling the script, it would be advisable to work through the excellent Django tutorial writing your first Django application.