当前位置: 首页>>代码示例>>Python>>正文


Python models.Subscription类代码示例

本文整理汇总了Python中models.Subscription的典型用法代码示例。如果您正苦于以下问题:Python Subscription类的具体用法?Python Subscription怎么用?Python Subscription使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Subscription类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: subscribe

def subscribe(subscriber, resource):
    # HACK workaround for using get_or_create / create_or_get with GFKFields.
    try:
        # HACK workaround for querying equality of GFKField. I'd love to do the following:
        # Subscription.get(
        #     (Subscription.subscriber == subscriber) &
        #     (Subscription.resource == resource))

        sub = Subscription.get(
            (Subscription.subscriber_id == subscriber._get_pk_value()) &
            (Subscription.subscriber_type == subscriber._meta.db_table) &
            (Subscription.resource_id == resource._get_pk_value()) &
            (Subscription.resource_type == resource._meta.db_table))

        created = False

    except Subscription.DoesNotExist:
        sub = Subscription.create(
            subscriber=subscriber,
            resource=resource,
        )

        created = True

    return sub, created
开发者ID:franciscod,项目名称:telegram-universal-forwarder-bot,代码行数:25,代码来源:util.py

示例2: signup_verify

def signup_verify(request):
    email = request.GET.get('email', '')
    skey = request.GET.get('skey', '')
    old = datetime.now() - timedelta(days=10)
    blists = []
    try:
        optin = Optin.objects.get(skey=skey, email=email, created__gte=old)
        for l in optin.bulk_lists.all():
            if Subscription.subscribed.filter(email__iexact=optin.email, bulk_list=l).count() == 0:
                s = Subscription(email=optin.email, signup_location=optin.signup_location, bulk_list=l)
                s.save()

            blists.append(l)

        optin.verify(request)
    except Optin.DoesNotExist:
        #they've already subscribed; let's show them that instead of a 404
        #this prevents emails like "my link isn't working" after they've already clicked it once
        subs = Subscription.objects.filter(email=email)
        if len(subs):
            for sub in subs:
                blists.append(sub.bulk_list)
        else:
            raise Http404

    c = {'lists': blists}
    return TemplateResponse(request, 'signup_verified.html', c)
开发者ID:EdgeCaseLabs,项目名称:django-ecl-tools,代码行数:27,代码来源:views.py

示例3: sub_command

    def sub_command(self, message=None):
        """Subscribe the user to XMPP or SMS"""
        user = message.sender.split('/')[0]
	
        plist = message.body.split(' ' )
 	service_name = plist[1]

	if len(plist)>2:
	    type = "sms"
            user = plist[2]
	else:
	    type = "xmpp"
		
        service = Service.all().filter('name = ', service_name).get()

        if service:
            subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
            if subscription:
                message.reply("user %s is already subscribed to service %s" % (user, service.name))
            else:
                subscription = Subscription(key_name=hashlib.sha1(user).hexdigest(), type=type, address=user, service=service)
                subscription.put()
                message.reply("Subscribed %s to service %s" % (user, service.name))
        else:
            message.reply("Sorry, I couldn't find a service called "
                          "%s" % service_name)
开发者ID:feczo,项目名称:splashmon,代码行数:26,代码来源:xmpp.py

示例4: post

  def post(self):
    cl = Checklist.get(Key.from_path('Checklist', long(self.request.get('cl_id'))))
    if not helpers.checkPermissionAndRespond(self, cl=cl, edit=False):
      return
    
    user = users.get_current_user()
    
    for sub in Subscription.all().filter("user ==", user).filter("deleted ==", False):
      if sub.source.key() == cl.key():
        helpers.createResponse(self, 'message_already_subscribed.html', 
          {'old_checklist': cl})
        
    sub = Subscription(
        user=user,
        source=cl,
        deleted=False,                       
                       )        

    sub.put()

    for item in cl.item_set:
      subItem = SubscribedItem(
          subscription=sub,
          original=item,
          finished=False,
          deleted=False,                               
                               )
      subItem.put()
    
    helpers.createResponse(self, 'message_subscribed.html')
开发者ID:yoooyle,项目名称:checklist,代码行数:30,代码来源:create.py

示例5: create

def create():
    existing = Subscription.query.filter(Subscription.email == request.form["email"]).first()
    if existing is not None:
        abort(409)

    subscription = Subscription()
    subscription.email = request.form["email"]

    db.session.add(subscription)
    db.session.commit()

    return jsonify({"Subscription": "success"})
开发者ID:thecumets,项目名称:cumets-backend,代码行数:12,代码来源:subscription.py

