Example #1
0
    def test_is_extendable(self):
        """
        Tests that the XFrameOptionsMiddleware method that determines the
        X-Frame-Options header value can be overridden based on something in
        the request or response.
        """

        class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware):
            # This is just an example for testing purposes...
            def get_xframe_options_value(self, request, response):
                if getattr(request, "sameorigin", False):
                    return "SAMEORIGIN"
                if getattr(response, "sameorigin", False):
                    return "SAMEORIGIN"
                return "DENY"

        with override_settings(X_FRAME_OPTIONS="DENY"):
            response = HttpResponse()
            response.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), response)
            self.assertEqual(r["X-Frame-Options"], "SAMEORIGIN")

            request = HttpRequest()
            request.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(request, HttpResponse())
            self.assertEqual(r["X-Frame-Options"], "SAMEORIGIN")

        with override_settings(X_FRAME_OPTIONS="SAMEORIGIN"):
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
            self.assertEqual(r["X-Frame-Options"], "DENY")
Example #2
0
def insts_status(request, host_id):
    """
    Instances block
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login')

    errors = []
    instances = []
    compute = Compute.objects.get(id=host_id)

    try:
        conn = wvmInstances(compute.hostname,
                            compute.login,
                            compute.password,
                            compute.type)
        get_instances = conn.get_instances()
    except libvirtError as msg_error:
        errors.append(msg_error.message)

    for instance in get_instances:
        instances.append({'name': instance,
                          'status': conn.get_instance_status(instance),
                          'memory': conn.get_instance_memory(instance),
                          'vcpu': conn.get_instance_vcpu(instance),
                          'uuid': conn.get_uuid(instance),
                          'host': host_id,
                          'dump': conn.get_instance_managed_save_image(instance)
                          })

    data = json.dumps(instances)
    response = HttpResponse()
    response['Content-Type'] = "text/javascript"
    response.write(data)
    return response
Example #3
0
def register(request) :
  '''
  Handle a Post request with the following information:
  login, password, email
  '''
  print 'receiving a request'
  #parameter retrieval
  try :
    login = request.GET['registerLogin']
    password = request.GET['registerPassword']
    email = request.GET['registerEmail']
  except MultiValueDictKeyError :
    response=HttpResponse('400 - BAD URI')
    response.status_code=400
    return response
  
  #parameter validation
  loginIsValid = re.match('[\w0-9]*', login) and len(login) > 3 and len(login) < 16
  passwordIsValid = len(password) >= 6 
  #TODO check with number
  emailIsValid = re.match('[\w.]*@\w*\.[\w.]*', email)
  
  logger.info(login + ' ' + password + ' ' + email)
  
  if loginIsValid and passwordIsValid and emailIsValid :
     return processFormInformation(login, password, email, request)   
  else :
    response=HttpResponse("400")
    response['message'] = 'invalid information'
    response.status_code=400
    return response
Example #4
0
    def wrapper(request, *args, **kwargs):
        authentication = app_settings.RECURLY_WEBHOOK_HTTP_AUTHENTICATION

        # If the user has not setup settings.RECURLY_WEBHOOK_HTTP_AUTHENTICATION then
        # we trust they are doing it at the web server level.
        if authentication is None:
            return fn(request, *args, **kwargs)

        try:
            method, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
        except KeyError:
            response = HttpResponse()
            response.status_code = 401
            response['WWW-Authenticate'] = 'Basic realm="Restricted"'
            return response

        try:
            if method.lower() != 'basic':
                raise ValueError()

            if not constant_time_compare(auth.strip().decode('base64'), authentication):
                return HttpResponseForbidden()
        except Exception:
            return HttpResponseBadRequest()

        return fn(request, *args, **kwargs)
Example #5
0
def statements_get(req_dict):
    stmt_result = {}
    mime_type = "application/json"
    # If statementId is in req_dict then it is a single get - can still include attachments
    # or have a different format
    if 'statementId' in req_dict:     
        if req_dict['params']['attachments']:
            resp, content_length = process_complex_get(req_dict)
        else:
            st = Statement.objects.get(statement_id=req_dict['statementId'])
            
            stmt_result = json.dumps(st.to_dict(format=req_dict['params']['format']))
            resp = HttpResponse(stmt_result, content_type=mime_type, status=200)
            content_length = len(stmt_result)
    # Complex GET
    else:
        resp, content_length = process_complex_get(req_dict)
        
    # Set consistent through and content length headers for all responses
    try:
        resp['X-Experience-API-Consistent-Through'] = str(Statement.objects.latest('stored').stored)
    except:
        resp['X-Experience-API-Consistent-Through'] = str(datetime.now())
    
    resp['Content-Length'] = str(content_length) 

    # If it's a HEAD request
    if req_dict['method'].lower() != 'get':
        resp.body = ''

    return resp
Example #6
0
 def test_newlines_in_headers(self):
     # Bug #10188: Do not allow newlines in headers (CR or LF)
     r = HttpResponse()
     with self.assertRaises(BadHeaderError):
         r.__setitem__('test\rstr', 'test')
     with self.assertRaises(BadHeaderError):
         r.__setitem__('test\nstr', 'test')
Example #7
0
def purchase_order_stats(request):
    cursor = connection.cursor()
    query = """
    SELECT (SELECT COUNT(id)
    FROM po_purchaseorder where lower(status) = 'processed') AS processed_count,
    (SELECT SUM(total)
    FROM po_purchaseorder where lower(status) = 'processed') AS processed_sum,
    (SELECT COUNT(id)
    FROM po_purchaseorder where lower(status) = 'received') AS received_count,
    (SELECT SUM(total)
    FROM po_purchaseorder where lower(status) = 'received') AS received_sum,
    (SELECT COUNT(id)
    FROM po_purchaseorder where lower(status) = 'paid') AS paid_count,
    (SELECT SUM(total)
    FROM po_purchaseorder where lower(status) = 'paid') AS paid_sum,
    COUNT(id) AS total_count,
    SUM(total) AS total_sum
    FROM po_purchaseorder
    WHERE lower(status) != 'cancelled';
    """
    
    cursor.execute(query)
    row = cursor.fetchone()

    data = {'processed': {'count': row[0], 'amount': str(row[1])},
            'received': {'count': row[2], 'amount': str(row[3])},
            'paid': {'count': row[4], 'amount': str(row[5])},
            'total': {'count': row[6], 'amount': str(row[7])}}
    
    response = HttpResponse(json.dumps(data),
                            content_type="application/json")
    response.status_code = 200
    return response
Example #8
0
def deferred(request):
    from google.appengine.ext.deferred.deferred import (
        run,
        SingularTaskFailure,
        PermanentTaskFailure
    )

    response = HttpResponse()

    if 'HTTP_X_APPENGINE_TASKEXECUTIONCOUNT' in request.META:
        logger.debug("[DEFERRED] Retry %s of deferred task", request.META['HTTP_X_APPENGINE_TASKEXECUTIONCOUNT'])

    if 'HTTP_X_APPENGINE_TASKNAME' not in request.META:
        logger.critical('Detected an attempted XSRF attack. The header "X-AppEngine-Taskname" was not set.')
        response.status_code = 403
        return response

    in_prod = environment.is_production_environment()

    if in_prod and os.environ.get("REMOTE_ADDR") != "0.1.0.2":
        logger.critical('Detected an attempted XSRF attack. This request did not originate from Task Queue.')
        response.status_code = 403
        return response

    try:
        run(request.body)
    except SingularTaskFailure:
        logger.debug("Failure executing task, task retry forced")
        response.status_code = 408
    except PermanentTaskFailure:
        logger.exception("Permanent failure attempting to execute task")

    return response
Example #9
0
File: tests.py Project: 10sr/hue
 def test_max_age_expiration(self):
     "Cookie will expire if max_age is provided"
     response = HttpResponse()
     response.set_cookie('max_age', max_age=10)
     max_age_cookie = response.cookies['max_age']
     self.assertEqual(max_age_cookie['max-age'], 10)
     self.assertEqual(max_age_cookie['expires'], cookie_date(time.time()+10))
Example #10
0
 def _outer(request, *args, **kwargs):
     if ApiUser.auth(request.POST.get("username", ""), request.POST.get("password", ""), permission):
         response = fn(request, *args, **kwargs)
     else:
         response = HttpResponse()
         response.status_code = 401
     return response
Example #11
0
 def wrap(request, *args, **kwargs):
     obj = func(request, *args, **kwargs)
     data = json.dumps(obj, ensure_ascii=False)
     status = kwargs.get('status', 200)
     response = HttpResponse(mimetype='application/json', status=status)
     response.write(data)
     return response
Example #12
0
def get_scanner(request, station_id):

    if request.method == "OPTIONS":
        return HttpResponse()

    ret = '{"detail":"%s"}'
    auth = VigilateAuthentication()

    try:
        auth_result = auth.authenticate(request)
        if not auth_result:
            return HttpResponse(ret % "Unauthenticated", status=403)
        request.user = auth_result[0]
    except AuthenticationFailed as e:
        return HttpResponse(ret % e, status=401)

    try:
        station_id_int = int(station_id)
        station = Station.objects.filter(id=station_id_int, user=request.user.id)[0]
    except (ValueError, IndexError):
        return HttpResponse(ret % "Not found", status=404)

    with open(os.path.join(BASE_DIR, 'program_scanner/scanner.py'), 'r') as raw_scan:
        conf_scan = raw_scan.read()

    conf_scan = conf_scan.replace('DEFAULT_ID', station_id)
    conf_scan = conf_scan.replace('DEFAULT_USER', request.user.email)
    conf_scan = conf_scan.replace('DEFAULT_TOKEN', Station.objects.get(id=station_id_int).token)
    conf_scan = conf_scan.replace('DEFAULT_URL', request.get_host())
    conf_scan = conf_scan.replace('DEFAULT_SCHEME', request.scheme)

    rep = HttpResponse(content_type='text/x-python')
    rep['Content-Disposition'] = 'attachment; filename=scanner.py'
    rep.write(conf_scan)
    return rep
    def test_cache_write_unpickable_object(self):
        update_middleware = UpdateCacheMiddleware()
        update_middleware.cache = self.cache

        fetch_middleware = FetchFromCacheMiddleware()
        fetch_middleware.cache = self.cache

        request = self._get_request_cache('/cache/test')
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        self.assertEqual(get_cache_data, None)

        response = HttpResponse()
        content = 'Testing cookie serialization.'
        response.content = content
        response.set_cookie('foo', 'bar')

        update_middleware.process_response(request, response)

        get_cache_data = fetch_middleware.process_request(request)
        self.assertNotEqual(get_cache_data, None)
        self.assertEqual(get_cache_data.content, content.encode('utf-8'))
        self.assertEqual(get_cache_data.cookies, response.cookies)

        update_middleware.process_response(request, get_cache_data)
        get_cache_data = fetch_middleware.process_request(request)
        self.assertNotEqual(get_cache_data, None)
        self.assertEqual(get_cache_data.content, content.encode('utf-8'))
        self.assertEqual(get_cache_data.cookies, response.cookies)
Example #14
0
def page_view(request, slug, **kwargs):
    try:
        page = Page.objects.get(page_slug=slug)
    except ObjectDoesNotExist:
        return render_to_response('pages/404.html')

    # If private page do basic auth
    if page.is_private:
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                if auth[0].lower() == "basic":
                    uname, passwd = base64.b64decode(auth[1]).split(':')
                    user = authenticate(username=uname, password=passwd)
                    if user is not None and user.is_active:
                        request.user = user

                        return render_to_response('pages/page.html', {"page": page})

        response = HttpResponse()
        response.status_code = 401
        response['WWW-Authenticate'] = 'Basic realm="%s"' % "Basci Auth Protected"
        return response
    else:
        return render_to_response('pages/page.html', {"page": page})
Example #15
0
def run(req):    
    r = HttpResponse()
    r["Access-Control-Allow-Origin"]="*"
    try: 
        if req.method == "OPTIONS" or len(req.POST)==0: #FF3 trying to check if Cross Site Request allowed. 
            return r
        else: 
        #rpc request:
            fctname = req.POST["f"]
            payload = json.loads(req.POST["a"])
            cid = req.POST["cid"]
            if cid == "0" or cid == 0: 
                cid = datetime.datetime.now()
                signals.register_session.send("rpc", cid=cid,req=req)            
            UR.CID = cid
            MODULE = sys.modules[__name__]
            if  fctname in __EXPORTS:
                r.content = getattr(MODULE, fctname)(payload, req)
                return r
            else:
                assert False, "[PDF] method '%s' not found in __EXPORTS" %  fctname
                r.content = UR.prepare_response({}, 1,"[PDF] method '%s' not found in __EXPORTS" %  fctname)
                return r
    except IOError: 
        logging.error("[rpc.views.run] IOError")
        r.content = UR.prepare_response({}, 1,"I/O Error")
        return r
Example #16
0
 def _http_auth_helper(self, request):
     # At this point, the user is either not logged in, or must log in using
     # http auth.  If they have a header that indicates a login attempt, then
     # use this to try to login.
     if request.META.has_key('HTTP_AUTHORIZATION'):
         auth = request.META['HTTP_AUTHORIZATION'].split()
         if len(auth) == 2:
             if auth[0].lower() == 'basic':
                 # Currently, only basic http auth is used.
                 uname, passwd = base64.b64decode(auth[1]).split(':')
                 user = authenticate(username=uname, password=passwd)
                 if user and user.is_staff:
                     request.session['moat_username'] = uname
                     return None
     
     # The username/password combo was incorrect, or not provided.
     # Challenge the user for a username/password.
     resp = HttpResponse()
     resp.status_code = 401
     try:
         # If we have a realm in our settings, use this for the challenge.
         realm = settings.HTTP_AUTH_REALM
     except AttributeError:
         realm = ""
     
     resp['WWW-Authenticate'] = 'Basic realm="%s"' % realm
     return resp
Example #17
0
def destroy(request, app_name, model_name, user, id=None):
    '''
    ' Receive a model_name and data object via ajax, and remove that item,
    ' returning either a success or error message.
    '''

    cls = apps.get_model(app_name, model_name)
    try:
        obj = cls.objects.get_editable_by_pk(user, id)
        if obj is None:
            transaction.rollback()
            error = "User %s does not have permission to delete this object." % user
            return HttpResponse(json.dumps({'errors': error}, indent=4), content_type="application/json")
    except Exception as e:
        transaction.rollback()
        error = "There was an error for user %s trying to delete this object: %s" % (user, str(e))
        return HttpResponse(json.dumps({'errors': error}, indent=4), content_type="application/json")

    try:
        obj.delete()
    except Exception as e:
        transaction.rollback()
        error = "Unexpected error deleting object: %s: %s" % (type(e), e)
        return HttpResponse(json.dumps({'errors': error}, indent=4), content_type="application/json")

    transaction.commit()
    dump = json.dumps({'success': 'Successfully deleted item with primary key: %s' % id}, indent=4)
    response = HttpResponse(dump, content_type="application/json")
    response.status_code = 201
    return response
Example #18
0
def resguardoPdf(request, pk):

    resguardo = Resguardo.objects.get(id=pk)
    nombre = 'resguardo_' + str(resguardo.id)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;filename=resguardo.pdf'
    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=letter)

    def header():

        c.drawImage('static/images/CFPPCH.png', 10, 670, 130, 130)
        c.setLineWidth(.3)
        c.setFont('Helvetica-Bold', 20)
        c.drawString(120, 750, 'CEFPP')
        c.drawString(160, 740, )

        c.setFont('Helvetica-Bold', 15)
        c.drawString(480, 750, 'Inventario')

    c.setFillColorRGB(255, 0, 0)
    c.setFont('Helvetica', 12)
    c.drawString(485, 735, resguardo.inventario)

    c.line(460, 747, 560, 747)

    header()

    c.showPage()
    c.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
Example #19
0
def keypair(request):
    ec2data = request.session["ec2data"]
    response = HttpResponse(mimetype='text/plain')
    response['Content-Disposition'] = 'attachment; filename={kp_name}-key.pem'.format(
        **ec2data)
    response.write(ec2data['kp_material'])
    return response
Example #20
0
def makefile(request,projectID):
    response = HttpResponse()
    response['Content-Disposition'] = 'attachment; filename=my.txt'
    statement = filemaker.make_Statement(projectID)
    print(statement)
    response.write(statement)
    return response
Example #21
0
    def add_view(self, request):
        """
        new_instance is the created instance of self.model or none, depending on if form.is_valid.
        Passed, for consistancy's sake to the template as "object"

        This view is csrf_exempt, which aparently conflicts with django's admin_view wrapper.
        This is problematic, as it exposes this view to anybody who knows the URL. @@TODO

        Uploadify doesn't properly pass the csrf_token, hopefully this is fixed in the release version of
        Uploadify.
        """
        instance_form = self.get_minimal_add_form()
        form = instance_form(request.POST, request.FILES, prefix=self.base_url())

        new_instance = None
        if form.is_valid():
            new_instance = form.save()
            template = select_template(self.item_add_template)
            context = RequestContext(request)
            context.update({
                    "insert": self,
                    "form": form,
                    "object": new_instance
                })
            response = HttpResponse(template.render(context))
            response.status_code = 201
            return response
        response = HttpResponse(form.errors)
        response.status_code = 400
        return response
Example #22
0
    def test_unicode_headers(self):
        r = HttpResponse()

        # If we insert a unicode value it will be converted to an ascii
        r['value'] = 'test value'
        self.assertTrue(isinstance(r['value'], str))

        # An error is raised when a unicode object with non-ascii is assigned.
        self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', 't\xebst value')

        # An error is raised when  a unicode object with non-ASCII format is
        # passed as initial mimetype or content_type.
        self.assertRaises(UnicodeEncodeError, HttpResponse,
                content_type='t\xebst value')

        # HttpResponse headers must be convertible to ASCII.
        self.assertRaises(UnicodeEncodeError, HttpResponse,
                content_type='t\xebst value')

        # The response also converts unicode keys to strings.)
        r['test'] = 'testing key'
        l = list(r.items())
        l.sort()
        self.assertEqual(l[1], ('test', 'testing key'))

        # It will also raise errors for keys with non-ascii data.
        self.assertRaises(UnicodeEncodeError, r.__setitem__, 't\xebst key', 'value')
Example #23
0
def statements_more_get(req_dict):
    stmt_result, attachments = get_more_statement_request(req_dict['more_id'])     

    if isinstance(stmt_result, dict):
        content_length = len(json.dumps(stmt_result))
    else:
        content_length = len(stmt_result)
    mime_type = "application/json"

    # If there are attachments, include them in the payload
    if attachments:
        stmt_result, mime_type, content_length = build_response(stmt_result)
        resp = HttpResponse(stmt_result, content_type=mime_type, status=200)
    # If not, just dump the stmt_result
    else:
        if isinstance(stmt_result, basestring):
            resp = HttpResponse(stmt_result, content_type=mime_type, status=200)
        else:
            resp = HttpResponse(json.dumps(stmt_result), content_type=mime_type, status=200)
    
    # Add consistent header and set content-length
    try:
        resp['X-Experience-API-Consistent-Through'] = str(Statement.objects.latest('stored').stored)
    except:
        resp['X-Experience-API-Consistent-Through'] = str(datetime.now())
    resp['Content-Length'] = str(content_length)
    
    # If it's a HEAD request
    if req_dict['method'].lower() != 'get':
        resp.body = ''

    return resp
Example #24
0
    def test_iter_content(self):
        r = HttpResponse(['abc', 'def', 'ghi'])
        self.assertEqual(r.content, b'abcdefghi')

        #test iter content via property
        r = HttpResponse()
        r.content = ['idan', 'alex', 'jacob']
        self.assertEqual(r.content, b'idanalexjacob')

        r = HttpResponse()
        r.content = [1, 2, 3]
        self.assertEqual(r.content, b'123')

        #test retrieval explicitly using iter and odd inputs
        r = HttpResponse()
        r.content = ['1', '2', 3, '\u079e']
        my_iter = r.__iter__()
        result = list(my_iter)
        #'\xde\x9e' == unichr(1950).encode('utf-8')
        self.assertEqual(result, [b'1', b'2', b'3', b'\xde\x9e'])
        self.assertEqual(r.content, b'123\xde\x9e')

        #with Content-Encoding header
        r = HttpResponse([1,1,2,4,8])
        r['Content-Encoding'] = 'winning'
        self.assertEqual(r.content, b'11248')
        r.content = ['\u079e',]
        self.assertRaises(UnicodeEncodeError,
                          getattr, r, 'content')
Example #25
0
def activity_state_get(req_dict):
    # add ETag for concurrency
    state_id = req_dict['params'].get('stateId', None)
    activity_id = req_dict['params']['activityId']
    agent = req_dict['params']['agent']
    a = Agent.objects.retrieve_or_create(**agent)[0]
    registration = req_dict['params'].get('registration', None)
    actstate = ActivityStateManager(a)
    # state id means we want only 1 item
    if state_id:
        resource = actstate.get_state(activity_id, registration, state_id)
        if resource.state:
            response = HttpResponse(resource.state.read(), content_type=resource.content_type)
        else:
            response = HttpResponse(resource.json_state, content_type=resource.content_type)
        response['ETag'] = '"%s"' % resource.etag
    # no state id means we want an array of state ids
    else:
        since = req_dict['params'].get('since', None)
        resource = actstate.get_state_ids(activity_id, registration, since)
        response = HttpResponse(json.dumps([k for k in resource]), content_type="application/json")
    
    # If it's a HEAD request
    if req_dict['method'].lower() != 'get':
        response.body = ''

    return response
Example #26
0
File: views.py Project: jittat/adm2
def list_qualified_applicants(request, download=True):
    submission_infos = (SubmissionInfo
                        .get_qualified_submissions()
                        .select_related(depth=1)
                        .all())
    applicants = get_applicants_from_submission_infos(submission_infos)

    personal_infos = build_model_dict(PersonalInfo)
    # added more info to applicants
    for a in applicants:
        if a.id in personal_infos:
            a.national_id = personal_infos[a.id].national_id
    
    FIELD_LIST = [
        'ticket_number', 
        'first_name', 
        'last_name', 
        'get_doc_submission_method_display', 
        'national_id' ]

    output_list = []
    for a in applicants:
        output_list.append(dump_fields(a, FIELD_LIST))
    output = u'\n'.join(output_list)

    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=applicants.csv'
    response.write(output)

    return response
Example #27
0
 def f(request, *args, **kwargs):
     # 1. check origin
     origin = request.META.get('HTTP_ORIGIN')
     if origin is None:
         origin = request.META.get('HTTP_REFERER')
         if origin:
             origin = cors.make_origin(origin)
     if not cors.check_origin(request, origin):
         return HttpResponseForbidden('bad origin')
     # 2. build response
     result = func(request, *args, **kwargs)
     json_str = json_dumps(result)
     response = HttpResponse(content_type='application/json')
     for variable in ('jsonpCallback', 'callback'):
         if variable in request.GET:
             identifier = request.GET[variable]
             if not re.match(r'^[$a-zA-Z_][0-9a-zA-Z_$]*$', identifier):
                 return HttpResponseBadRequest('invalid JSONP callback name')
             json_str = '%s(%s);' % (identifier, json_str)
             break
     else:
         response['Access-Control-Allow-Origin'] = origin
         response['Access-Control-Allow-Credentials'] = 'true'
         response['Access-Control-Allow-Headers'] = 'x-requested-with'
     response.write(json_str)
     return response
Example #28
0
def SaveExcel(request):
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename=BugList_'+time.strftime('%Y%m%d%H%M%S')+'.xls'
    wb = xlwt.Workbook(encoding = 'utf-8')
    sheet = wb.add_sheet(u'Bugs')
    #1st line
    sheet.write_merge(0, 0, 0, 4, 'Bug List')
    sheet.write(1,0, 'Bug ID')
    sheet.write(1,1, 'Problem')
    sheet.write(1,2, 'Create Person')
    sheet.write(1,3, 'Create Time')
    sheet.write(1,4, 'Note')
    row = 2
    for bug in Bug.objects.all():
        sheet.write(row,0, bug.id)
        sheet.write(row,1, bug.problem)
        sheet.write(row,2, bug.create_person)
        sheet.write(row,3, str(bug.create_time))
        sheet.write(row,4, bug.note)
        row=row + 1

    output = StringIO.StringIO()
    wb.save(output)
    output.seek(0)
    response.write(output.getvalue())
    return response
Example #29
0
 def _wrapper_(request):
     try:
         return view(request)
     except HttpError as ex:
         response = HttpResponse(unicode(ex), content_type="text/plain")
         response.status_code = ex.status
         return response
Example #30
0
def set_district(request):
    try:
        state = request.POST["state"]
        if state != "XX" and state not in us.statenames: raise Exception()
        district = int(request.POST["district"])
    except:
        return HttpResponseBadRequest()

    # Who represents?
    from person.models import Person
    mocs = None
    if state != "XX":
        mocs = [p.id for p in Person.from_state_and_district(state, district)]

    # Form response.
    response = HttpResponse(
        json.dumps({ "status": "ok", "mocs": mocs }),
        content_type="application/json")

    if request.user.is_authenticated():
        # Save to database.
        prof = request.user.userprofile()
        prof.congressionaldistrict = "%s%02d" % (state, district)
        prof.save()
    else:
        # Save in cookie.
        response.set_cookie("cong_dist", json.dumps({ "state": state, "district": district }),
            max_age=60*60*24*21)

    return response