我在我的Django中创建了一个名为“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()
答案 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框架,应用程序的模型等。