web2py重新创建(重置)数据库的计划任务

2024-04-19 07:03:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个CRON作业,它将一个包含9000行设备名的文本文件放入其中。在

这个作业每天用我们域中网络爬虫程序更新的列表重新创建文件。在

我遇到的是,当我让下面的工作线程运行导入到数据库中时,db.[name].id使用下面的方法不断增长

scheduler.py

# -*- coding: utf-8 -*-
from gluon.scheduler import Scheduler
def demo1():
    db(db.asdf.id>0).delete()
    db.commit()
    with open('c:\(project)\devices.list') as f:
        content = f.readlines()
        for line in content:
            db.asdf.insert(asdf = line)
    db.commit()

mysched = Scheduler(db, tasks = dict(demo1 = demo1) )

default.py(初始启动)

^{pr2}$

所以下一次启动作业时,它将从db.[name].id = 9001开始。因此,根据爬虫的回报,身份证号每天都会增长9000左右。它看起来很草率,我不想在以后的几年里遇到一些我不知道的数据库限制问题。在

(我是DB新手(我知道,我不知道什么)

很好。。。。。在

这就是我想到的,我不知道这是否是最佳实践。我在创建条目的同一个函数中使用db.[name].drop()时遇到的一个问题是db表不存在,我的作业状态变为“失败”。所以我在工作中定义了表。见下文:

scheduler.py

from gluon.scheduler import Scheduler
def demo1():
    db.asdf.drop()  #<=====Kill db.asdf
    db.commit()     #<=====Commit Kill
    db.define_table('asdf',Field('asdf'),auth.signature )  #<==== Phoenix Rebirth!!!
    with open('c:\(project)\devices.list') as f:
        content = f.readlines()
        for line in content:
            db.asdf.insert(asdf = line)
    db.commit()     #<=========== Magic

mysched = Scheduler(db, tasks = dict(demo1 = demo1) )

在凤凰重生行上面的注释代码。这是实现我目标的最好方法吗?在

它从1开始,这就是我想要的,但是我应该这样做吗?在

谢谢!在

请原谅我用windows dir结构的例子,因为我当前的非prod沙盒是我的windows工作站。:(


Tags: 方法namepyid数据库db作业line
1条回答
网友
1楼 · 发布于 2024-04-19 07:03:12

为什么不在插入相应记录之前检查行是否存在?在

...
with open('c:\(project)\devices.list') as f:
    content = f.readlines()
    for line in content:
        # distinguishing t_ for tables and f_ for fields
        db_matching_entries = db(db.t_asdf.f_asdf==line).select()
        if len(db_matching_entries) == 0:
            db.t_asdf.insert(f_asdf = line)
        else:
            # here you could update your record, just in case ;-)
            pass
db.commit()     #<=========== Magic

有一个类似的过程,需要几秒钟才能完成2k-3k条目。你的时间不会超过半分钟。在

相关问题 更多 >