Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
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")
Exemplo n.º 5
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
Exemplo n.º 6
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
Exemplo n.º 7
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
Exemplo n.º 8
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
Exemplo n.º 9
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
Exemplo n.º 10
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
Exemplo n.º 11
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)
Exemplo n.º 12
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
Exemplo n.º 13
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
Exemplo n.º 14
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
Exemplo n.º 15
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')
Exemplo n.º 16
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
Exemplo n.º 17
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
Exemplo n.º 18
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')
Exemplo n.º 19
0
Arquivo: views.py Projeto: 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
Exemplo n.º 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
Exemplo n.º 21
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')
Exemplo n.º 22
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
Exemplo n.º 23
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
Exemplo n.º 24
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
Exemplo n.º 25
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
Exemplo n.º 26
0
    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)
Exemplo n.º 27
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
Exemplo n.º 28
0
Arquivo: tests.py Projeto: 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))
Exemplo n.º 29
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})
Exemplo n.º 30
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
Exemplo n.º 31
0
def story(request, id=None):
    """
    */entry/stories/<id>*, */entry/stories/new*

    The entry interface's edit/add/delete story view. This view creates
    the edit page for a given story, or the "new story" page if it
    is not passed an ID. It also accepts POST requests to create or edit
    stories.

    If called with DELETE, it will return a 200 upon success or a 404 upon
    failure. This is to be used as part of an AJAX call, or some other API
    call.
    """
    if request.method == 'DELETE':
        story = get_object_or_404(Story, pk=id)
        story.delete()
        return HttpResponse()

    if request.method == 'POST':
        message = ''
        post_data = request.POST.copy()

        story_form = StoryForm(post_data)
        if story_form.is_valid():
            image_keys = post_data.get('image_ids', None)
            images = []
            if image_keys:
                images = [Image.objects.get(
                    pk=int(i)) for i in image_keys.split(',')]
            video_keys = post_data.get('video_ids', None)
            videos = []
            if video_keys:
                videos = [Video.objects.get(
                    pk=int(v)) for v in video_keys.split(',')]
            if id:
                story = Story.objects.get(id=id)
                # process images
                existing_images = story.images.all()
                for image in existing_images:
                    if image not in images:
                        story.images.remove(image)
                for image in images:
                    if image not in existing_images:
                        story.images.add(image)
                # process videos
                existing_videos = story.videos.all()
                for video in existing_videos:
                    if video not in videos:
                        story.videos.remove(video)
                for video in videos:
                    if video not in existing_videos:
                        story.videos.add(video)
                story.__dict__.update(**story_form.cleaned_data)
                story.save()
            else:
                story = story_form.save()
                for image in images:
                    story.images.add(image)
                for video in videos:
                    story.videos.add(video)

            return HttpResponseRedirect(
                "%s?success=true" % reverse(
                    'edit-story', kwargs={'id': story.id}))
        else:
            pass
    else:
        message = ''

    if id:
        story = Story.objects.get(id=id)
        title = "Edit {0}".format(story.name)
        post_url = reverse('edit-story', kwargs={'id': id})
        story_form = StoryForm(instance=story)
        existing_images = story.images.all()
        existing_videos = story.videos.all()

        if request.GET.get('success') == 'true':
            message = "Story saved successfully!"

    elif request.method != 'POST':
        story_form = StoryForm()
        post_url = reverse('new-story')
        title = "New Item"
        existing_images = []
        existing_videos = []

    else:
        post_url = reverse('new-story')
        title = "New Item"
        existing_images = []
        existing_videos = []

    data = {'images': [], 'videos': []}

    for image in Image.objects.all():
        data['images'].append({
            'id': image.id,
            'name': image.name
        })

    for video in Video.objects.all():
        data['videos'].append({
            'id': video.id,
            'name': video.name
        })

    return render(request, 'story.html', {
        'parent_url': [
            {'url': reverse('home'), 'name': 'Home'},
            {'url': reverse('entry-list-stories'), 'name': 'Product Education'}
        ],
        'existing_images': existing_images,
        'existing_videos': existing_videos,
        'data_json': json.dumps(data),
        'data_dict': data,
        'title': title,
        'message': message,
        'post_url': post_url,
        'story_form': story_form,
    })
