2016-08-18 68 views
2

我試過讓這個工作,但必須有更好的方式,任何輸入是值得歡迎的。發送預定的電子郵件與pyramid_mailer和apscheduler

我試圖使用pyramid_mailer(存儲在.ini文件中的設置)在我的python金字塔應用程序中發送計劃的電子郵件,並且設置計劃的apscheduler。

我還使用SQLAlchemyJobStore,因此如果應用程序重新啓動,可以重新啓動作業。

jobstores = { 
    'default': SQLAlchemyJobStore(url='mysql://localhost/lgmim') 
} 
scheduler = BackgroundScheduler(jobstores=jobstores) 

@view_config(route_name='start_email_schedule') 
def start_email_schedule(request): 
    # add the job and start the scheduler 
    scheduler.add_job(send_scheduled_email, 'interval', [request], weeks=1) 
    scheduler.start() 

    return HTTPOk() 

def send_scheduled_email(request): 

    # compile message and recipients 
    # send mail 
    send_mail(request, subject, recipients, message) 

def send_mail(request, subject, recipients, body): 

    mailer = request.registry['mailer'] 
    message = Message(subject=subject, 
        recipients=recipients, 
        body=body) 

    mailer.send_immediately(message, fail_silently=False) 

這是就我所知,現在我得到一個錯誤,可能是因爲它不能pickle請求。

PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed 

使用pyramid.threadlocal.get_current_registry().settings獲得郵件工作的第一次,但此後我得到一個錯誤。我建議不要在任何情況下使用它。

我還能做什麼?

回答

2

通常情況下,你不能醃request對象,因爲它包含對開放套接字和其他有生命的對象的引用。

一些有用這裏的模式是

  • 數據庫您預生成的電子郵件ID,然後通過ID(INT,UUID)在調度

  • 您生成模板上下文(JSON字典),然後通過日程安排程序並在模型中渲染模板

  • 您在調度程序中執行所有數據庫讀取操作並且不會傳遞任何參數

具體問題如何生成一個調度內的人造request對象可以解決這樣的:

from pyramid import scripting 
from pyramid.paster import bootstrap 

def make_standalone_request(): 
    bootstrap_env = bootstrap("your-pyramid-config.ini") 
    app = bootstrap_env["app"] 
    pyramid_env = scripting.prepare(registry=bootstrap_env["registry"]) 
    request = pyramid_env["request"] 

    # Note that request.url will be always dummy, 
    # so if your email refers to site URL, you need to 
    # resolve request.route_url() calls before calling the scheduler 
    # or read the URLs from settings 

    return request 

Some more inspiration can be found here (disclaimer: I am the author).

+0

謝謝你,這是真的很有幫助。你的鏈接似乎被打破了。 – Niel

+0

修復了鏈接。被瀏覽器自動完成咬傷。 –