示例6: testAddSubscription

    def testAddSubscription(self):
        Subscription.add_subscription('user1', 'kw1')
        Subscription.add_subscription('user2', 'kw2')
        Subscription.add_subscription('user1', 'kw2')
        Subscription.add_subscription('user2', 'kw2')

        ret = Subscription.get_active_subscriptions()
        print ret
        self.assertEqual(3, len(ret))
开发者ID:jiachengpan,项目名称:wechat-rent,代码行数:9,代码来源:test_models.py

示例7: subscription_post

def subscription_post(client, service):
    exists = Subscription.query.filter_by(device=client).filter_by(service=service).first() is not None
    if exists:
        return Error.DUPLICATE_LISTEN

    subscription_new = Subscription(client, service)
    db.session.add(subscription_new)
    db.session.commit()

    if zeromq_relay_uri:
        queue_zmq_message(json_encode({'subscription': subscription_new.as_dict()}))

    return jsonify({'service': service.as_dict()})
开发者ID:Pushjet,项目名称:Pushjet-Server-Api,代码行数:13,代码来源:subscription.py

示例8: seed

def seed(db=DATABASE_URI):
    """Seed the database with some seed data."""
    connect(db)
    user = User.create(email='[email protected]', password='test')

    # Create seed subscriptions through json file.
    with open('resources/seed/subscriptions.json', 'r') as f:
        subscriptions = Subscription.from_json(f.read())
        for subscription in subscriptions:
            if random.choice([True, False]):
                user.subscribe(subscription)

        # Ensure at least one subscription
        user.subscribe(subscriptions[0])

    # Create seed topics through json file.
    with open('resources/seed/topics.json', 'r') as f:
        topics = Topic.from_json(f.read())
        for topic in topics:
            user.subscribe(subscriptions[0], topic)

    # Create seed articles through json file.
    with open('resources/seed/articles.json', 'r') as f:
        articles = Article.from_json(f.read())
        for article in articles:
            topic = random.choice(list(article.source.topics()))
            ArticleTopic.create(article=article, topic=topic)

            user.add_article(article)
开发者ID:johnliu,项目名称:journal-server,代码行数:29,代码来源:db.py

示例9: post

def post(request):
    if not request.user.is_superuser:
        raise Http404

    if request.GET and request.GET.get('sent'):
        return render_to_response(request, 'subscribe/message.html', {'message': u'%s писем отправлено.' % request.GET.get('sent')})

    form = PostForm(request.POST)
    if request.POST and form.is_valid():
        log = logging.getLogger('django.email')
        subject, content = form.cleaned_data['message'].split("\n", 1)
        subject = subject.strip()
        count = 0
        fails = 0
        for s in Subscription.valid_emails():
            try:
                unsubscribe = u"\n\nЧтобы отписаться от рассылки, перейдите по ссылке\n\nhttp://%s/subscribe/cancel?email=%s&code=%s"\
                              % (settings.DOMAIN, s.email, s.delete_code)
                send_mail(subject, content + unsubscribe, settings.DEFAULT_FROM_EMAIL, [s.email])
                count += 1
            except Exception, e:
                log.error("Cannot send mail: %s", e)
                fails += 1

        log.info("%s emails sended, %s failed", count, fails)
        return HttpResponseRedirect(reverse('post') + '?sent=%s' % count)
开发者ID:wd5,项目名称:5-django_subscribe,代码行数:26,代码来源:views.py

示例10: get

 def get(self):
   user = users.get_current_user()
   checklist_q = Checklist.all().filter("user ==", user).filter("deleted ==", False).order("title");
   cursor = self.request.get('cursor_cl')
   if cursor:
     checklist_q = checklist_q.with_cursor(cursor)
   checklists = checklist_q.fetch(10)
   
   checklist_q = checklist_q.with_cursor(checklist_q.cursor())
   
   subs_by_cl = []
   for cl in checklists:
     subs = []
     for sub in cl.subscription_set:
       subs.append(sub)
     subs_by_cl.append(subs)
       
   subs_q = Subscription.all().filter("user ==", user).filter("deleted ==", False);
   cursor = self.request.get('cursor_sub')
   if cursor:
     subs_q = subs_q.with_cursor(cursor)
   subs = subs_q.fetch(10)
   
   subs_q = subs_q.with_cursor(subs_q.cursor())
   
   helpers.createResponse(self, 'dashboard_cls.html',
       {'checklists': checklists,
        'cursor_cl': checklist_q.cursor(),
        'subs_by_cl': subs_by_cl,
        'subs': subs,
        'cursor_sub': subs_q.cursor(),
        'more_subs': subs_q.count(1) == 1,
        'more_cls': checklist_q.count(1) == 1,
        })
开发者ID:yoooyle,项目名称:checklist,代码行数:34,代码来源:index.py

