【发布时间】: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