Exemplo n.º 32
0
def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)
Exemplo n.º 33
0
def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)
Exemplo n.º 34
0
def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)
Exemplo n.º 35
0
def portattack(req):
    """
    端口爆破
    :param req:
    :return:
    """
    data = json.loads(req.body)
    result = {"status": True, "msg": "成功", "data": "", "logid": ""}

    # id
    id = str(uuid.uuid1())
    try:
        if data["type"] == "create":
            # 创建端口的爆破任务,存储数据库
            # 爆破开始时间
            start_time = currenttime()
            # 爆破状态
            status = "running"
            # 爆破任务类型
            type = "ALL"
            # 扫描进度
            progress = "0.00"
            # 创建主任务数据
            PortCrack.objects.create(id=id,
                                     start_time=start_time,
                                     status=status,
                                     type=type,
                                     progress=progress)

            attackObject = AttackObject()
            # 必须调用setThreads方法,里面有对queue的初始化
            attackObject.setThreads(data["threads"])
            print attackObject.attack_queue_dict
            attackObject.pid = id
            attackObject.usernames = "/Users/margin/PycharmProjects/AnyScan/AnyScanUI/attack/ssh_username.txt"
            attackObject.passwords = "/Users/margin/PycharmProjects/AnyScan/AnyScanUI/attack/ssh_password.txt"

            # 实时显示任务的id
            result["logid"] = id
            # 要爆破的ip,port
            attack_dict = data["attack_dict"]
            attacker = Attacker(attackObject)
            status = attacker.attack(attack_dict, attack_task_id_dict={})
            if status == False:
                result["status"] == False
                result["msg"] == "任务添加异常,请查看日志"
        elif data["type"] == "start":
            id = data["id"]
            if id is None or id == "":
                result = {"status": False, "msg": "任务ID不可为空"}
                return HttpResponse(json.dumps(result, ensure_ascii=False))
            # 判断任务id是否存在
            portcrack = PortCrack.objects.get(id=id)
            if portcrack is None:
                result = {"status": False, "msg": "您所选的任务ID不存在"}
                return HttpResponse(json.dumps(result, ensure_ascii=False))
            # 如果任务不是暂停状态就在启动任务
            if portcrack.status != "pause":
                result = {
                    "status": False,
                    "msg": "您所选的任务不是【%s】,不能启动" % portcrack.status
                }
                return HttpResponse(json.dumps(result, ensure_ascii=False))

            # 查询任务信息和子任务信息,组织数据给Attacker.py
            child_set = portcrack.portcrackchild_set.all()
            # 组织给Attacker.py的数据  attack_dict: {"ip":[80,3306],"ip2":[22]}
            attack_dict = {}
            # 搞一个字典{"ip+port":id},为了能让attacker正确的取出当前任务的id
            attack_task_id_dict = {}
            for child in child_set:
                __ip = attack_dict.get(child.ip)
                if __ip is None or __ip == "":
                    attack_dict[child.ip] = [child.port]
                else:
                    attack_dict[child.ip].append(child.port)
                attack_task_id_dict[child.ip + child.port] = child.id

            # 更新该任务状态
            PortCrack.objects.filter(id=id).update(status="running",
                                                   end_time=currenttime())
            attackObject = AttackObject()
            # 当前攻击启动的类型
            attackObject.type = "start"
            attackObject.pid = id
            attacker = Attacker(attackObject)
            status = attacker.attack(attack_dict, attack_task_id_dict)
            if status == False:
                result["status"] == False
                result["msg"] == "任务启动异常,请查看日志"

    except Exception:
        result = {
            "status": False,
            "msg": "任务添加异常",
            "data": traceback.format_exc(),
            "logid": ""
        }
        print traceback.format_exc()
    return HttpResponse(json.dumps(result, ensure_ascii=False))
def index(request):
    return HttpResponse("Hello, world. You're at the login page.")
def register(request):
    return HttpResponse("Register.")
Exemplo n.º 38
0
def home(request):
    return HttpResponse('Greetings. Welcome to the time machine.')
Exemplo n.º 39
0
def today(request):
    date = datetime.date.today()
    return HttpResponse("Today's date is: {}".format(date))
Exemplo n.º 40
0
def DefaultPage(request):
    return HttpResponse('这是后端,请从前端访问' + '127.0.0.1:8080')
