在django中,如何调用子命令“syncdb”?从初始化脚本?

发布于 2024-09-14 22:07:40 字数 463 浏览 5 评论 0原文

我是 python 和 django 的新手,在阅读 Django Book 时,我了解了命令“python manage.pysyncdb”为我生成了数据库表。在开发环境中,我在内存数据库中使用sqlite,因此每次重新启动服务器时它都会自动删除。那么我该如何编写这个“syncdb”命令的脚本?(应该在“settings.py”文件中完成吗?)

澄清

OP正在使用内存数据库,需要在以下位置初始化:使用针对该数据库定义的 Django 模型的任何流程的开始。确保数据库初始化(每个进程启动一次)的最佳方法是什么?这将用于通过 manage.py runserver 或通过 Web 服务器进程(例如使用 WSGI 或 mod_python)运行测试或运行服务器。

I'm new to python and django, and when following the Django Book I learned about the command 'python manage.py syncdb' which generated database tables for me. In development environment I use sqlite in memory database, so it is automatically erased everytime I restart the server. So how do I script this 'syncdb' command?(Should that be done inside the 'settings.py' file?)

CLARIFICATION

The OP is using an in-memory database, which needs to be initialized at the start of any process working with Django models defined against that database. What is the best way to ensure that the database is initialized (once per process start). This would be for running tests, or running a server, either via manage.py runserver or via a webserver process (such as with WSGI or mod_python).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

明明#如月 2024-09-21 22:07:40

所有 Django 管理命令 都可以以编程方式访问

from django.core.management import call_command
call_command('syncdb', interactive=True)

理想情况下,您可以在 runserver 上使用预初始化信号来激活此信号,但这样的信号不存在。所以,实际上,如果我是你,我处理这个问题的方法是创建一个自定义管理命令,例如 runserver_newdb,并在其中执行:

from django.core.management import call_command
call_command('syncdb', interactive=True)
call_command('runserver')

请参阅 文档 了解有关编写自定义管理命令的更多信息。

All Django management commands can be accessed programmatically:

from django.core.management import call_command
call_command('syncdb', interactive=True)

Ideally you'd use a pre-init signal on runserver to activate this, but such a signal doesn't exist. So, actually, the way I'd handle this if I were you would be to create a custom management command, like runserver_newdb, and execute this inside it:

from django.core.management import call_command
call_command('syncdb', interactive=True)
call_command('runserver')

See the documentation for more information on writing custom management commands.

兰花执着 2024-09-21 22:07:40

根据“Where to put Djangostartup code?”的建议,您可以使用用于启动代码的中间件。 Django 文档位于此处

例如(未经测试):

startup.py:

from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
from django.core.management import call_command

class StartupMiddleware(object):
    def __init__(self):
        # The following db settings name is django 1.2.  django < 1.2 will use settings.DATABASE_NAME
        if settings.DATABASES['default']['NAME'] == ':memory:':
            call_command('syncdb', interactive=False)

        raise MiddlewareNotUsed('Startup complete')

并在您的settings.py中:

 MIDDLEWARE_CLASSES = (
     'your_project.middleware.startup.StartupMiddleware',

     # Existing middleware classes here
 )

As suggested by "Where to put Django startup code?", you can use middleware for your startup code. The Django docs are here.

For example (untested):

startup.py:

from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
from django.core.management import call_command

class StartupMiddleware(object):
    def __init__(self):
        # The following db settings name is django 1.2.  django < 1.2 will use settings.DATABASE_NAME
        if settings.DATABASES['default']['NAME'] == ':memory:':
            call_command('syncdb', interactive=False)

        raise MiddlewareNotUsed('Startup complete')

and in your settings.py:

 MIDDLEWARE_CLASSES = (
     'your_project.middleware.startup.StartupMiddleware',

     # Existing middleware classes here
 )
温柔戏命师 2024-09-21 22:07:40

更新

我在项目的根目录中添加了一个名为 run.sh 的脚本。这对我的 SQLite 数据库有用:

#!/usr/bin/python
from django.core.management import call_command
call_command('syncdb')
call_command('runserver')

原始答案

我不确定我是否理解“编写syncdb命令脚本”的意思。您通常从命令行执行python manage.pysyncdb。这通常在添加新模型后完成。如果您愿意,可以使用简单的 shell 脚本轻松完成此操作。我不认为有任何理由从 settings.py 中放置(或调用)syncdb

您能为您的问题添加更多详细信息吗?添加上下文并解释您到底想要完成什么?

Update

I added a script called run.sh in the project's root directory. This worked for me with an SQLite database:

#!/usr/bin/python
from django.core.management import call_command
call_command('syncdb')
call_command('runserver')

Original Answer

I am not sure I understand what you mean by "scripting the syncdb command". You usually execute python manage.py syncdb from the command line. This is usually done after adding new models. In case you want to you easily accomplish this using a simple shell script. I don't see any reason to place (or invoke) syncdb from within settings.py.

Could you add more details to your question? Add context and explain what exactly are you trying to get done?

黑色毁心梦 2024-09-21 22:07:40

@Daniel Naab 的答案以及官方网站中的文档并不用于作为入口点执行管理命令。

当您想使用管理命令作为托管云环境(例如 AWS Lambda 或 Google Cloud Functions)中的入口点时,您可以查看 manage.py 并尝试类似的操作。

import os
from django.core.management import execute_from_command_line

def publishing_fn(data, context):
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YOURAPP.settings')
    # The first argument is "manage.py" when it's run from CLI.
    # It can be an empty string in this case
    execute_from_command_line(['', 'COMMAND', 'ARGS...'])

@Daniel Naab's answer, as well as the doc in the official site, is not for executing management commands as an entrypoint.

When you want to use a management command as the entrypoint in managed cloud environment like AWS Lambda or Google Cloud Functions, you can take a look at manage.py and try something similar.

import os
from django.core.management import execute_from_command_line

def publishing_fn(data, context):
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YOURAPP.settings')
    # The first argument is "manage.py" when it's run from CLI.
    # It can be an empty string in this case
    execute_from_command_line(['', 'COMMAND', 'ARGS...'])
日暮斜阳 2024-09-21 22:07:40

您可以创建一个新的脚本来调用,而不是调用manage.py的manage.py:

from subprocess import call
call(["python", "manage.py", "syncdb"])
call(["python", "manage.py", "runserver"])

如果您不需要添加管理员,您可以像这样更改第二行:

call(["python", "manage.py", "syncdb", "--noinput"])

我假设您正在尝试执行以下操作 :要做的就是创建数据库,然后每次使用一个命令启动服务器。

You could create a new script that you call instead of manage.py that calls manage.py:

from subprocess import call
call(["python", "manage.py", "syncdb"])
call(["python", "manage.py", "runserver"])

If you don't need to add an admin you could change the second line like this:

call(["python", "manage.py", "syncdb", "--noinput"])

I'm assuming that what you're trying to do is create your db and then start your server with one command every time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文