【问题标题】:Is there a better way to write this script in python有没有更好的方法在 python 中编写这个脚本
【发布时间】:2016-12-13 17:42:03
【问题描述】:

我知道这很笨拙,我是初学者,但有没有更好的方法来做到这一点,我觉得有,但我不知道。我正在尝试做的是,只要分数变化高于 9,就发送电子邮件提醒。

代码如下:

#!/usr/bin/env python

"""
Script to send any pending alerts via email
"""

import sys
from pymongo import MongoClient
from datetime import datetime

#### begin


def send_email(): 
print "Begin GAMER-ALERT-SEND-EMAILS %s " % (datetime.now()).

if 'score_by_cat' >=9: 
        send_email()

 if 'score_by_cat' >=9:
       print( "Send Email")
    else:
       print('Nothing")




print "Begin GAMER-ALERT-SEND-EMAILS %s " % (datetime.now())


client = MongoClient('mongodb://localhost:28057/')
db = client.factor

email_rcpt_list = ['example@momo.com']
                  ['example2@momo.com']  

#process the alert..  if it is high enough risk and the makes sense (not a security control etc)

    for alert in db.risk_alerts.find({"$and" : [{'sent': False}]}):
        if float(alert['metric'])>=9 and alert['category']!='security control':
            #Call email send here
            for email in email_rcpt_list:
                print 'Call email and pass in the email address from email_rcpt_list'
                print ' Sample alert:  Vendor: %s  Has an new item %s on %s  of elevated risk %s in the category %s link: https://Gamer-dev.momo.net/profile/view/detail/%s' % (alert['vendor_name'],alert['key'],alert['source'],alert['metric'],alert['category'],alert['profile_id']) 
    #mark as sent always
    db.risk_alerts.update_one({"_id":alert['_id']},{"$set": {"sent":True}})

print "End GAMER-ALERT-SEND-EMAILS %s" % (datetime.now())

【问题讨论】:

  • 你确定这个脚本一开始就可以工作吗? if 'score_by_cat' >=9 不带冒号 :?
  • 是的,这里似乎存在格式问题。而在python中,格式化很重要,所以我们需要看到它的格式是否正确。
  • 好的,很抱歉我会编辑它
  • 我的个人风格总是将大量重复分解,例如使用.format( *( alert(x) for x in ("vendor_name","source","key",...) ))alerts。格式特定的你也可以"...{0[vendor_name]} ... {0[source]} ... ".format(alert)。不过,这可能与问题无关。
  • @jon 另外,如果您已经有了想要改进的可行代码,您可能需要考虑code review

标签: python email scripting alerts


【解决方案1】:

查看代码的前几行:

if 'score_by_cat' >=9

print "Begin GAMER-ALERT-SEND-EMAILS %s " % (datetime.now())
timestamp=datetime.utcnow()

条件语句(例如,ifelsefor)必须以冒号 (:) 结尾。我认为第二行应该缩进(如果分数> = 9,则必须发送电子邮件)。此外,此代码中未使用timestamp=datetime.utcnow();因此,您可以删除此行。

现在去重新检查您的代码是否存在潜在的格式错误。

【讨论】:

  • 谢谢,我现在就这么做,就像我说我是初学者一样
  • 只是一个问题,但有没有办法可以将所有这些变成一个函数并在 if 语句中简单地调用它?
  • “所有这些”是指:
  • print "Begin GAMER-ALERT-SEND-EMAILS %s " % (datetime.now()) timestamp=datetime.utcnow()?
  • 您可以使用:def send_email(): print "Begin GAMER-ALERT-SEND-EMAILS %s " % (datetime.now())。然后,您可以将前面的行重新格式化为:if 'score_by_cat' >=9: send_email()
猜你喜欢
  • 1970-01-01
  • 2019-06-28
  • 2011-02-21
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多