【发布时间】:2019-11-18 14:06:59
【问题描述】:
我是 django 和 python 的新手。我创建了一个 django web 应用程序,我还有一个 python 脚本,我必须在 web 应用程序的后端实时运行(就像它应该总是检查新的更新并告诉 web 来自 API 的新响应生成通知)。我正在使用 IBM-Qradar API,我必须通过它在 Web 应用程序上显示数据。
我有两个问题 1)有什么办法可以像我上面描述的那样在我的django项目中使用下面的python代码? 2) 并使用json格式的API响应将数据直接从响应变量存储到MySQL数据库中。
我只能找到通过使用表单将数据存储到数据库中的方法,这对我的项目来说不是必需的。
import json
import os
import sys
import importlib
sys.path.append(os.path.realpath('../modules'))
client_module = importlib.import_module('RestApiClient')
SampleUtilities = importlib.import_module('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)))
# -------------------------------------------------------------------------
# Using the fields parameter with 'GET'
# If you just print out the result of a call to the siem/offenses GET
# endpoint there will be a lot of fields displayed which you have no
# interest in. Here, the fields parameter will make sure the only the
# fields you want are displayed for each offense.
# 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'])
【问题讨论】:
-
基本上你正在寻找一个cronjob。您可以使用
celery。这是一个documentation,关于如何将 django 与 celery 集成。 -
@ruddra 你不需要 celery 来运行 cron 作业......
-
你是对的。 cron 作业的替代方法是使用 celery 周期性任务。
标签: mysql json django python-3.x