Exemplo n.º 41
0
def homepage(request):
    return HttpResponse('Hello Android Students.')
Exemplo n.º 42
0
def timestamp(request):
    ts = time.time()
    return HttpResponse("Timestamp: {}".format(ts))
Exemplo n.º 43
0
 def get(self, request, *args, **kwargs):
     return HttpResponse()
Exemplo n.º 44
0
def base_url_js(request):
    return HttpResponse(u"var __municipios_base_url__ = '%s';" % reverse('municipios-base-url'))
Exemplo n.º 45
0
def short_url(request, domain, app_id):
    build_profile_id = request.GET.get('profile')
    short_url = get_app(domain, app_id).get_short_url(build_profile_id=build_profile_id)
    return HttpResponse(short_url)
Exemplo n.º 46
0
            def get(self, request, *args, **kwargs):
                self.get_table()
                from django.http import HttpResponse

                return HttpResponse()
Exemplo n.º 47
0
def get_data(request, id):
    text = "Article Id is: %s" % id
    return HttpResponse(text)
Exemplo n.º 48
0
def short_odk_url(request, domain, app_id, with_media=False):
    build_profile_id = request.GET.get('profile')
    short_url = get_app(domain, app_id).get_short_odk_url(with_media=with_media, build_profile_id=build_profile_id)
    return HttpResponse(short_url)
Exemplo n.º 49
0
def list_provinces(request):
    try:
        provinces = session.query(SepeProvince).all()
        return HttpResponse(json.dumps([ province.name for province in provinces ]))
    finally:
        session.remove()
Exemplo n.º 50
0
def odk_media_qr_code(request, domain, app_id):
    profile = request.GET.get('profile')
    qr_code = get_app(domain, app_id).get_odk_qr_code(with_media=True, build_profile_id=profile)
    return HttpResponse(qr_code, content_type="image/png")
Exemplo n.º 51
0
def edit(request):
    if request.is_ajax():
        message = "Yes, AJAX!"
    else:
        message = "Not Ajax"
    return HttpResponse(message)
Exemplo n.º 52
0
def hello(request):
    text = """<h1>Welcome </h1>"""
    return HttpResponse(text)
Exemplo n.º 53
0
def hello(request):
    return HttpResponse('hello vk')
