當前位置: 首頁>>代碼示例>>Python>>正文


Python models.Email類代碼示例

本文整理匯總了Python中models.Email的典型用法代碼示例。如果您正苦於以下問題:Python Email類的具體用法?Python Email怎麽用?Python Email使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Email類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: supply

def supply(request):
    """
    If the HTTP Verb is GET: Provide a form for adding a new spam email message.
    
    If the HTTP Verb is POST: Save and process a new email message, and view
    the resulting message.
    
    :param HttpRequest request: A web request.
    :rtype: An HttpResponse object.
    """
    user = users.get_current_user()
    
    if user is None:
        return redirect(users.create_login_url('/supply'))
        
    usetting = UserSetting.gql('WHERE userid = :1', user.user_id())
    if usetting.count() != 1 or not usetting.get().is_contrib:
        return HttpResponseForbidden('<h1>Authorization Required</h1>')
        
    if request.method == 'GET':
        ctx = RequestContext(request, {})
        return render_to_response('input_form.html', context_instance=ctx)
        
    title = request.POST['title']
    input = request.POST['input'].lstrip('\t\n\r ')
    date = datetime.now()
    
    email = Email(title=title, body=input, date=date, views=0, rating=0)
    email.put()

    _process_new(email)
    
    return redirect('/view/%s' % email.key())
開發者ID:dzwarg,項目名稱:spamlibs,代碼行數:33,代碼來源:views.py

示例2: list

def list(request, page):
    """
    List all the spams in the system, using a paging output.
    
    :param HttpRequest request: A web request.
    :param integer page: The page to view.
    :rtype: An HttpResponse object.
    """
    pagesize = 10
    maxfwd = pagesize * 5 + 1
    
    order = 'date'
    if 'order' in request.GET:
        tmpo = request.GET['order']
        if tmpo[0] == '-':
            tmpo = tmpo[1:]
        if tmpo in Email.properties():
            order = request.GET['order']
    
    page = int(page)
        
    qry = Email.all().order(order)
    nspams = qry.count(offset=(page-1)*pagesize, limit=maxfwd)
    spams = qry.fetch(pagesize, offset=(page-1)*pagesize)
    
    ctx = RequestContext(request, {
        'spams':spams,
        'count':maxfwd,
        'pager':_pager(page, (page-1)*pagesize + nspams, 10),
        'order':order,
        'page':page
    })
    
    return render_to_response('list.html', context_instance=ctx)
開發者ID:dzwarg,項目名稱:spamlibs,代碼行數:34,代碼來源:views.py

示例3: index

def index(request):
    """
    Generate the front page of spamlibs. This shows the 10 most recent spam
    email messages, and allows users to seed and view them.
    
    :param HttpRequest request: A web request.
    :rtype: An HttpResponse object.
    """
    limit = 10
    
    qry = Email.all().order('-date')
    recent_spams = qry.fetch(limit)
    
    count = qry.count(limit=limit+1)
    
    qry = Email.all().order('-views')
    viewed_spams = qry.fetch(limit)
    
    qry = Email.all().order('-rating')
    popular_spams = qry.fetch(limit)
    
    ctx = RequestContext(request, {
        'recent_spams':recent_spams,
        'viewed_spams':viewed_spams,
        'popular_spams':popular_spams,
        'more':count==limit+1
    })    
    
    return render_to_response('index.html', context_instance=ctx)
開發者ID:dzwarg,項目名稱:spamlibs,代碼行數:29,代碼來源:views.py

示例4: send_email

