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


Python router.get_router函数代码示例

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


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

示例1: handle

 def handle(self, **options):
     try:
         connection = Connection.objects.get(identity=settings.PING_NUMBER)
         text = datetime.datetime.now().strftime('Worked at %H:%M %Y-%m-%d')
         get_router().handle_outgoing(OutgoingMessage(connection, text))
     except:
         print "exception"
         pass
开发者ID:CoolCloud,项目名称:ureport-project,代码行数:8,代码来源:send_ping_message.py

示例2: send_password

    def send_password(self):
        # generate a one time use password
        password = User.objects.make_random_password(length=6, allowed_chars='1234567890')
        self.set_password(password)
        self.save()

        # send the SMS out
        (backend, created) = Backend.objects.get_or_create(name='mtn_3071')
        (connection, created) = Connection.objects.get_or_create(backend=backend, identity=self.username)
        get_router().add_outgoing(connection, "Your motome password is: %s %s %s" % (password[:2], password[2:4], password[4:]))
开发者ID:matsinvasion,项目名称:motome,代码行数:10,代码来源:models.py

示例3: dashboard

def dashboard(req):
    """ dashboard for viewing poll status and incoming / outgoing messages """
    # lets flush the messages & starts the workers
    get_router(True)
    if req.method.upper() == "GET":
        reply_form = ReplyForm()

    elif req.POST["action"].upper() == "REPLY":
        reply_form = ReplyForm(req.POST)
        if reply_form.is_valid():
            if Connection.objects.filter(identity=reply_form.cleaned_data["recipient"]).count():
                text = reply_form.cleaned_data["message"]
                try:  # if the contact is in the database perform a mailmerge
                    conn = Connection.objects.filter(identity=reply_form.cleaned_data["recipient"])[0]
                    text = _mail_merge(Contact.objects.get(connection__identity=conn.identity), text)
                except:
                    pass
                outgoing = OutgoingMessage(conn, text)
                get_router().handle_outgoing(outgoing)
            else:
                ## Create the contact and send it an email ???
                # reply_form.errors['recipient']="This number isn't in the system. please add a contact"
                print "the message was ignored because the contact is not in the database"
        else:
            reply_form.errors.setdefault("short_description", ErrorList())

            if "recipient" in reply_form.errors:
                reply_form.errors["recipient"].append("This number isn't in the system")
            if "message" in reply_form.errors:
                reply_form.errors["message"].append("A message is required")

    polls = Poll.objects.annotate(Count("responses")).order_by("start_date")[:5]
    data_collections = XForm.objects.annotate(Count("submissions")).order_by("created")[:5]
    messages = Message.objects.all().order_by("-date")[0:10]

    # get some real names per connection
    for message in messages:
        message.connection.name = "Unknown"
        if Contact.objects.filter(connection__identity=message.connection.identity).exists():
            message.connection.name = Contact.objects.get(connection__identity=message.connection.identity).name

    # prepare for the message table
    titles = [_("Text"), _("Direction"), _("Phone number"), _("Status"), _("Time")]
    table = read_only_message_table(messages, titles)

    return render_to_response(
        "polls/poll_dashboard.html",
        {"polls": polls, "data_collections": data_collections, "reply_form": reply_form, "messages_table": table},
        context_instance=RequestContext(req),
    )
开发者ID:msabramo,项目名称:HarukaSMS,代码行数:50,代码来源:views.py

示例4: approve

def approve(request,payment_pk):
    from requests.auth import HTTPBasicAuth
    payment=MobilePayment.objects.get(pk=payment_pk)
    s = requests.Session()
    s.auth = (settings.USERNAME, settings.PASSWORD)
    s.headers.update({'x-test': 'true'})
    payment.approved=True
    payment.save()
    client=payment.client
    loan=MLoan.objects.get(client=client)
    no_ofpayements=loan.term_frequency
    principal=int(loan.principal_amount)
    loan_officer=loan.loan_officer_id
    payements_count=MNote.objects.filter(loan_id=loan.id,client_id=client.id).count()
    next_payement=MLoanRepaymentSchedule.objects.filter(installment=payements_count+1)[0]
    pm=int(MLoanRepaymentSchedule.objects.filter(loan_id=loan.id)[0].principal_amount)
    balance=(no_ofpayements-(payements_count+1))*pm
    message="Thanks %s for your payment of %d on %s. Your remaining balance is %d and your next payment is due %s"%(client.firstname,payment.amount,payment.created.strftime("%d %b %Y"),balance,next_payement.duedate.strftime("%d %b"))
    post_url=settings.BASE_URL+"loans/%d/transactions?tenantIdentifier=default&command=repayment"%loan.id
    headers={"Content-type": "application/json"}
    now=datetime.datetime.now()
    post_dict={"locale": "en_GB","accountNumber": "%s"%payment.client.account_no,"dateFormat": "dd MMMM yyyy","transactionDate": "%s"%now.strftime("%d %b %Y"),"transactionAmount": "%d"%payment.amount,"note": "Mobile Payment"}
    r=requests.post(post_url,json.dumps(dict(post_dict)),verify=False,headers=headers,auth=HTTPBasicAuth(settings.USERNAME, settings.PASSWORD),)
    router = get_router()
    backend, created = Backend.objects.get_or_create(name="mifos")
    connection, created = Connection.objects.get_or_create(backend=backend, identity=payment.sender)
    msg1 = router.add_outgoing(connection, message)
    return HttpResponse(r.text)
