如何在外部python脚本Django

时间:2019-07-10 04:42:41

标签: django python-3.x

我尝试在项目目录中包含python脚本。我只想运行getoffense.py(在project1下),并且在执行getoffense.py后将间接运行3个脚本。这三个脚本是SampleUtilities.py,RestApiClient.py和config.py。这三个脚本位于“模块”下

当我与django分开运行此程序时,它运行正常,但是当我使用模块路径时,服务器会给我有关此错误的信息。

由于我是python和django的新手,我已尽我所能更好地解释了。 这是我的项目结构

C:.
├───.idea
└───project1
    ├───modules
    ├───Templates
    └───__pycache__

我想运行这些外部python脚本并将结果显示在html文件上。

这是我的getofense.py

import json
import os
import sys

import importlib
sys.path.append(os.path.realpath('/modules'))
client_module = importlib.import_module('/modules/RestApiClient')
SampleUtilities = importlib.import_module('/modules/SampleUtilities')


def main():

    # First we have to create our client
    client = client_module.RestApiClient(version='9.0')

    # -------------------------------------------------------------------------
    # Basic 'GET'
    # In this example we'll be using the GET endpoint of siem/offenses without
    # any parameters. This will print absolutely everything it can find, every
    # parameter of every offense.

    # Send in the request
    SampleUtilities.pretty_print_request(client, 'siem/offenses', 'GET')
    response = client.call_api('siem/offenses', 'GET')

    # Check if the success code was returned to ensure the call to the API was
    # successful.
    if (response.code != 200):
        print('Failed to retrieve the list of offenses')
        SampleUtilities.pretty_print_response(response)
        sys.exit(1)

    # Since the previous call had no parameters and response has a lot of text,
    # we'll just print out the number of offenses
    response_body = json.loads(response.read().decode('utf-8'))
    print('Number of offenses retrieved: ' + str(len(response_body)))

    # ------------------------------------------------------------------------

    # Setting a variable for all the fields that are to be displayed
    fields = '''id%2Cstatus%2Cdescription%2Coffense_type%2Coffense_source%2Cmagnitude%2Csource_network%2Cdestination_networks%2Cassigned_to'''

    # Send in the request
    SampleUtilities.pretty_print_request(client, 'siem/offenses?fields='+fields, 'GET')
    response = client.call_api('siem/offenses?fields=' +fields, 'GET')


    # Once again, check the response code
    if (response.code != 200):
        print('Failed to retrieve list of offenses')
        SampleUtilities.pretty_print_response(response)
        sys.exit(1)

    # This time we will print out the data itself
    #SampleUtilities.pretty_print_response(response)

    response_body = json.loads(response.read().decode('utf-8'))
    print(response_body)
    print(type(response_body))
    for i in response_body:
        print(i)
        print("")

    for j in response_body:
        print(j['id'])
        print(j['status'])
        print(j['description'])


if __name__ == "__main__":
    main()

这是错误消息

 File "C:\celery\project1\project1\urls.py", line 18, in <module>
    from . import views
  File "C:\celery\project1\project1\views.py", line 2, in <module>
    from . import getoffenses
  File "C:\celery\project1\project1\getoffenses.py", line 25, in <module>
    SampleUtilities = importlib.import_module('SampleUtilities')
  File "C:\Users\kiran.tanweer\Envs\celery\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named 'SampleUtilities'

1 个答案:

答案 0 :(得分:0)

几年前,我遇到了类似的问题。我想在Django视图中运行一些脚本。问题是进口。如果要在django中导入相同级别的某些模块,则必须使用“。”。前缀,如:

# Django
from .module import some_func

在Python脚本中,无需使用“。”在模块名称之前

# Python Script
from module import some_func

我建议您尝试这样编写导入:

import importlib
sys.path.append(os.path.realpath('./modules'))
client_module = importlib.import_module('./modules/RestApiClient')
SampleUtilities = importlib.import_module('./modules/SampleUtilities')

或者仅使用常规导入:

import importlib
from .modules import RestApiClient
from .modules impoort SampleUtilities

请注意,这里只有一些想法。我不确定这是否能解决您的问题。祝你好运,祝你愉快!