def send_email(data):
	"""
	This is a helper function for sending emails based on the settings 
	provided in the settings.py file.
	"""
	if not settings.URL:
		abort(500,'Email provider URL is not set')
	if not settings.API_KEY:
		abort(500,'Email provider API_KEY is not set')

	status = False
	if settings.EMAIL_PROVIDER == 'MAILGUN':
		status = send_email_using_mailgun(data, settings.URL, settings.API_KEY)
		if status != 'success' and settings.AUTO_SWITCH_EMAIL_PROVIDER:		#check to auto switch email provider
			return send_email_using_mandrill(data, settings.ALT_URL, settings.ALT_API_KEY)

	elif settings.EMAIL_PROVIDER == 'MANDRILL':
		status = send_email_using_mandrill(data, settings.URL, settings.API_KEY)
		if status != 'success' and settings.AUTO_SWITCH_EMAIL_PROVIDER:		#check to auto switch email provider
			return send_email_using_mailgun(data, settings.ALT_URL, settings.ALT_API_KEY)

	if status == 'success':		#Storing emails sent in the database
		email = Email(to_name=data['to_name'], to_email=data['to'],
					  from_email=data['from'], from_name=data['from_name'],
					  subject=data['subject'], body=data['body'])
		if 'send_at' in data and data['send_at']:
			email.send_at = data['send_at']
		
		db_session.add(email)
		db_session.commit()
	
	return status
開發者ID:darshanrp,項目名稱:email_service,代碼行數:32,代碼來源:email_service.py

示例5: reset_db

def reset_db():
    from app import db
    from models import User, Email
    User.drop_table()
    User.create_table()

    Email.drop_table()
    Email.create_table()
開發者ID:v,項目名稱:mailblog,代碼行數:8,代碼來源:scripts.py

示例6: incoming

def incoming(request):
    """
    Accept a new email message directly via the AppEngine email facility. The
    entire email message is contained in the POST body of *email*.
    
    :param HttpRequest request: A web request.
    :rtype: An HttpResponse object.
    """
    logging.info('Incoming email received.')
    
    try:
        msg = InboundEmailMessage(request.raw_post_data)
        
        usetting = UserSetting.gql('WHERE email = :1', msg.sender)
        if usetting.count() == 0:
            logging.warn('Received email from an unrecognized sender: ' + msg.sender)
            
            return render_to_response('msg_receipt.email', mimetype='text/plain')
            
        if not usetting.get().is_contrib:
            logging.warn('Received email from an unauthorized contributor: ' + msg.sender)
            
            return render_to_response('msg_receipt.email', mimetype='text/plain')
            
        content = ''
        for content_type, body in msg.bodies('text/plain'):
            headers = True
            date = False
            for line in str(body).split('\n'):
                if not date:
                    parts = line.split(' ')
                    line = ' '.join(parts[len(parts)-5:])
                    date = datetime.strptime(line, '%a %b %d %H:%M:%S %Y')
                    logging.debug(str(date))
                    
                if headers and line == '':
                    headers = False
                elif not headers:
                    content += '%s\n' % line
        
        if content == '':
            logging.warn('Received an email, but no text/plain bodies.')
        else:
            logging.info('Compiled plain-text email: body length=%d' % len(content))
            
            newtitle = msg.subject.replace('\n','').replace('\r','')
            content = content.lstrip('\t\n\r ')
            email = Email(title=newtitle, body=content, date=date, views=0, rating=0)
            email.put()
            
            logging.info('Processing new data for tokens & tags')
            
            _process_new(email)
            
    except Exception, ex:
        logging.error('Error processing new email. %s' % ex)
開發者ID:dzwarg,項目名稱:spamlibs,代碼行數:56,代碼來源:views.py

示例7: get_queryset

    def get_queryset(self):
        selector = {}
        for k, v in self.request.GET.items():
            if v and k!='page':
                if k in self.header_fields:
                    k = 'header.' + k
                #TODO pretty unsafe to use user's input directly
                # TOO DANGEROUS OF NOSQL INJECTION
                selector[k] = {'$regex': '.*%s.*' % re.escape(v)}
                # Try using the python regex objects instead. Pymongo will serialize them properly
                # selector[k] = {'$regex': '.*%s.*' % re.escape(v), '$options': 'i'}
        # We have a middleware to set remote_addr
        logger.info('Selector is %s', selector, extra=self.request.__dict__)
        cursor = Email.find(**selector)

        paginator = Paginator(cursor, 20) # Show 20 contacts per page
        # pdb.set_trace()
        page = self.request.GET.get('page')
        try:
            emails = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            emails = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            emails = paginator.page(paginator.num_pages)
        return emails
開發者ID:icekittenxx,項目名稱:prism,代碼行數:27,代碼來源:views.py

示例8: confirm_email

def confirm_email(digest):
    res = redirect(url_for('account'))
    email = Email.create_with_digest(addr=request.args.get('email', ''),
                                     user_id=current_user.id,
                                     digest=digest)
    if email:
        try:
            DB.session.add(email)
            DB.session.commit()
            pending = request.cookies.get('pending-emails', '').split(',')
            try:
                pending.remove(email.address)
            except ValueError:
                pass  # when not in list, means nothing serious.
            res.set_cookie('pending-emails', ','.join(pending), max_age=10800)
            flash(u'{} confirmed.'.format(
                email.address), 'success')
        except IntegrityError as e:
            g.log.error('Failed to save new email address to account.',
                        exception=repr(e))
            flash(u'A unexpected error has ocurred while we were trying '
                  'to confirm the email. Please contact us if this continues '
                  'to happen.', 'error')
            return res
    else:
        flash(u"Couldn't confirm {}. Wrong link.".format(email), 'error')
    return res
開發者ID:Amstutz-IT,項目名稱:formspree,代碼行數:27,代碼來源:views.py

示例9: add_email

def add_email():
    address = request.form['address'].lower().strip()
    res = redirect(url_for('account'))

    g.log = g.log.bind(address=address, account=current_user.email)

    if Email.query.get([address, current_user.id]):
        g.log.info('Failed to add email to account. Already registered.')
        flash(u'{} is already registered for your account.'.format(
            address), 'warning')
        return res
    try:
        g.log.info('Adding new email address to account.')
        sent = Email.send_confirmation(address, current_user.id)
        if sent:
            pending = request.cookies.get('pending-emails', '').split(',')
            pending.append(address)
            res.set_cookie('pending-emails', ','.join(pending), max_age=10800)
            flash(u"We've sent a message with a verification link to {}."
                  .format(address), 'info')
        else:
            flash(u"We couldn't sent you the verification email at {}. "
                  "Please try again later.".format(
                    address), 'error')
    except ValueError:
        flash(u'{} is not a valid email address.'.format(
            request.form['address']), 'warning')
    return res
開發者ID:Amstutz-IT,項目名稱:formspree,代碼行數:28,代碼來源:views.py

示例10: get_email_or_404

def get_email_or_404(id_str):
    if not ObjectId.is_valid(id_str):
        raise ObjectDoesNotExist()
    email = Email.find_one({'_id': ObjectId(id_str)})
    if not email:
        raise ObjectDoesNotExist()
    return email
開發者ID:icekittenxx,項目名稱:prism,代碼行數:7,代碼來源:shortcuts.py

示例11: register

def register():
    if request.method == 'GET':
        return render_template('users/register.html')
    try:
        user = User(request.form['email'], request.form['password'])
        DB.session.add(user)
        DB.session.commit()
    except ValueError:
        DB.session.rollback()
        flash("%s is not a valid email address." % request.form['email'], "error")
        return render_template('users/register.html')
    except IntegrityError:
        DB.session.rollback()
        flash("An account with this email already exists.", "error")
        return render_template('users/register.html')

    login_user(user, remember=True)

    sent = Email.send_confirmation(user.email, user.id)
    res = redirect(request.args.get('next', url_for('account')))
    if sent:
        res.set_cookie('pending-emails', user.email, max_age=10800)
        flash("Your {SERVICE_NAME} account was created successfully!".format(**settings.__dict__), 'success')
        flash("We've sent an email confirmation to {addr}. Please go there and click on the confirmation link before you can use your {SERVICE_NAME} account.".format(addr=current_user.email, **settings.__dict__), 'info')
    else:
        flash("Your account was set up, but we couldn't send a verification email to your address, please try doing it again manually later.", "warning")
    return res
開發者ID:arun-shrestha,項目名稱:formspree,代碼行數:27,代碼來源:views.py