开发者ID:sparkplug,项目名称:smsrelay,代码行数:28,代码来源:views.py

示例5: sendSMS

    def sendSMS(self, msg, connection=None):
        if not connection:
            connection = self.conn1

        router = get_router()
        db_msg = router.handle_incoming(connection.backend.name, connection.identity, msg)        
        return db_msg
开发者ID:fiston,项目名称:nsms,代码行数:7,代码来源:tests.py

示例6: demo

def demo(req, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    (b1, created) = Backend.objects.get_or_create(name='yo')

    # Terra

    (c1, created) = \
        Connection.objects.get_or_create(identity='256785137868',
            defaults={'backend': b1})

    # Sharad

    (b2, created) = Backend.objects.get_or_create(name='utl')
    (c2, created) = \
        Connection.objects.get_or_create(identity='256717171100',
            defaults={'backend': b2})
    router = get_router()
    outgoing = OutgoingMessage(c1,
                               "dear Bulambuli representative: uReport, Uganda's community-level monitoring system, shows that 75% of young reporters in your district found that their local water point IS NOT functioning."
                               )
    router.handle_outgoing(outgoing)
    outgoing = OutgoingMessage(c2,
                               "dear Amuru representative: uReport, Uganda's community-level monitoring system, shows that 46.7% of young reporters in your district found that their local water point IS NOT functioning."
                               )
    router.handle_outgoing(outgoing)
    return HttpResponse(status=200)
开发者ID:Senescyt,项目名称:rapidsms-polls,代码行数:26,代码来源:views.py

示例7: setUp

    def setUp(self):
        """
        Create a dummy connection
        """




        self.backend = Backend.objects.create(name='test')
        self.connection = Connection.objects.create(identity='11235811', backend=self.backend)
        self.connection1 = Connection.objects.create(identity='4162549', backend=self.backend)
        self.connection2 = Connection.objects.create(identity='82764125', backend=self.backend)
        self.connection3 = Connection.objects.create(identity='256777773260', backend=self.backend)
        self.user,created=User.objects.get_or_create(username="admin")
        self.router=get_router()
        #create test contact
        self.connection.contact = Contact.objects.create(name='Anonymous User')
        self.connection.save()
        #create message flags
        word_list=['zombies','inferi','waves','living dead','monsters']
        for word in word_list:
            flag=Flag.objects.create(name=word)

        Flag.objects.create(name="jedi",words="luke,sky,walker,jedi",rule=2)
        #create test group
        self.gem_group=Group.objects.create(name="GEM")
        Location.objects.create(name="kampala",type=LocationType.objects.create(name="district",slug="district"))
开发者ID:CoolCloud,项目名称:ureport-project,代码行数:27,代码来源:model_tests.py

示例8: testRouter

    def testRouter(self):
	router = get_router()

	msg = OutgoingMessage(self.connection, "test")
	db_msg = router.handle_outgoing(msg)

	# assert a db message was created
	self.assertTrue(db_msg.pk)
	self.assertEqual(db_msg.text, "test")
	self.assertEqual(db_msg.direction, "O")
	self.assertEqual(db_msg.connection, self.connection)
	self.assertEqual(db_msg.status, 'Q')

	# check our queue
	msgs = Message.objects.filter(status='Q')
	self.assertEqual(1, len(msgs))

	# now mark the message as delivered
	router.mark_delivered(db_msg.pk)

	# load it back up
	db_msg = Message.objects.get(id=db_msg.pk)

	# assert it looks ok now
	self.assertEqual(db_msg.text, "test")
	self.assertEqual(db_msg.direction, 'O')
	self.assertEqual(db_msg.connection, self.connection)
	self.assertEqual(db_msg.status, 'D')
开发者ID:Senescyt,项目名称:rapidsms-httprouter,代码行数:28,代码来源:tests.py

示例9: testAppCancel

    def testAppCancel(self):
	router = get_router()

	class CancelApp(AppBase):
	    # cancel outgoing phases by returning True
	    def outgoing(self, msg):
		return False

	    @property
	    def name(self):
		return "ReplyApp"

	try:
	    router.apps.append(CancelApp(router))

	    msg = OutgoingMessage(self.connection, "test")
	    db_msg = router.handle_outgoing(msg)

	    # assert a db message was created, but also cancelled
	    self.assertTrue(db_msg.pk)
	    self.assertEqual(db_msg.text, "test")
	    self.assertEqual(db_msg.direction, "O")
	    self.assertEqual(db_msg.connection, self.connection)
	    self.assertEqual(db_msg.status, 'C')

	finally:
	    router.apps = []
开发者ID:Senescyt,项目名称:rapidsms-httprouter,代码行数:27,代码来源:tests.py

示例10: handle

    def handle(self, **options):

        #file1=open("/home/mossplix/log_8.txt")
        file2=open("/home/mossplix/incoming2.log")
        files=[file2]
        num=re.compile('([0-9]+)')
        for f in files:
            lines=f.readlines()
            for line in lines:
                parts=line.strip().rsplit('[FID:]')[1].split('] [')
                identity=num.search(parts[1]).groups()[0]
                message_text=parts[4].split(':')[2]

                try:
                    connection=Connection.objects.get(identity=identity)
                    msg=Message.objects.filter(connection__identity=identity,text__icontains=message_text,direction="I")
                    if msg.exists():
                        pass
                    else:
                        router=get_router()
                        router.handle_incoming(connection.backend.name, connection.identity, message_text)

#                        with open("/home/mossplix/desc.log", "r+") as f:
#                            old = f.read() # read everything in the file
#                            f.seek(0) # rewind
#                            f.write(line + old)

#                        msg=Message.objects.create(connection__identity=identity,text=message_text,direction="I")
#                        print "created "+msg.text
#                        if poll.objects.filter(pk=connection.contact.pk):
#                            poll.process_response(msg)
                except Connection.DoesNotExist:
                    pass
开发者ID:askpaul,项目名称:rapidsms-ureport,代码行数:33,代码来源:fix_kannel.py

示例11: view_message_history

def view_message_history(request, connection_id):
    """
        This view lists all (sms message) correspondence between 
        RapidSMS and a User 
        
    """
    direction_choices = DIRECTION_CHOICES
    status_choices = STATUS_CHOICES
    reply_form = ReplyForm()
    connection = get_object_or_404(Connection, pk=connection_id)

    if connection.contact:
        messages = Message.objects.filter(connection__contact=connection.contact)
    else:
        messages = Message.objects.filter(connection=connection)
    messages = messages.order_by('-date')

    total_incoming = messages.filter(direction="I").count()
    total_outgoing = messages.filter(direction="O").count()
    latest_message = None
    if total_incoming:
        latest_message = messages.filter(direction="I").latest('date')

    if request.method == 'POST':
        reply_form = ReplyForm(request.POST)
        if reply_form.is_valid():
            if Connection.objects.filter(identity=reply_form.cleaned_data['recipient']).count():
                text = reply_form.cleaned_data.get('message')
                conn = Connection.objects.filter(identity=reply_form.cleaned_data['recipient'])[0]
                in_response_to = reply_form.cleaned_data['in_response_to']
                outgoing = OutgoingMessage(conn, text)
                get_router().handle_outgoing(outgoing, in_response_to)
                return redirect("/contact/%d/message_history/" % connection.pk)
            else:
                reply_form.errors.setdefault('short_description', ErrorList())
                reply_form.errors['recipient'].append("This number isn't in the system")

    return render_to_response("contact/message_history.html", {
        "messages": messages,
        "stats_latest_message": latest_message,
        "stats_total_incoming": total_incoming,
        "stats_total_outgoing": total_outgoing,
        "connection": connection,
        "direction_choices": direction_choices,
        "status_choices": status_choices,
        "replyForm": reply_form
    }, context_instance=RequestContext(request))
开发者ID:asseym,项目名称:rapidsms-contact,代码行数:47,代码来源:views.py

示例12: get_backend_class

 def get_backend_class(self, backend_config, backend_name):
     path = backend_config["ENGINE"]
     module_name, class_name = path.rsplit('.', 1)
     module = __import__(module_name, globals(), locals(), [class_name])
     backend_class = getattr(module, class_name)
     router = get_router()
     backend = backend_class(router, backend_name, **backend_config)
     return backend
开发者ID:Senescyt,项目名称:rapidsms-httprouter,代码行数:8,代码来源:send_messages.py

示例13: fake_incoming_with_date

    def fake_incoming_with_date(self, message, connection, date):
        router = get_router()
        handled = router.handle_incoming(connection.backend.name, connection.identity, message)
        for response in handled.poll_responses.all():
            response.date = date
            response.save()

        return handled
开发者ID:krelamparo,项目名称:edtrac,代码行数:8,代码来源:abstract_clases_for_tests.py

示例14: handle

    def handle(self, **options):
        phone = options["phone"] or raw_input("Phone number you wish the message to appear to come from: ")
        text = options["text"] or raw_input("Text of the message: ")

        connection = Connection.objects.get(identity=phone)
        router = get_router()
        handled = router.handle_incoming(connection.backend.name, connection.identity, text)
        self.stdout.write("Done!\n")
开发者ID:krelamparo,项目名称:edtrac,代码行数:8,代码来源:fake_incoming_message.py

示例15: fake_incoming

 def fake_incoming(self, message, connection=None):
     if connection is None:
         connection = self.connection
     router = get_router()
     router.handle_incoming(connection.backend.name, connection.identity, message)
     form = XForm.find_form(message)
     if form:
         return XFormSubmission.objects.all().order_by('-created')[0]
开发者ID:hfeeki,项目名称:coffeeclub,代码行数:8,代码来源:tests.py


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