Beispiel #1
0
def instance_data(way_handled, additional_params):
    '''Return a custom http response associated the handling
       of the xform, in this case as a valid submission matched
       to a schema.
    '''
    try:
        if way_handled.submission.xform and \
           way_handled.submission.xform.has_linked_schema():
            meta = way_handled.submission.xform.get_linked_metadata()
            startdate = datetime.now().date() 
            enddate = startdate + timedelta(days=1)
            submits_today = meta.get_submission_count(startdate, enddate)
            startdate = datetime.min
            submits_all_time = meta.get_submission_count(startdate, enddate)
            response = SubmitResponse(status_code=200, forms_sent_today=submits_today,
                                      submit_id=way_handled.submission.id, 
                                      or_status_code=2000, 
                                      or_status=SUCCESSFUL_SUBMISSION,
                                      total_forms_sent=submits_all_time, 
                                      **additional_params)
                                      
            return response.to_response()
    except Exception, e:
        logging.error("Problem in properly responding to instance data handling of %s" %
                      way_handled)
Beispiel #2
0
def _do_domain_submission(request, domain_name, is_resubmission=False):
    if request.method != 'POST':
        return HttpResponse("You have to POST to submit data.")

    # ODK/legacy handling hack.
    # on a NON standard post (ie, not multipart/mixed), we hijack the file 
    # upload handler.
    # This is for multipart/mixed.  For text/xml, we can safely assume that 
    # it's just straight from raw_post_data.
    # and that is the case on the last case of the parsing/checksum calculation.
    if not request.META["CONTENT_TYPE"].startswith('multipart/form-data'):
        request.upload_handlers = [LegacyXFormUploadBlobHandler()]
    is_legacy_blob = False
    # get rid of the trailing slash if it's there
    if domain_name[-1] == '/':    
        domain_name = domain_name[0:-1]
        
    #ODK HACK - the ODK client appends /submission to the end of the URL.  So for testing purposes until
    #we get the header-based authentication, we need to strip out the /submission from the end.
    if len(domain_name.split('/')) > 1:
        fixdomain = domain_name.split('/')[0]
        odksuffix = domain_name.split('/')[1:]
        if odksuffix.count('submission') == 1:
            domain_name = fixdomain         

    try: 
        #Verify that the domain is valid if possible
        submit_domain = Domain.objects.get(name=domain_name)
    except Domain.DoesNotExist:
        logging.error("Submission error! %s isn't a known domain.  The submission has been saved with a null domain" % (domain_name))
        submit_domain = None
    try:        
        if request.FILES.has_key('xml_submission_file'):
            # ODK Hack. because the way in which ODK handles the uploads using 
            # multipart/form data instead of the w3c xform transport
            # we need to unwrap the submissions differently
            is_legacy_blob = False
            xform = request.FILES['xml_submission_file'].read()            
            request.FILES['xml_submission_file'].seek(0) #reset pointer back to the beginning            
            checksum = hashlib.md5(xform).hexdigest()
        elif request.FILES.has_key('raw_post_data'):        
            rawpayload = request.FILES['raw_post_data'].read()
            is_legacy_blob = True
            checksum = hashlib.md5(rawpayload).hexdigest()        
        elif len(request.raw_post_data) > 0:
            rawpayload = request.raw_post_data
            is_legacy_blob = True
            checksum = hashlib.md5(rawpayload).hexdigest()      
        else:                       
            logging.error("Submission error for domain %s, user: %s.  No data payload found." % \
                      (domain_name,str(request.user)))               
            response = SubmitResponse(status_code=500, or_status_code=5000)
            return response.to_response()     
            
    except Exception, e:
        return HttpResponseServerError("Saving submission failed!  This information probably won't help you: %s" % e)
Beispiel #3
0
def registration_response(way_handled, additional_params):
    '''Return a custom http response associated the handling
       of the xform, in this case as a valid backup file.
    '''
    try:
        # Registrations will eventually respond with some smart information
        # about the outcome of the registration and the data that was created,
        # but for now this doesn't do anything special except override the 
        # status message to say that we understood what you were trying to do.
        response = SubmitResponse(status_code=200, 
                                  submit_id=way_handled.submission.id, 
                                  or_status_code=2000, 
                                  or_status=SUCCESSFUL_REGISTRATION)
        return response.to_response()
    except Exception, e:
        logging.error("Problem in properly responding to backup handling of %s: %s" % \
                      (way_handled, e.message))
Beispiel #4
0
def duplicate_attachment(way_handled, additional_params):
    '''Return a custom http response associated the handling
       of the xform.  In this case, telling the sender that
       they submitted a duplicate
       '''
    try:
        # NOTE: this possibly shouldn't be a "200" code, but it is for 
        # now because it's not clear how JavaRosa will handle 202.
        # see: http://code.dimagi.com/JavaRosa/wiki/ServerResponseFormat
        response = SubmitResponse(status_code=200, or_status_code=2020, 
                                  or_status="Duplicate Submission.",
                                  submit_id=way_handled.submission.id,
                                  **additional_params)
        return response.to_response()
    except Exception, e:
        logging.error("Problem in properly responding to instance data handling of %s" %
                      way_handled)
Beispiel #5
0
def backup_response(way_handled, additional_params):
    '''Return a custom http response associated the handling
       of the xform, in this case as a valid backup file.
    '''
    try:
        from backups.models import Backup
        # Backups should only ever be posting as a single file
        # We don't know what it means if they're not
        if way_handled.submission.attachments.count() == 1:
            attachment = way_handled.submission.attachments.all()[0]
            backup = Backup.objects.get(attachment=attachment)
            response = SubmitResponse(status_code=200, 
                                      submit_id=way_handled.submission.id, 
                                      or_status_code=2000, 
                                      or_status=SUCCESSFUL_BACKUP,
                                      **{"BackupId": backup.id })
            return response.to_response()
    except Exception, e:
        logging.error("Problem in properly responding to backup handling of %s: %s" % \
                      (way_handled, e.message))
Beispiel #6
0
         app_name = way_handled.handled.app
         method_name = way_handled.handled.method
         try:
             module = __import__(app_name,fromlist=[''])
             if hasattr(module, method_name):
                 method = getattr(module, method_name)
                 response = method(way_handled, receiver_params)
                 if response and isinstance(response, HttpResponse):
                     return response
         except ImportError:
             # this is ok it just wasn't a valid handling method
             continue
     # either no one handled it, or they didn't want to override the 
     # response.  This falls back to the old default. 
     response = SubmitResponse(status_code=200, or_status_code=2000,
                               submit_id=new_submission.id,
                               **receiver_params)
     return response.to_response()
         
 except Exception, e:
     type, value, tb = sys.exc_info()
     traceback_string = "\n\nTRACEBACK: " + '\n'.join(traceback.format_tb(tb))
     logging.error("Submission error for domain %s, user: %s, header: %s" % \
                   (domain_name,str(request.user), str(request.META)), \
                   extra={'submit_exception':str(e), 'submit_traceback':traceback_string, \
                          'header':str(request.META)})
     # should we return success or failure here?  I think failure, even though
     # we did save the xml successfully.
     response = SubmitResponse(status_code=500, or_status_code=5000, 
                               or_status="FAIL. %s" % e)
     return response.to_response()