示例11: cmd_all

    def cmd_all(self, msg, args, chat=None):
        subscriptions = list(Subscription.select().where(
                             Subscription.tg_chat == chat))

        if len(subscriptions) == 0:
            return self.reply(msg, 'You have no subscriptions, so no tweets to show!')

        text = ""

        for sub in subscriptions:
            if sub.last_tweet is None:
                text += "\n{screen_name}: <no tweets yet>".format(
                    screen_name=escape_markdown(sub.tw_user.screen_name),
                )
            else:
                text += ("\n{screen_name}:\n{text} "
                         "[link](https://twitter.com/{screen_name}/status/{tw_id})").format(
                    text=markdown_twitter_usernames(escape_markdown(sub.last_tweet.text)),
                    tw_id=sub.last_tweet.tw_id,
                    screen_name=escape_markdown(sub.tw_user.screen_name),
                )

        self.reply(msg, text,
                   disable_web_page_preview=True,
                   parse_mode=telegram.ParseMode.MARKDOWN)
开发者ID:franciscod,项目名称:telegram-twitter-forwarder-bot,代码行数:25,代码来源:bot.py

示例12: work

 def work(self):
     for source in Subscription.select():
         if self.produce(source.url):
             self._logger.info('Producing source url %s.' % source.url)
         else:
             self._logger.info('Skipping source url %s.' % source.url)
     time.sleep(10)
开发者ID:johnliu,项目名称:journal-server,代码行数:7,代码来源:workers.py

示例13: post

    def post(self):
        active_subs = Subscription.get_active_subscriptions()

        items = json.loads(self.request.get('items'))
        logging.debug('before parsing, memory: %s' % runtime.memory_usage().current())
        parser = RentParser()
        parsed_items = []

        for item in items:
            try:
                parsed  = parser.parse(item)
                ret     = RentRecord.add_record(parsed)
            except Exception as e:
                logging.error(repr(e))

            parsed_items.append(parsed)

        logging.debug('after parsing, memory: %s' % runtime.memory_usage().current())

        user2message = filter_items(parsed_items, active_subs)

        for user, item in user2message.items():
            logging.debug('user: %s has %d messages' % (user, len(item)))
            User.update_user_items(user, item)
            url = get_short_url(user)
            if not url:
                url = site_config.url + '?user=%s' % user
            msg = [u'新找到%d条租房信息。' % len(item),
                   u'点击以下链接查看:',
                   url]

            messenger.send_message(user, '\n'.join(msg))
开发者ID:jiachengpan,项目名称:wechat-rent,代码行数:32,代码来源:handlers.py

示例14: unsub_command

    def unsub_command(self, message=None):
        """Unsubscribe the user from a service"""
        user = message.sender.split('/')[0]

        plist = message.body.split(' ' )
        service_name = plist[1]

	if len(plist)>2:
	    type = "sms"
            user = plist[2]
	else:
	    type = "xmpp"
		
        service = Service.all().filter('name = ', service_name).get()

        if service:
            subscription = Subscription.all().filter('address =', user).filter('service = ', service).filter('type =', type).get()
            if subscription:
                subscription.delete()
		if type == "xmpp":
	            	mobile = Mobile.all().filter('subscription = ', subscription).get()
			if mobile:
				mobile.delete()
                message.reply("Unsubscribed %s from service %s" % (user, service.name))
            else:
                message.reply("user %s is not subscribed to service %s" % (user, service.name))
        else:
            message.reply("Sorry, I couldn't find a service called "
                          "%s" % service_name)
开发者ID:feczo,项目名称:splashmon,代码行数:29,代码来源:xmpp.py

示例15: post

    def post(self):
        """Notify subscribers that a service changed status."""

        address = self.request.get('address')
        service = Service.get(self.request.get('service'))
        oldstatus = Status.get(self.request.get('oldstatus'))
        number = self.request.get('number')

        logging.info("Service: %s" % service)
        logging.info("Service name: %s" % service.name)

        msg = "%s changed state from %s to %s (%s)" % (
                service.name, oldstatus.name,
                service.current_event().status.name,
                service.current_event().message)

        user = Subscription.get_by_email(address)
        if user.status == "available" or not number:
        	status_code = xmpp.send_message(address, msg)
    		chat_message_sent = (status_code == xmpp.NO_ERROR)
		logging.info("Notified: %s\nmessage: %s code: %d" % (address, msg, status_code))
        elif user.status == "unavailable" and number:
		sms = smsgw(to = number, msg = msg)
		sms.send()
		logging.info("Offline SMS: %s\nmessage: %s" % (number, msg))
开发者ID:feczo,项目名称:splashmon,代码行数:25,代码来源:xmpp.py


注:本文中的models.Subscription类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。