• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Subscription类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: _handle

    def _handle(self,url,tags,latlon):
        self._set_response_headers()

        user = users.get_current_user()

        if not user:
            response = { 'success': False, 'login': self._loginURL() }
        else:
            response = { 'success': False }
            if tags is not None:
                tags = tags.split(',')
            else:
                tags = []

            tags = [x for x in tags if len(x) > 0]

            src = NotificationSource.query( NotificationSource.url == url ).fetch(1)
            if len(src) == 1:
                src = src[0]
                conditions = [ Subscription.user == user,
                               Subscription.source == src.key,
                               Subscription.latlon == latlon ]
                if len(tags) > 0:
                  conditions.append( ndb.AND(*[Subscription.tags == tag for tag in tags]) )

                subscription = Subscription.query( *conditions ).fetch(1)
                if len(subscription) == 1:
                  subscription = subscription[0]
                  response = { 'success': True, 'id': subscription.key.urlsafe() }

        return json.dumps(response)
开发者ID:hasadna,项目名称:notification-center,代码行数:31,代码来源:main.py


示例17: unsms_command

    def unsms_command(self, message=None):
        """Unsubscribe the user from a service"""
	plist = message.body.split(' ')
	if len(plist)==2:
	        user = message.sender.split('/')[0]
	
	        service_name = plist[1]
	
	        service = Service.all().filter('name = ', service_name).get()
	
	        if service:
		    subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
		
		    if subscription:
	            	mobile = Mobile.all().filter('subscription = ', subscription).get()
	            	if mobile:
		    	    message.reply("Unsubscribed user %s from backup mobile %s for service %s" % (user, mobile.number,service_name))
	            	    mobile.delete()
			else:
			    message.reply("No backup mobile for user %s on %s service" % (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)
	else:
		 message.reply("Usege: unsms SERVICE +6112345678")
开发者ID:feczo,项目名称:splashmon,代码行数:27,代码来源:xmpp.py


示例18: sms_command

    def sms_command(self, message=None):
        """Subscribe the user to a offline SMS"""

        plist = message.body.split(' ')
	if len(plist)==3:
	        user = message.sender.split('/')[0]
	 	service_name = plist[1]
	 	number = plist[2]
	
	        service = Service.all().filter('name = ', service_name).get()
	
	        if service:
		 	subscription = Subscription.all().filter('address =', user).filter('service = ', service).get()
		
		        if subscription:
		            mobile = Mobile.all().filter('number =', number).get()
		            if mobile:
		                message.reply("user %s is already registered backup mobile %s for service %s" % (user, mobile.number,service_name))
		            else:
		                mobile = Mobile(number=number, subscription = subscription)
		                mobile.put()
		                message.reply("Subscribed user %s to backup mobile %s for service %s" % (user, number,service_name))
		        else:
		            message.reply("Sorry, I couldn't find a subscription on %s for %s" % (service_name,user))
	        else:
	            message.reply("Sorry, I couldn't find a service called "
	                          "%s" % service_name)
	else:
		message.reply("Usage: sms SERVICE +61412345678")
开发者ID:feczo,项目名称:splashmon,代码行数:29,代码来源:xmpp.py


示例19: get

  def get(self, **args):
    cl = Checklist.get(Key.from_path("Checklist", long(args['id'])))
    
    if not cl or cl.deleted: 
      helpers.createResponse(self, 'message_not_exist.html')
      return
    
    if not helpers.checkPermissionAndRespond(self, cl=cl, edit=False): return
    
    item_q = cl.item_set.filter("deleted ==", False).order("creation_time")
    cursor = self.request.get('cursor')
    if cursor:
      item_q = item_q.with_cursor(cursor)
    items = item_q.fetch(20)

    user = users.get_current_user()
    subscribed = False
    for sub in Subscription.all().filter("user ==", user).filter("deleted ==", False):
      if sub.source.key() == cl.key():
        subscribed = True
        break
   
    helpers.createResponse(self, 'dashboard_subscribe.html', 
        {'items': items,
        'cl': cl,
        'cursor_item': item_q.cursor(),
        'subscribed': subscribed,
        },
                           )   
开发者ID:yoooyle,项目名称:checklist,代码行数:29,代码来源:subscribe.py


示例20: locations_insert

    def locations_insert(self, location):
        """Insert a new location for the current user.

        Not part of the actual mirror API but used by the emulator.
        """

        if location.id is not None:
            raise endpoints.BadRequestException("ID is not allowed in request body.")

        location.put()

        # Notify location subscriptions

        data = {}
        data["collection"] = "locations"
        data["itemId"] = "latest"
        operation = Operation.UPDATE
        data["operation"] = operation.name

        header = {"Content-type": "application/json"}

        query = Subscription.query().filter(Subscription.user == endpoints.get_current_user())
        query = query.filter(Subscription.collection == "locations")
        query = query.filter(Subscription.operation == operation)
        for subscription in query.fetch():
            data["userToken"] = subscription.userToken
            data["verifyToken"] = subscription.verifyToken

            req = urllib2.Request(subscription.callbackUrl, json.dumps(data), header)
            try:
                urllib2.urlopen(req)
            except:
                logging.error(sys.exc_info()[0])

        return location
开发者ID:Jeliz187,项目名称:mirror-api,代码行数:35,代码来源:mirror_api.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.SyndicatedPost类代码示例发布时间:2022-05-27
下一篇:
Python models.Submission类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap