【问题标题】:How to send data from Django script to MySQL如何将数据从 Django 脚本发送到 MySQL
【发布时间】:2015-08-09 09:49:30
【问题描述】:

我在我的 Django 中在“polls”中创建了一个名为“bdd.py”的脚本,正如您在 tree 中看到的那样:

我的问题是该脚本应该将一些数据发送到我的 MySQL 数据库“TORRENTS”中的表 torrent_infos 中,但我在表中看不到任何内容。事实上,当我执行脚本时它似乎工作:

root@debian:/home/florian/Documents/mysite/polls# python bdd.py

但我的桌子还是空的,我不明白为什么。看看我的数据库:

mysql> DESCRIBE torrent_infos;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Name  | varchar(50) | YES  |     | NULL    |       |
| Size  | varchar(50) | YES  |     | NULL    |       |
| Hash  | varchar(60) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM torrent_infos ;
Empty set (0.01 sec)

这是我的脚本,可能是问题的根源,正如您所见,我从文件夹中的 .torrent 文件中获取信息,我正试图将其发送到我的表 torrent_infos。我尝试了一些缩进的更改,但没有成功。欢迎任何想法:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import mysql.connector
import bencode
import binascii
import hashlib
import os
import sys

conn = mysql.connector.connect(host="localhost",user="root",password="root", database="TORRENTS")
cursor = conn.cursor()
path = "/home/florian/TorrentFiles"
dirs = os.listdir(path)
for file in dirs:
        try:
                with open(os.path.join(path, file), 'rb') as torrentfile:
                        torrent = bencode.bdecode(torrentfile.read())
                        user = ("torrent['info']['name']","torrent['info']['length']","(hashlib.sha1(bencode.bencode(torrent['info'])).hexdigest())")
                        cursor.execute("""INSERT INTO torrent_infos (Name, Size, Hash) VALUES(%s, %s, %s)""", user)
        except bencode.BTL.BTFailure:
                continue


conn.close()

【问题讨论】:

  • 既然这是一个 django 应用程序,我想知道你为什么不为你的脚本使用 django 框架。 docs.djangoproject.com/en/1.8/howto/custom-management-commands
  • 您没有调用 conn.commit(),因此当您断开连接时,您的更改会回滚。不过,我认为你应该听从 Wtower 的建议,将这种事情作为 Django 的 managemenet 命令来实现。
  • @Wtower:谢谢,实际上我想知道我能找到有关它的信息吗?我会关注这个文档 :)
  • @Wtower 但我不太明白使用这个的好处
  • 你为什么首先使用 django 来开发这个应用程序?

标签: python mysql django python-2.7


【解决方案1】:

我将重写上面的内容以充分使用 django 框架作为custom management command

  • polls/ 中创建一个名为management 的目录
  • polls/management/ 中创建一个空的__init__.py 文件
  • polls/management/ 中创建一个名为commands 的目录
  • polls/management/commands/ 中创建一个空的__init__.py 文件
  • polls/management/commands/ 中创建一个bdd.py 文件
  • bdd.py 中定义一个从django.core.management.base.BaseCommand 继承的命令类,如文档示例中所示
  • models.py 中为torrent_infos 创建(如果您还没有这样做)适当的模型并导入bdd.py
  • 使用 Django ORM 正确定义命令逻辑。

通过这种方式,您可以充分利用 Django 框架、应用程序模型等。

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 2012-01-06
    • 1970-01-01
    • 2019-06-02
    • 2011-10-24
    • 2013-10-25
    • 1970-01-01
    • 2012-03-14
    • 2018-07-25
    相关资源
    最近更新 更多