import json import logging import os import time import urllib import urllib2 import urlparse from google.appengine.api import taskqueue from google.appengine.api import memcache from google.appengine.ext import ndb from google.appengine.api import urlfetch import jinja2 import webapp2 from sendgrid.helpers.mail import * from sendgrid import * import base_handlers import constants import list_builders import models JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__), constants.TEMPLATES_DIR)), extensions=[constants.TMPL_ENGINE_JINJA_AUTOESCAPE_EXTENSION], autoescape=True) def MaybeCreateMemcacheKey(key, default=1): num_scheduled = memcache.get(key) if not num_scheduled: memcache.add(key=key, value=default, time=2592000) class WaqarDemoStatsHandler(webapp2.RequestHandler): def get(self): scheduled = memcache.get("email_scheduled") sent = memcache.get("email_sent") failed = memcache.get("email_send_failure") custom_messages = memcache.get("custom_messages_sent") list_files_opened_for_read = memcache.get("list_files_opened_for_read") if not list_files_opened_for_read: list_files_opened_for_read = 0 if not custom_messages: custom_messages = 0 if not scheduled: scheduled = 0 if not sent: sent = 0 if not failed: failed = 0 self.response.write('<h1>LBT (Appengine) Mail stats</h1>' '<p><b>Custom messages sent using the UI:</b> %d</p>' '<p><b>Lists opened for read:</b> %d</p>' '<p><b>Actual emails scheduled:</b> %d</p>' '<p><b>Actual emails Sent:</b> %d</p>' '<p><b>Actual emails Failed:</b> %d</p>' % (custom_messages, list_files_opened_for_read, scheduled, sent, failed)) class WaqarDemoSingleMessageHandler(webapp2.RequestHandler): def post(self): workflow_config = """ { "strategy": "SucceedIfAnyOrFailIfAnyDeclineAsync", "tasks": [ { "module": "vi_workflow.adapters.simple_email_adapter", "type": "ViSimpleEmailAdapterAsync", "delay_seconds": 2, "abort_seconds": 40, "payload": { "receiver_email_address": "%s", "subject": "%s", "message": "%s" } } ] } """ % (self.request.get('to'), self.request.get('subject'), self.request.get('body')) #print workflow_config form_data = urllib.urlencode({ 'workflow-config': workflow_config }) result = urlfetch.fetch( follow_redirects=True, url=constants.VI_WORKFLOWS_ENDPOINT, payload=form_data, method=urlfetch.POST) final_url = result.final_url or result.content logging.info('Email sent! Pipeline: %s', final_url) logging.info('receiver_email_address: %s', receiver_email_address) class WaqarDemoHandler(webapp2.RequestHandler): """ Handles a request to the Demo for Waqar.""" def get(self): """ Handles a get request.""" results = models.ListTracker.query().order( -models.ListTracker.last_updated).fetch() template_values = { constants.UI_JINJA_TMPL_VALUE_SEARCH_OPTIONS_KEY: constants.SEARCH_OPTIONS_CONFIG, constants.UI_JINJA_TMPL_VALUE_SEARCH_OPTIONS_JSON_KEY: json.dumps(constants.SEARCH_OPTIONS_CONFIG), constants.UI_JINJA_TMPL_VALUE_RESULTS_KEY: results } template = JINJA_ENVIRONMENT.get_template('waqar.html') self.response.write(template.render(template_values)) def post(self): """Handle the actual request to send the emails out.""" subject = self.request.get('subject') body = self.request.get('body') task = taskqueue.add( url='/really_schedule_email_for_waqar', target=constants.TASK_QUEUE_TARGET_VALUE, params={ 'subject': subject, 'body': body, 'q': self.request.get('q') } ) MaybeCreateMemcacheKey("custom_messages_sent", default=1) memcache.incr("custom_messages_sent") class ReallyScheduleEmailHandler(webapp2.RequestHandler): def post(self): subject = self.request.get('subject') body = self.request.get('body') selected_lists = self.request.get('q') reconstructed_list_of_lists = json.loads(selected_lists) list_of_keys = [] for urlstring in reconstructed_list_of_lists: list_of_keys.append(ndb.Key(urlsafe=urlstring)) results = ndb.get_multi(list_of_keys) all_recipients = [] MaybeCreateMemcacheKey("email_scheduled", default=1) MaybeCreateMemcacheKey("list_files_opened_for_read", default=1) for list_tracker in results: if constants.ON_DEV: url = list_tracker.url.replace('/_ah/gcs', '') else: url = urlparse.urlparse(list_tracker.url).path parsed_data = json.loads(list_builders.ReadFile(url)) if '_final_results' in parsed_data: memcache.incr('list_files_opened_for_read') all_recipients += parsed_data['_final_results'] all_recipients = list(set(all_recipients)) for recipient in all_recipients: if '@' not in recipient: # in case the search is done requesting patientId, fake an email address of the form # %patientId%@vitalinteraction.com just so they are not rejected by sendgrid. recipient = '%s@vitalinteraction.com' % recipient task = taskqueue.add( url='/send_single_email_for_waqar', target=constants.TASK_QUEUE_TARGET_VALUE, params={ 'to': recipient, 'subject': subject, 'body': body } ) memcache.incr("email_scheduled") self.response.write( 'Total number of emails scheduled for delivery: %d' % len( all_recipients)) app = webapp2.WSGIApplication( [ ('/demo_for_waqar', WaqarDemoHandler), ('/demo_for_waqar_stats', WaqarDemoStatsHandler), ('/really_schedule_email_for_waqar', ReallyScheduleEmailHandler), ('/send_email_for_waqar', WaqarDemoHandler), ('/send_single_email_for_waqar', WaqarDemoSingleMessageHandler), ], debug=True)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question