如何将数据从Django脚本发送到MySQL

时间:2015-05-27 10:46:43

标签: python mysql django python-2.7

我在我的Django中创建了一个名为“bdd.py”的脚本,在“民意调查”中,你可以在tree中看到: enter image description here

我的问题是这个脚本应该在我的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()

1 个答案:

答案 0 :(得分:2)

我会重写上面的内容,将django框架充分用作custom management command

  • 在名为polls/
  • management中创建目录
  • __init__.py
  • 中创建一个空的polls/management/文件
  • 在名为polls/management/
  • commands中创建目录
  • __init__.py
  • 中创建一个空的polls/management/commands/文件
  • bdd.py
  • 中创建polls/management/commands/个文件
  • bdd.py中定义一个继承自django.core.management.base.BaseCommand的命令类,如文档示例所示
  • torrent_infos中创建models.py的{​​{1}}相应模型并导入bdd.py
  • 使用Django ORM正确定义命令逻辑。

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