Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
运行django应用程序触发的python脚本时出错_Django_Python 3.x_Path_Scripting_Frameworks - Fatal编程技术网

运行django应用程序触发的python脚本时出错

运行django应用程序触发的python脚本时出错,django,python-3.x,path,scripting,frameworks,Django,Python 3.x,Path,Scripting,Frameworks,我正在构建一个完全开源的testrunner来满足我的需求,但是我遇到了一些问题。测试运行程序在不同的路径中为一组脚本解析yaml文件,并执行脚本,并使用我将创建的库返回结果。现在我有一个简单的ping脚本,我正在运行和测试它,但是我遇到了很多错误。下面是错误,所有源代码也显示在错误下面 这方面的github回购协议就在这里。请随意使用它并测试我看到的问题。 问题: Enterprize:testrunner xwing$ python3 ping_google.py Traceback (m

我正在构建一个完全开源的testrunner来满足我的需求,但是我遇到了一些问题。测试运行程序在不同的路径中为一组脚本解析yaml文件,并执行脚本,并使用我将创建的库返回结果。现在我有一个简单的ping脚本,我正在运行和测试它,但是我遇到了很多错误。下面是错误,所有源代码也显示在错误下面

这方面的github回购协议就在这里。请随意使用它并测试我看到的问题。

问题:

Enterprize:testrunner xwing$ python3 ping_google.py
Traceback (most recent call last):
  File "ping_google.py", line 1, in <module>
    from testrunnerlib.test import HostInterface
  File "/Users/xwing/PycharmProjects/testrunner/testrunnerlib/test.py", line 11, in <module>
    from testrunner.models import Host, TestSuite
  File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 5, in <module>
    class Host(models.Model):
  File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
from testrunnerlib.test import HostInterface
from testrunnerlib.outcomes import Outcomes

from ping3 import ping


def pinger(host):
    result = Outcomes()
    try:
        ping_google = ping(host)
        print(ping_google)
        if ping_google:
            return result.passed()
        msg = 'ping had an issue, the following is all we know %s' % ping_google
        return result.failed(msg)
    except Exception as e:
        return result.aborted(exception=e)

if __name__ == '__main__':
    pinger(HostInterface().target)
import yaml
import subprocess

from testrunner.models import Host, TestSuite


class HostInterface(object):
    def __init__(self):
        self._target = 'not set'

    @property
    def target(self):
        return self._target

    @target.setter
    def target(self, value):
        print("setter of target called", value)
        self._target = value

    @target.deleter
    def target(self):
        print("deleter of target called")
        del self._target

    def host(self):
        out = Host.objects.get(id=self.target).name
        return out


class YamlInterface:
    def __init__(self, yamlfile):
        self.file = yamlfile

    def handle_yaml(self):
        data = TestSuite.objects.get(id=self.file)
        yamldata = yaml.safe_load(data.text)
        for i in yamldata['testsuite']:
            status = subprocess.call('python3 %s' % i, shell=True)
            print(status)


def run_tests(host, yaml):
    h_interface = HostInterface()
    h_interface.target = host
    h_interface.host()
    yaml = YamlInterface(yaml)
    yaml.handle_yaml()
from __future__ import unicode_literals
from django.db import models


class Host(models.Model):
    ip_address = models.CharField(max_length=16)
    port = models.IntegerField()
    name = models.CharField(max_length=256)


class TestSuite(models.Model):
    name = models.CharField(max_length=256)
    text = models.TextField()
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return "%s" % self.name
我正在尝试使用我构建的testrunner来解析yaml文件,以找到我正在为im使用的项目编写的脚本的路径

例如,如果想要在目标上使用一组特定的测试,我可以为每一组测试类型创建一个yaml文件

但是,我看到了一个问题,文件的相对路径和精确路径无法使用django库,因为它无法找到库的路径,除非它从django应用程序的顶层运行(即../ping_google.py vs./testcases/ping_google.py)

但除此之外,django应用程序表示,当独立库引用models.py和admin.py时,它不会运行。它们无法从同一目录导入模型。我需要帮助解决和理解这个问题

以下是详细信息(stacktrace):

Enterprize:testrunner xwing$ python3 ping_google.py
Traceback (most recent call last):
  File "ping_google.py", line 1, in <module>
    from testrunnerlib.test import HostInterface
  File "/Users/xwing/PycharmProjects/testrunner/testrunnerlib/test.py", line 11, in <module>
    from testrunner.models import Host, TestSuite
  File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 5, in <module>
    class Host(models.Model):
  File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
from testrunnerlib.test import HostInterface
from testrunnerlib.outcomes import Outcomes

from ping3 import ping


def pinger(host):
    result = Outcomes()
    try:
        ping_google = ping(host)
        print(ping_google)
        if ping_google:
            return result.passed()
        msg = 'ping had an issue, the following is all we know %s' % ping_google
        return result.failed(msg)
    except Exception as e:
        return result.aborted(exception=e)

if __name__ == '__main__':
    pinger(HostInterface().target)
import yaml
import subprocess

from testrunner.models import Host, TestSuite


class HostInterface(object):
    def __init__(self):
        self._target = 'not set'

    @property
    def target(self):
        return self._target

    @target.setter
    def target(self, value):
        print("setter of target called", value)
        self._target = value

    @target.deleter
    def target(self):
        print("deleter of target called")
        del self._target

    def host(self):
        out = Host.objects.get(id=self.target).name
        return out


class YamlInterface:
    def __init__(self, yamlfile):
        self.file = yamlfile

    def handle_yaml(self):
        data = TestSuite.objects.get(id=self.file)
        yamldata = yaml.safe_load(data.text)
        for i in yamldata['testsuite']:
            status = subprocess.call('python3 %s' % i, shell=True)
            print(status)


def run_tests(host, yaml):
    h_interface = HostInterface()
    h_interface.target = host
    h_interface.host()
    yaml = YamlInterface(yaml)
    yaml.handle_yaml()
from __future__ import unicode_literals
from django.db import models


class Host(models.Model):
    ip_address = models.CharField(max_length=16)
    port = models.IntegerField()
    name = models.CharField(max_length=256)


class TestSuite(models.Model):
    name = models.CharField(max_length=256)
    text = models.TextField()
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return "%s" % self.name
仅包含django导入的库:

Enterprize:testrunner xwing$ python3 ping_google.py
Traceback (most recent call last):
  File "ping_google.py", line 1, in <module>
    from testrunnerlib.test import HostInterface
  File "/Users/xwing/PycharmProjects/testrunner/testrunnerlib/test.py", line 11, in <module>
    from testrunner.models import Host, TestSuite
  File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 5, in <module>
    class Host(models.Model):
  File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
from testrunnerlib.test import HostInterface
from testrunnerlib.outcomes import Outcomes

from ping3 import ping


def pinger(host):
    result = Outcomes()
    try:
        ping_google = ping(host)
        print(ping_google)
        if ping_google:
            return result.passed()
        msg = 'ping had an issue, the following is all we know %s' % ping_google
        return result.failed(msg)
    except Exception as e:
        return result.aborted(exception=e)

if __name__ == '__main__':
    pinger(HostInterface().target)
import yaml
import subprocess

from testrunner.models import Host, TestSuite


class HostInterface(object):
    def __init__(self):
        self._target = 'not set'

    @property
    def target(self):
        return self._target

    @target.setter
    def target(self, value):
        print("setter of target called", value)
        self._target = value

    @target.deleter
    def target(self):
        print("deleter of target called")
        del self._target

    def host(self):
        out = Host.objects.get(id=self.target).name
        return out


class YamlInterface:
    def __init__(self, yamlfile):
        self.file = yamlfile

    def handle_yaml(self):
        data = TestSuite.objects.get(id=self.file)
        yamldata = yaml.safe_load(data.text)
        for i in yamldata['testsuite']:
            status = subprocess.call('python3 %s' % i, shell=True)
            print(status)


def run_tests(host, yaml):
    h_interface = HostInterface()
    h_interface.target = host
    h_interface.host()
    yaml = YamlInterface(yaml)
    yaml.handle_yaml()
from __future__ import unicode_literals
from django.db import models


class Host(models.Model):
    ip_address = models.CharField(max_length=16)
    port = models.IntegerField()
    name = models.CharField(max_length=256)


class TestSuite(models.Model):
    name = models.CharField(max_length=256)
    text = models.TextField()
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return "%s" % self.name
型号:

Enterprize:testrunner xwing$ python3 ping_google.py
Traceback (most recent call last):
  File "ping_google.py", line 1, in <module>
    from testrunnerlib.test import HostInterface
  File "/Users/xwing/PycharmProjects/testrunner/testrunnerlib/test.py", line 11, in <module>
    from testrunner.models import Host, TestSuite
  File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 5, in <module>
    class Host(models.Model):
  File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
from testrunnerlib.test import HostInterface
from testrunnerlib.outcomes import Outcomes

from ping3 import ping


def pinger(host):
    result = Outcomes()
    try:
        ping_google = ping(host)
        print(ping_google)
        if ping_google:
            return result.passed()
        msg = 'ping had an issue, the following is all we know %s' % ping_google
        return result.failed(msg)
    except Exception as e:
        return result.aborted(exception=e)

if __name__ == '__main__':
    pinger(HostInterface().target)
import yaml
import subprocess

from testrunner.models import Host, TestSuite


class HostInterface(object):
    def __init__(self):
        self._target = 'not set'

    @property
    def target(self):
        return self._target

    @target.setter
    def target(self, value):
        print("setter of target called", value)
        self._target = value

    @target.deleter
    def target(self):
        print("deleter of target called")
        del self._target

    def host(self):
        out = Host.objects.get(id=self.target).name
        return out


class YamlInterface:
    def __init__(self, yamlfile):
        self.file = yamlfile

    def handle_yaml(self):
        data = TestSuite.objects.get(id=self.file)
        yamldata = yaml.safe_load(data.text)
        for i in yamldata['testsuite']:
            status = subprocess.call('python3 %s' % i, shell=True)
            print(status)


def run_tests(host, yaml):
    h_interface = HostInterface()
    h_interface.target = host
    h_interface.host()
    yaml = YamlInterface(yaml)
    yaml.handle_yaml()
from __future__ import unicode_literals
from django.db import models


class Host(models.Model):
    ip_address = models.CharField(max_length=16)
    port = models.IntegerField()
    name = models.CharField(max_length=256)


class TestSuite(models.Model):
    name = models.CharField(max_length=256)
    text = models.TextField()
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return "%s" % self.name
admin.py

from django.contrib import admin
from django import forms
from testrunner.models import Host, TestSuite


class HostAdmin(admin.ModelAdmin):
    list_display = ['name']
    fields = ('name', 'ip_address', 'port')
    def __str__(self):
        return '%s' % self.name
    pass
admin.site.register(Host, HostAdmin)


class TestSuiteAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super(TestSuiteAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'text':
            formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
        return formfield
admin.site.register(TestSuite, TestSuiteAdmin)

您需要生成一个Django管理命令。这将允许您创建脚本,允许您使用Django的所有功能

您可以使用python3 manage.py ping_google运行此命令

要创建管理命令

在“应用程序”文件夹中,创建一个名为“管理”的模块(创建一个名为“管理”的文件夹,并在其中放置init.py文件)

在管理文件夹内,创建命令模块(文件夹和init.py文件)

在commands文件夹中创建ping_google.py文件

命令是这样写的

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):

    help = 'Desc of your command'

    def handle(self, *args, **options):
        #  Your logic goes here

您可以阅读有关自定义django命令的更多信息

我是否需要为每个目录中的所有脚本制作其中一个命令?或者我可以将这样的东西应用到整个目录中吗?如果不完全理解您的要求,您可以详细说明吗?测试运行程序解析可以联合开发的python脚本列表。我需要一种方法通过django应用程序运行这些新脚本,而无需额外添加。如果我需要为其中的每一个创建一个管理脚本命令,那么如果我可以简单地链接一个递归目录结构而不是每个文件(如果可能的话),或者我需要找到另一种方法,这将是非常理想的。接受这个答案是唯一能够帮助我解决这个问题的方法。我需要重构项目结构以使其正常工作