如何将数据从views.py存储到mysql数据库

时间:2019-07-12 08:27:58

标签: mysql python-3.x django-models django-forms django-views

我想将来自views.py的数据存储到mysql数据库中。 我已经创建了一个名为“犯罪”的表格 它具有以下字段id(自动递增字段),oid,说明

我想将id与oid保存在一起,将description与描述保存到数据库中。 因为我已经将变量从views.py中的此函数传递到table.html页面,所以我也希望将其保存在数据库中。

或者,如果我可以将其保存在数据库中并将数据从数据库中检索到table.html,也有可能

如果任何人都可以告诉我这两种方法,那将是非常可观的。

所有文件都在同一文件夹中。

forms.py

from django import forms

class offenseForm(forms.ModelForm):
    class Meta:
        model = offenses
        fields = "__all__"

views.py

def main(request):

    # First we have to create our client
    client =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
    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')
        """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)))
    no_of_offense = 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
    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')
        """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'])


    context1 = {
        'ids': [j['id'] for j in response_body],
        'response': response_body,
        'dict_values': {'a': 1, 'b': 2}
    }

    return render(request, 'table.html', context1)

table.html

<!doctype html>
<html lang="en">
<head>

</head>
<body>
{% block content %}

   <div class="content">
        <div class="container-fluid">
            <p> Offenses <p>
            {% for r in response %}
             <pre>
                  {{ r.id }}
                  {{ r.description }}
             </pre>
            {% endfor %}
        </div>
        </div>
   </div>

       {% endblock %}


</body>
</html>
{% else %}
  <p>You are not logged in</p>
  <a href="{% url 'login' %}">login</a>
{% endif %}

models.py

from django.db import models
from django.core.validators import int_list_validator
# Create your models here.

class offenses(models.Model):
    oid = models.IntegerField(primary_key=True)
    description = models.CharField(null=False, max_length=20)
    assigned_to = models.CharField(null=True, max_length=20)
    categories = models.TextField(null=True)
    category_count = models.IntegerField(null=True)
    policy_category_count = models.IntegerField(null=True)
    security_category_count = models.IntegerField(null=True)
    close_time = models.TimeField(null=True)
    closing_user = models.IntegerField(null=True)
    closing_reason_id = models.IntegerField(null=True)
    credibility = models.IntegerField(null=True)
    relevance = models.IntegerField(null=True)
    severity = models.IntegerField(null=True)
    magnitude = models.IntegerField(null=True)
    destination_networks = models.TextField(null=True)
    source_network = models.CharField(null=True, max_length=20)
    device_count = models.IntegerField(null=True)
    event_count = models.IntegerField(null=True)
    flow_count = models.IntegerField(null=True)
    inactive = models.BooleanField(null=True)
    last_updated_time = models.DateTimeField(null=True)
    local_destination_count = models.IntegerField(null=True)
    offense_source = models.IntegerField(null=True)
    offense_type = models.IntegerField(null=True)
    protected = models.BooleanField(null=True)
    follow_up = models.BooleanField(null=True)
    remote_destination_count = models.IntegerField(null=True)
    source_count = models.IntegerField(null=True)
    start_time = models.TimeField(null=True)
    status = models.CharField(null=True, max_length=20)
    username_count = models.IntegerField(null=True)
    source_address_ids = models.TextField(null=True)
    local_destination_address_ids = models.TextField(null=True)
    domain_id = models.IntegerField(null=True)
    class Meta:
        db_table = "offenses"

也请记住,我只想加载一次数据。我不想每次我的应用程序运行时都添加重复数据

0 个答案:

没有答案