Ejemplo n.º 1
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobiles',
                            type=list,
                            required=True,
                            help='A mobiles list field is require',
                            location='json')
        parser.add_argument('content',
                            type=unicode,
                            required=True,
                            help='A content field is require',
                            location='json')
        args = parser.parse_args()
        try:
            sms = SMS(mobiles=json.dumps(request.json['mobiles']),
                      content=request.json['content'],
                      returned_value=-99,
                      user_id=1)
            db.session.add(sms)
            db.session.commit()
            sms_ini = app.config['SMS_WSDL_PARAMS']
            sms_client = SMSClient(sms_ini['url'])
            sms_client.sms_init(sms_ini['db_ip'], sms_ini['db_name'],
                                sms_ini['db_port'], sms_ini['user'],
                                sms_ini['pwd'])
            r = sms_client.sms_send(sms_ini['user'], sms_ini['user'],
                                    sms_ini['pwd'], request.json['mobiles'],
                                    request.json['content'], sms.id)
            sms.returned_value = r
            db.session.commit()
            del sms_client
        except Exception as e:
            logger.error(e)
            raise
        result = {
            'id': sms.id,
            'mobiles': json.loads(sms.mobiles),
            'date_send': str(sms.date_send),
            'content': sms.content,
            'user_id': sms.user_id,
            'returned_value': sms.returned_value
        }
        if sms.returned_value == 0:
            result['succeed'] = True
        else:
            result['succeed'] = False

        return result, 201
Ejemplo n.º 2
0
def create(request):
    try:
        json_obj = commonHttp.get_json(request.body)

        req_attrs = [
            expectedAttr["TO"], expectedAttr["TITLE"], expectedAttr["MESSAGE"]
        ]

        commonHttp.check_keys(json_obj, req_attrs)

        new_sms = SMS(to=json_obj[expectedAttr["TO"]],
                      title=json_obj[expectedAttr["TITLE"]],
                      message=json_obj[expectedAttr["MESSAGE"]])

        commonHttp.save_model_obj(new_sms)

        url = "http://smsgateway.me/api/v3/messages/send"
        data = {
            'email':
            '*****@*****.**',
            'password':
            env.SMS_ACC_PASSWORD,
            'device':
            '32326',
            'number':
            json_obj[expectedAttr["TO"]],
            'message':
            json_obj[expectedAttr["TITLE"]] + "," +
            json_obj[expectedAttr["MESSAGE"]]
        }

        r = requests.post(url, data)
        print "test"
        print r.json()['success']

        if r.json()['success'] == True:
            status = True
        else:
            status = False

        response = JsonResponse({"id": new_sms.id, "success": status})

        return response

    except commonHttp.HttpBadRequestException as e:
        return HttpResponseBadRequest(e.reason_phrase)
Ejemplo n.º 3
0
def sms(request):
    """
    Handles both the get and the post
    
    first thing is checks to make sure that the incoming message
    has the right secret device key
    
    POST:
    use the post data to create a SMS, and add it to the database
    will return empty 200 if success, or 500/400 with an {'error': <error message>} json body
    
    GET:
    gets up to max_sms sms, and returns them in a json list
    as well as a sms_count
    """

    attrs = ('to_number', 'from_number', 'body')

    if request.method == "POST":

        device = authorize(request.POST.get('key'))
        if device is None:
            return HttpResponseForbidden()

        sms_dict = {}
        for attr in attrs:

            post_val = request.POST.get(attr)
            if post_val is None:
                return HttpResponseBadRequest("POST must have attribute %s" %
                                              attr)

            sms_dict[attr] = post_val

        new_sms = SMS(**sms_dict)

        sms_handlers = []
        sms_handler_tuple = getattr(settings, 'SMS_HANDLERS', [])
        for sms_handler_string in sms_handler_tuple:
            sms_handlers.append(get_callable(sms_handler_string))

        # call the handlers? is this the best way?
        for sms_handler in sms_handlers:
            retval = sms_handler(new_sms)
            if retval is False:
                break

        return HttpResponse()

    elif request.method == "GET":
        """
        Remove this section if you will not be using
        The database as a queue for SMS sending-consumers
        """

        device = authorize(request.GET.get('key'))
        if device is None:
            return HttpResponseForbidden()

        max_sms = request.GET.get('max_sms',
                                  getattr(settings, 'SMS_MAX_SMS_GET', 10))

        # ok, get that many!
        if max_sms is None:
            sms_set = SMS.objects.all().order_by('datetime')
        else:
            sms_set = SMS.objects.all().order_by('datetime')[:max_sms]

        sms_list = list(sms_set.values(*attrs))

        count = len(sms_list)

        data_out = {'sms_count': count, 'sms': sms_list}

        for sms in sms_set:
            sms.delete()

        return HttpResponse(json.dumps(data_out))
Ejemplo n.º 4
0
def sms(request):
    """
    Handles both the GET and the POST
    
    first thing is checks to make sure that the incoming message
    has the right secret device key
    
    POST:
    use the post data to create a SMS, and add it to the database
    will return empty 200 if success, or 500/400 with an {'error': <error message>} json body
    
    GET:
    gets up to max_sms sms, and returns them in a json list
    as well as a sms_count
    """

    attrs = ('to_number', 'from_number', 'body')

    if request.method == "POST":
        """
        Handles an incoming SMS
        """
        device = authorize(request.POST.get('key'))
        if device is None:
            return HttpResponseForbidden(str(device))

        sms_dict = {}
        for attr in attrs:
            post_val = request.POST.get(attr)
            if post_val is None:
                return HttpResponseBadRequest("POST must have attribute %s" %
                                              attr)
            sms_dict[attr] = post_val
        new_sms = SMS(**sms_dict)

        sms_handlers = []
        sms_handler_tuple = getattr(settings, 'SMS_HANDLERS', [])
        for sms_handler_string in sms_handler_tuple:
            sms_handlers.append(get_callable(sms_handler_string))

        # call the handlers? is this the best way?
        for sms_handler in sms_handlers:
            retval = sms_handler(new_sms)
            if retval is False:
                break

        return HttpResponse()

    elif request.method == "GET":
        """
        Remove this section if you will not be using
        The database as a queue for SMS sending-consumers
        """
        device = authorize(request.GET.get('key'))
        if device is None:
            return HttpResponseForbidden(str(device))

        try:
            return dj_simple_sms.SMS_SENDER.respond_to_get(request)
        except NotImplementedError:
            return HttpResponseNotAllowed('GET')