Exemplo n.º 54
0
def index(request):
    ad = ""
    mng = ""
    contexthome = {}
    lista_contracte = models.Contract.objects.all()
    contexthome['lista'] = lista_contracte
    contexthome['nume_fisier'] = "pdftest"

    if request.POST.get('sterg') == 'da':
        contract = Contract(id=request.POST.get('id'))
        user_curent=request.user
        modificare = Modificare(idContract=contract, idUser=user_curent, dataModificare=datetime.datetime.now(),tip='sterg')
        modificare.save()
        contract.delete()
        response_data={}
        response_data['id'] = contract.id
        response_data['msg']='STERS'
        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )

    if request.method == 'POST':


        contract_id = request.POST.get('id')
        contract_obligatii=request.POST.get('obligatii')
        contract_incepere = request.POST.get('data_incepere')
        contract_expirare = request.POST.get('data_expirare')
        contract_platii = request.POST.get('data_platii')
        contract_rap_inter = request.POST.get('data_rap_inter')
        contract_rap_act = request.POST.get('data_rap_act')
        contract_emitere_factura = request.POST.get('data_emitere_factura')
        contract_semnat = request.POST.get('semnat')
        contract_tip_copie = request.POST.get('tip_copie')
        contract_mod_trimitere = request.POST.get('mod_trimitere')
        contract_obligatii2=request.POST.get('obligatii2')
        contract_incepere2 = request.POST.get('data_incepere2')
        contract_expirare2 = request.POST.get('data_expirare2')
        contract_platii2 = request.POST.get('data_platii2')
        contract_rap_inter2 = request.POST.get('data_rap_inter2')
        contract_rap_act2 = request.POST.get('data_rap_act2')
        contract_emitere_factura2 = request.POST.get('data_emitere_factura2')
        contract_semnat2 = request.POST.get('semnat2')
        contract_tip_copie2 = request.POST.get('tip_copie2')
        contract_mod_trimitere2 = request.POST.get('mod_trimitere2')
        furnizor_id=request.POST.get('furnizor')
        furnizor=request.POST.get('nume_furnizor')
        contract_numefis=request.POST.get('numefis')
        contract_extensie=request.POST.get('extensie')
        contract_fis=request.POST.get('numefis2')
        contract_ext=request.POST.get('extensie2')


        user_curent=request.user

        response_data = {}

        if contract_fis is None:
          contract_fis=contract_numefis
          contract_ext=contract_extensie

        furnizor = Furnizor(id=furnizor_id,nume=furnizor)

        contract = Contract(id=contract_id,idFurnizor=furnizor,dataIncepere=contract_incepere2,dataExpirare=contract_expirare2,obligatii=contract_obligatii2,
                            dataPlata=contract_platii2,dataRapInter=contract_rap_inter2,dataRapAct=contract_rap_act2,dataEmitereFactura=contract_emitere_factura2,
                            tipCopie=contract_tip_copie2,semnat=contract_semnat2,modTrimitere=contract_mod_trimitere2,numefis=contract_fis,extensie=contract_ext)

        contract.save()

        modificare = Modificare(idContract=contract,idUser=user_curent,dataModificare=datetime.datetime.now(),dataIncepereBefore=contract_incepere,
                                dataIncepereAfter=contract_incepere2,dataExpirareBefore=contract_expirare,dataExpirareAfter=contract_expirare2,
                                obligatiiBefore=contract_obligatii,obligatiiAfter=contract_obligatii2,dataEmitereFacturaBefore=contract_emitere_factura,dataEmitereFacturaAfter=contract_emitere_factura2,
                                tipCopieBefore=contract_tip_copie,tipCopieAfter=contract_tip_copie2,modTrimitereBefore=contract_mod_trimitere,modTrimitereAfter=contract_mod_trimitere2,
                                semnatBefore=contract_semnat,semnatAfter=contract_semnat2,dataPlataBefore=contract_platii,dataPlataAfter=contract_platii2,dataRapActBefore=contract_rap_act,
                                dataRapActAfter=contract_rap_act2,dataRapInterBefore=contract_rap_inter,dataRapInterAfter=contract_rap_inter2,numefisBefore=contract_numefis,numefisAfter=contract_fis,
                                extensieBefore=contract_extensie,extensieAfter=contract_ext,tip='modif')

        modificare.save()

        response_data['id'] = contract.id
        response_data['numefis']=contract.numefis
        response_data['extensie']=contract.extensie
        response_data['incepere'] = contract.dataIncepere
        response_data['expirare'] = contract.dataExpirare
        response_data['obligatii'] = contract.obligatii
        response_data['emitere_factura'] = contract.dataEmitereFactura
        response_data['plata']=contract.dataPlata
        response_data['rap_act']=contract.dataRapAct
        response_data['rap_inter']=contract.dataRapInter
        response_data['semnat']=contract.semnat
        response_data['tip_copie']=contract.tipCopie
        response_data['mod_trimitere']=contract.modTrimitere

        json.dumps(response_data)

        return HttpResponse(
          json.dumps(response_data),
          content_type="application/json"
         )

    return render(request, 'AppInterno/home.html', contexthome)
Exemplo n.º 55
0
def main(request):
    #return render(request,'secondweb/new.html',{"name":"vedha krishna"})
    return HttpResponse(cd)
Exemplo n.º 56
0
 def __call__(self, extension='png'):
     if self.tile_bytes:
         return HttpResponse(self.tile_bytes, mimetype=('image/%s' % extension))
     else:
         raise Http404
Exemplo n.º 57
0
def listado(request):
    lista = serializers.serialize('json', Mascota.objects.all())
    return HttpResponse(lista, content_type='application/json')
Exemplo n.º 58
0
def home(request):
    return HttpResponse('hello world')
Exemplo n.º 59
0
 def test_etag(self):
     req = HttpRequest()
     res = HttpResponse('content')
     self.assertTrue(
         CommonMiddleware().process_response(req, res).has_header('ETag'))
 def wrapper_func(request,*args,**kwargs):
     if request.user.is_superuser:
         print("yes")
         return view_func(request,*args,**kwargs)
     else:
         return HttpResponse("<h1>You are not allowed to access this page</h1>")