示例12: get

 def get(self, club_id, email_id):
     # check credentials
     if not(check_admin(club_id)):
         add_notify("Error", "You do not have the appropriate permissions")
         self.redirect("/")
         return
     user = users.get_current_user()
     club = Club.get_by_key_name(club_id)
     
     # get the email to be admin-ified
     email = Email.get_by_key_name(email_id)
     if not(email):
         add_notify("Error", "No email to be promoted!")
         self.redirect("/club/%s" % club.slug)
         return
     # find the link to promote it
     query = EmailToClub.all()
     query.filter("email =", email)
     query.filter("club =", club)
     link = query.get()
     if not(link):
         add_notify("Error", "No email to be promoted!")
         self.redirect("/club/%s" % club.slug)
         return
     if not link.enable:
         add_notify("Error", "Can't promote a disabled email")
         self.redirect("/club/%s" % club.slug)
         return
     # flip the admin bit
     link.admin = not(link.admin)
     link.put()
     # make sure we have at least one admin
     query = EmailToClub.all()
     query.filter("club =", club)
     query.filter("admin =", True)
     admin_check = query.get()
     if not(admin_check):
         # reverse the admin
         link.admin = True
         link.put()
     # send an email if you've just been promoted
     if link.admin:
         domain = "http://%s.appspot.com" % get_application_id()
         msg = mail.EmailMessage()
         fromaddr = "[email protected]%s.appspotmail.com" % get_application_id()
         msg.sender  = "Flyer Guy <%s>" % fromaddr
         msg.to      = email.email
         msg.subject = "[Flyer] You've an admin of %s!" % club.name
         msg.html    = template.render("templates/email_admin.html",
                                       {"domain":domain,
                                        "club":club.name,
                                        "email":email.id})
         try:
             msg.send()
         except apiproxy_errors.OverQuotaError, (message,):
             # Log the error
             add_notify("Error", "Could not send email")
             logging.error("Could not send email")
             logging.error(message)
開發者ID:thenoviceoof,項目名稱:flyer-poke,代碼行數:59,代碼來源:flyer.py

示例13: find_existing

 def find_existing(cls, email):
     hash = hashlib.md5(email).hexdigest()
     found = Account.all().filter("hash =", hash).get()
     if not found:
         found = Account.all().filter("hashes =", hash).get()
     if not found:
         found = Email.all().filter("email =", email).get()
     return found
開發者ID:Mondego,項目名稱:pyreco,代碼行數:8,代碼來源:allPythonContent.py

示例14: callback

def callback():
    """ Handles the home page rendering."""

    if request.data:
        data = json.loads(request.data)
    else:
        data = request.form

    email_from = data['from']
    name, email = parse_email(email_from) 
    
    user = User.get_or_create(name=name, email=email)
    subject = data['subject']

    reply_regex = re.compile('[Rr][Ee]\s*\:')
    fwd_regex = re.compile('[Ff][Ww][Dd]*\s*\:')

    subject = re.sub(reply_regex, '', subject).strip()
    subject = re.sub(fwd_regex, '', subject).strip()

    thread = Email.get_thread(subject)

    if 'time' in data:
        time = parse(data['time'])
    else:
        time = datetime.datetime.now()

    text = unquote(data['text'])

    if 'html' in data:
        html = unquote(data['html'])
    else:
        html = text

    email = Email(
            _from=user, 
            to=data['to'], 
            subject=subject,
            text=text,
            html=html,
            time=time,
            thread=thread,
        )

    email.save()
    return 'Thanks Swift'
開發者ID:v,項目名稱:mailblog,代碼行數:46,代碼來源:app.py

示例15: cadastrar_newsletter_ajax

def cadastrar_newsletter_ajax(request):
    try:
        email = strip_tags(request.POST['email'])
        nome = strip_tags(request.POST['nome'])
        try:
            cadastro = Email.objects.get(email = email)
            resposta = "email_existente"
        except Email.DoesNotExist:    
            novo_cadastro = Email()
            novo_cadastro.email = email
            novo_cadastro.nome = nome
            novo_cadastro.save()
            resposta = "sucesso" 
    except Exception:
        resposta = "falha" 
        pass
    return HttpResponse(resposta)
開發者ID:tiagofreire,項目名稱:micro,代碼行數:17,代碼來源:views.py


注:本文中的models.Email類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。