3

Django笔记四十之运行Django环境的python脚本 - XHunter

 1 year ago
source link: https://www.cnblogs.com/hunterxiong/p/17396431.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文首发于公众号:Hunter后端

原文链接:Django笔记四十之运行Django环境的python脚本

这一篇笔记介绍如何在 Django 中运行脚本。

假设说我们要实现一个功能,需要获取 blog.models.Blog 这张表里的总数且使用 print() 输出。

如果代码逻辑很短,且是一次性执行的操作,我们可以在系统的根目录下使用 python3 manage.py shell 在 shell 中操作实现。

from blog.models import Blog
print(Blog.objects.all().count())

但是如果这个需求是一个很长的逻辑,且需要可以重复执行,那么应该如何操作呢?

首先,我们需要可以用到 Django 里的 Blog model,然后使用 model 的方式来进行查询。

我们可以将其写入一个文件,每次都使用 shell 来调用。

写入文件,在 shell 调用

比如,我们可以在 blog 创建一个 scripts 文件夹,然后创建一个 blog_script.py 文件:

# blog/scripts/blog_script.py

from blog.models import Blog

def get_blog_count():
    print(Blog.objects.all().count())

然后每次调用的时候就进入 python3 manage.py shell 操作:

from blog.scripts.blog_script import get_blog_count

get_blog_count()

直接运行脚本

如果我们想创建一个文件,然后直接运行该脚本,那么就需要在脚本中引入当前 Django 系统环境的一些参数和变量,可以直接在系统根目录下创建一个 blog_script.py 文件:

# blog_script.py

import django, os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hunter.settings")
django.setup()

from blog.models import Blog

if __name__ == "__main__":
    print(Blog.objects.count())

然后我们在系统根目录下直接执行该脚本:

python3 blog_script.py

这个文件目前只有放在系统的根目录下才可以运行,但是如果太多的脚本都放到系统根目录下也不太好,所以我们如果有这种脚本一般都可以放到对应的 application 的 scripts 文件夹下。

如果我们想要直接在 blog/scripts/ 下直接运行该脚本的话,则需要在我们的脚本中添加 Django 系统的路径,假设我们的 Django 系统名为 hunter,在服务器的路径为:/Users/xxxx/hunter/,我们可以如下操作:

# blog/scripts/

import django, os, sys

django_path = "/Users/xxxx/hunter/"
sys.path.extend([django_path])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hunter.settings")

django.setup()

from blog.models import Blog

if __name__ == "__main__":
    print(Blog.objects.count())

如果想获取更多后端相关文章,可扫码关注阅读:

image

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK