【问题标题】:How to backup PostgreSQL database using Django?如何使用 Django 备份 PostgreSQL 数据库?
【发布时间】:2019-07-17 06:56:32
【问题描述】:

我正在尝试导出 Postgresql 数据库,但它返回 backup() 不带任何参数(给定 1)。一世 尝试了各种方法,但无法导出数据库。

from pathlib import Path, PureWindowsPath
from subprocess import PIPE,Popen
​
​
def backup():
    version = 11
    # postgresDir = "D:/Program Files (x86)/PostgreSQL/9.1/bin"
    postgresDir = str("D:/Program Files (x86)/PostgreSQL/9.1/bin/").split('\\')[-1:][0]
​
    directory = postgresDir
    filename = 'myBackUp2'  # output filename here
    saveDir = Path("D:/{}.tar".format(filename))  # output directory here
    file = PureWindowsPath(saveDir)
​
    host = 'localhost'
    user = 'postgres'
    port = '5432'
    dbname = 'BPS_Server'  # database name here
    proc = Popen(['pg_dump', '-h', host, '-U', user, '-W', '-p', port,
                   '-F', 't', '-f', str(file), '-d', dbname],
                    cwd=directory, shell=True, stdin=PIPE)
    proc.wait()
​
backup()

【问题讨论】:

  • 您使用 Django 的原因有哪些?对我来说,这看起来像是一个普通的 python 脚本,你可以尝试将脚本移出你的 Django 项目并执行它吗?也可能重命名备份功能,只是一个疯狂的猜测
  • 我试图从我的 django 项目中运行该文件,但它不起作用。它返回 FileNotFoundError: [WinError 2] 系统找不到指定的文件

标签: django


【解决方案1】:

从 postgresql 备份有两种方法:

1) 使用 bash 脚本并每天或每月运行它以获取备份: 您可以获取更多信息here

2) 在 django 中使用fixture

def backup():
    filename = 'myBackUp2'  # output filename here
    saveDir = open("D:/{}.json".format(filename), 'w')

    # change application_name with your django app which you want to get backup from it
    call_command('dumpdata', 'application_name', stdout=saveDir, indent=3)
    saveDir.close()

call_command() 用于执行 django 命令,dumpdata 用于从表中获取夹具。 more information

【讨论】:

  • 我创建了 db.json 文件。抱歉,我很困惑我应该在 dumpdata 和 application_name 中放什么。我应该把 db.json 文件的路径放在 open("D:/{}.json".format(filename), 'w') 中吗?
  • dumpdata 生成一个包含您的数据的 json 文件。你知道,在 django 中,我们可以在 INSTALLED_APPS 中定义一些应用程序,因此对于获取转储数据,您应该定义一个您在 INSTALLED_APPS 中定义的应用程序,然后 django 生成它的转储数据
  • 看到这个sample
  • 我想备份整个数据库。我做了python manage.py dumpdata。我可以看到在 python shell 中创建的转储数据,但我不知道它是在哪里创建的。
  • 我也尝试过使用子进程。它创建 gzip 文件但为空文件。
猜你喜欢
  • 2019-05-29
  • 2010-10-25
  • 2014-01-29
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
  • 1970-01-01
相关资源
最近更新 更多