Example #1
0
def cancel_request(request, request_id):
    if request.method == 'DELETE':
        req = request.user.request_set.get(id=request_id)

        if req.status == Request.OPEN:
            req.delete()

            return JsonResponse({
                'status': 'success',
                'message': req.subject
            })

        else:
            response = JsonResponse({
                'status': 'error',
                'message': 'Cannot cancel once a bidder has been accepted.',
            })
            response.status_code = 404
            return response

    response = JsonResponse({
        'status': 'error',
        'message': 'Invalid request method.',
    })
    response.status_code = 404
    return response
Example #2
0
def info(request):

    # step 1 - get the hex
    hex_p = subprocess.Popen(['multichain-cli', 'food2', 'getinfo'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)

    out, err = hex_p.communicate()
    big_string = ''.join(out.split('\n\n')[1]).strip()
    resp = json.loads(big_string)


    # step 3 - index into json to get either prev txid or coinbase
    # new_txid = resp['vin'][0]['txid']
    # sender_address = resp['vout'][1]['scriptPubKey']['addresses'][0]
    # print "Prev txid is ", new_txid
    # print "Sender address is ", sender_address
    # prev_owner = User.objects.get(address=sender_address).name
    # print "sender name is ", prev_owner

    # step 4 - look for coinbase

    response = JsonResponse(resp)
    response.__setitem__("Access-Control-Allow-Origin", "*")

    return response
def send_token(request):
    if request.method == 'POST':
        urn_tel = request.POST.get('phone')
        email_address = request.POST.get('text')
        session_ureporter = Ureporter.objects.get(urn_tel=urn_tel)
        existing_ureporter = Ureporter.objects.filter(user__email=email_address).first()
        if existing_ureporter:
            tasks.delete_user_from_rapidpro(existing_ureporter)
            existing_ureporter.uuid = session_ureporter.uuid
            existing_ureporter.urn_tel = session_ureporter.urn_tel
            existing_ureporter.user.username = session_ureporter.user.username
            session_ureporter.delete()
            existing_ureporter.save()
            if not existing_ureporter.token:
                data = {'send_token': 'exists'}
            else:
                data = {'send_token': 'send'}
                tasks.send_verification_token.delay(existing_ureporter)
        else:
            session_ureporter.user.email = email_address
            session_ureporter.save()
            data = {'send_token': 'send'}
            tasks.send_verification_token.delay(session_ureporter)

        response = JsonResponse(data)
        response.status_codecode = 200
        return response
Example #4
0
def write_review(req, request_id):
    if req.method == 'POST':
        try:
            data = json.loads(req.body)
        except ValueError:
            data = req.POST

        request = Request.objects.get(id=request_id)

        worker_id = request.proposal_set.get(status=Request.ACCEPTED).worker_id

        request.status = Request.CLOSED
        request.save()

        user = req.user
        worker = Worker.objects.get(id=worker_id)
        rating = data['rating']
        type = Review.CUSTOMER_WORKER
        message = data['message']

        review = Review(user=user, worker=worker, rating=rating, type=type, message=message)

        review.save()
        return JsonResponse({
            'status': 'success',
            'message': review.user.username
        })

    response = JsonResponse({
        'status': 'error',
        'message': 'Invalid request method'
    })
    response.status_code = 405

    return response
Example #5
0
    def post(self, request, *args, **kwargs):
        data = {}
        post_data = json.loads(request.body) if request.body else {}
        form = AuthenticationForm(request, post_data)
        if form.is_valid():
            user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
        else:
            user = None

        status_code = 401
        if user is not None:
            if user.is_active:
                login(request, user)
                status_code = 200
                # Redirect to a success page.
            else:
                data['message'] = 'Disabled Account'
                # Return a 'disabled account' error message
                status_code = 401
        else:
            data['message'] = 'Invalid Credentials'
            # Return an 'invalid login' error message.
            status_code = 401

        response = JsonResponse(data)
        response.status_code = status_code
        return response
Example #6
0
    def post(self, request):
        """"""
        # 获取参数
        sku_id = request.POST.get("sku_id")

        # 参数校验
        if not sku_id:
            return JsonResponse({"code": 1, "message": "参数缺失"})

        # 业务处理, 删除购物车数据
        if not request.user.is_authenticated():
            # 用户未登录,操作cookie
            cart_json = request.COOKIES.get("cart")
            if cart_json is not None:
                cart = json.loads(cart_json)
                # 判断cart字典中是否存在sku_id键
                if sku_id in cart:
                    # 删除cookie中cart字典的商品记录
                    del cart[sku_id]
                response = JsonResponse({"code": 0, "message": "删除成功"})
                response.set_cookie("cart", json.dumps(cart))
                return response
            else:
                return JsonResponse({"code": 0, "message": "删除成功"})
        else:
            # 用户已登录,操作redis
            redis_conn = get_redis_connection("default")
            user_id = request.user.id
            # 删除redis中的sku_id字段的记录
            redis_conn.hdel("cart_%s" % user_id, sku_id)
            return JsonResponse({"code": 0, "message": "删除成功"})
Example #7
0
def login(request):
    form = LoginForm(request.POST)

    message = {}

    if request.method == 'POST':
        if form.is_valid():
            # Autentica o usuário
            usuario = authenticate(username=form.cleaned_data.get('username'),
                                   password=form.cleaned_data.get('password'))

            # Verifica se o usuário existe
            if usuario is not None:
                # Verifica se o usuário está ativo
                if usuario.is_active:
                    login_(request, usuario)
                    message = {'message': 'Login realizado com sucesso !', 'level': 'success'}
                else:
                    message = {'message': u'Seu usuário foi desativo !', 'level': 'danger'}
            else:
                message = {'message': u'Seu usuário ou senha estão incorretos !', 'level': 'danger'}
        else:
            response = JsonResponse(form.errors)
            response.status_code = 500
            return response

        return JsonResponse(message)
Example #8
0
def json_from_email(request):
    email = request.GET.get("email")
    
    #Check for an entry point with the given e-mail (or lack thereof), setting
    #entry_point to none if it wasn't found
    if email:
        domain = email.split("@")[-1]
        try:
            entry_point = EntryPoint.objects.get(domain=domain)
        except EntryPoint.DoesNotExist:
            entry_point = None
    else:
        entry_point = None
    
    #Try to get the default entry point if we don't have one already from the e-mail
    if not entry_point:
        try:
            entry_point = EntryPoint.objects.get(domain="")
        except EntryPoint.DoesNotExist:
            #Do nothing, entry_point is already None
            pass
    
    if entry_point:
        page = entry_point.page
        data = _json_for_page(request, page)
        
        response = JsonResponse(data)
        response["Access-Control-Allow-Origin"] = "*"
        return response
    
    #After all that, we still couldn't figure out what to serve.
    response = JsonResponse({})
    response.status_code = 404
    response["Access-Control-Allow-Origin"] = "*"
    return response
Example #9
0
def get_matches_by_player(player):

    user = User.objects.get(username=player)
    wins = Match.objects.filter(winner=user)
    losses = Match.objects.filter(loser=user)

    rating_history = dict()
    for win in wins:
        rating_history[win.match_date] = win.winner_after_elo
    for loss in losses:
        rating_history[loss.match_date] = loss.loser_after_elo

    sorted_rating_history = collections.OrderedDict()
    for k in sorted(rating_history.keys()):
        sorted_rating_history[k] = rating_history[k]

    #javascript wants a zero based month, what the hell?
    resp = [{'x': 'new Date(' + ','.join(str(a) for a in [date.year, date.month - 1, date.day, date.hour, date.minute, date.second]) + ')', 'y': elo} for date, elo in sorted_rating_history.items()]
    resp = JsonResponse(
        resp,
        safe=False
    )
    #Unfortunate formatting adjustments to give canvasjs what it wants
    resp = str(resp.content.decode('utf-8')).replace("\"", '')
    resp = resp.replace("Content-Type: application/json", "")
    return resp
Example #10
0
def index(request):
    response = JsonResponse({'foo':'bar'})
    # Get the number of visits to the site.
    # We use the COOKIES.get() function to obtain the visits cookie.
    # If the cookie exists, the value returned is casted to an integer.
    # If the cookie doesn't exist, we default to zero and cast that.
    visits = request.session.get('visits')

    reset_last_visit_time = False
 
    # Does the cookie last_visit exist?
    if 'last_visit' in request.COOKIES:
        # Yes it does! Get the cookie's value.
        last_visit = request.COOKIES['last_visit']
        # Cast the value to a Python date/time object.
        last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")

        # If it's been more than a day since the last visit...
        #if (datetime.now() - last_visit_time).days > 0:
        visits = visits + 1
            # ...and flag that the cookie last visit needs to be updated
        reset_last_visit_time = True
    else:
        print('nenhuma visita anterior')
        # Cookie last_visit doesn't exist, so flag that it should be set.
        reset_last_visit_time = True

    if reset_last_visit_time:
        response.set_cookie('last_visit', datetime.now())
        response.set_cookie('visits', visits)

    # Return response back to the user, updating any cookies that need changed.
    return response
Example #11
0
def edit(request):
    if request.POST.get('id'):
        company = Company.objects.get(id=request.POST.get('id'))
    else:
        company = None
    cf = CompanyForm(request.POST, request.FILES, instance=company)
    if not cf.is_valid():
        response = JsonResponse(cf.errors)
        response.status_code = 500
        return response
    company = cf.save()
    errors = dict()
    if request.POST.get('positions'):
        positions = literal_eval(request.POST.get('positions'))
        for position in positions:
            position['company'] = company.id
            if position.get('id'):
                position_obj = Position.objects.get(id=position['id'])
            else:
                position_obj = None
            pf = PositionForm(position, instance=position_obj)
            if not pf.is_valid():
                if position.get('name'):
                    errors[position['name']] = pf.errors
                else:
                    errors['Unknown'] = pf.errors
            else:
                if pf.instance.ongoing is None:
                    pf.instance.ongoing = pf.fields['ongoing'].initial
                pf.save()
    if len(errors) > 0:
        response = JsonResponse({'company': serializer(company=company), 'errors': errors})
        response.status_code = 500
        return response
    return JsonResponse({'company': serializer(company=company)})
Example #12
0
def status(request):  # pylint: disable=unused-argument
    """Status"""
    token = request.GET.get("token", "")
    if not token or token != settings.STATUS_TOKEN:
        raise Http404()

    info = {}
    check_mapping = {
        'REDIS': (get_redis_info, 'redis'),
        'ELASTIC_SEARCH': (get_elasticsearch_info, 'elasticsearch'),
        'POSTGRES': (get_pg_info, 'postgresql'),
        'CELERY': (get_celery_info, 'celery'),
    }

    for setting, (check_fn, key) in check_mapping.items():
        if setting in settings.HEALTH_CHECK:
            log.debug('getting: %s', key)
            info[key] = check_fn()
            log.debug('%s done', key)

    code = HTTP_OK
    status_all = UP
    for key in info:
        if info[key]["status"] == DOWN:
            code = SERVICE_UNAVAILABLE
            status_all = DOWN
            break

    info["status_all"] = status_all

    resp = JsonResponse(info)
    resp.status_code = code
    return resp
Example #13
0
    def dispatch(self, request: HttpRequest, *args, **kwargs):
        self.request = request
        try:
            result = super().dispatch(request, *args, **kwargs)
            if isinstance(result, HttpResponse):
                return result
            http_code = self.http_code
            api_result = dict(
                data=result,
            )
        except rmr.Error as error:

            response_logger.log(
                error.level,
                '%(code)s: %(message)s',
                dict(message=error.message, code=error.code),
            )

            http_code = error.http_code
            api_result = dict(
                error=dict(
                    code=error.code,
                    description=error.message,
                ),
            )

        response = JsonResponse(api_result, status=http_code, safe=False)
        response.setdefault('Content-Length', len(response.content))
        return response
Example #14
0
    def get(self, request):

        response = JsonResponse({"status":"success",
                                 "msg":""
                                 })
        response.delete_cookie("token")
        response.delete_cookie("logined")
        return  response
Example #15
0
def default(request):
    """
    in case the url doesn't match the existing
    """
    msg = {'message': 'Resource Not found'}
    re = JsonResponse(msg)
    re.status_code = 404
    return re
Example #16
0
 def post(self, request, *args, **kwargs):
     """Override post to first check if any users exist already."""
     if User.objects.count() > 0:
         response = JsonResponse({'status': 'denied'})
         response.status_code = 403
         return response
     else:
         return super().post(request, *args, **kwargs)
Example #17
0
def render_json_response(status_code, view_object_name, view_object, msg, url):
    r = JsonResponse({
        view_object_name: view_object,
        'msg': msg,
        'url': url
    })
    r.status_code = status_code
    return r
Example #18
0
def device_request(request):
	from django.http import JsonResponse

	data = {}
	error_code = 0

	if request.POST.get('uuid') and request.POST.get('address') and request.POST.get('action'):
		device_uuid = request.POST['uuid']
		resource_address = request.POST['address']
		action = request.POST['action']

		if action == 'read' or action == 'write':
			if Resource.objects.filter(device__uuid=device_uuid).filter(address=resource_address).count() != 0:
				from django.conf import settings
				from pika.exceptions import ConnectionClosed

				try:
					if action == 'read':
						DeviceRequest(settings.AMQP_HOST, device_uuid).read(resource_address)

						data['status'] = 'success'
						data['message'] = 'read request sent'
					else:
						if request.POST.get('value'):
							resource_value = request.POST['value']

							DeviceRequest(settings.AMQP_HOST, device_uuid).write(resource_address, resource_value)

							data['status'] = 'success'
							data['message'] = 'write request sent'
						else:
							data['status'] = 'error'
							data['message'] = 'write action requested without value'
							error_code = 400
				except ConnectionClosed:
					data['status'] = 'error'
					data['message'] = 'Unable to connect to the AMQP server'
					error_code = 500
			else:
				data['status'] = 'error'
				data['message'] = 'unknown device or resource'
				error_code = 400
		else:
			data['status'] = 'error'
			data['message'] = 'unknown action'
			error_code = 400
	else:
		data['status'] = 'error'
		data['message'] = 'bad request'
		error_code = 400

	if error_code != 0:
		response = JsonResponse(data)
		response.status_code = error_code
		return response
	else:
		return JsonResponse(data)
Example #19
0
    def post(request):
        """Identifies a time series group by the name of an AssetSensor.

        If the AssetSensor does not yet exist, creates it.

        Args:
            recipe_instance: (Optional) POST argument with the
                recipe_instance pk. Used to retrieve the Brewhouse equipment
                associated with the request. Used for some cases when the
                equipment has more readily available access to the
                recipe_instance rather than the Brewhouse directly.
            brewhouse: (Optional): POST argument with the Brewhouse pk. Required
                if recipe_instance is not submitted.
            name: Name for the AssetSensor to be used in the time series data.
                See AssetSensor for more information on naming.
            variable_type: Type of AssetSensor to be used (e.g. "value" or
                "override"). Defaults to 'value'.

        Returns:
            JsonResponse with the pk to the sensor as the property "sensor".
            Response status is 200 if just returning object and 201 if needed to
            create a new AssetSensor.
        """
        name = request.data['name']
        variable_type = request.data.get('variable_type', 'value')

        if 'recipe_instance' in request.data:
            recipe_instance_id = request.data['recipe_instance']
            recipe_instance = models.RecipeInstance.objects.get(
                id=recipe_instance_id)
            brewhouse = recipe_instance.brewhouse
        else:
            brewhouse_id = request.data['brewhouse']
            brewhouse = models.Brewhouse.objects.get(id=brewhouse_id)

        if not permissions.is_member_of_brewing_company(
                request.user, brewhouse.brewery.company):
            return HttpResponseForbidden(
                'Access not permitted to brewing equipment.')

        # See if we can get an existing AssetSensor.
        try:
            sensor = models.AssetSensor.objects.get(name=name,
                                                    brewhouse=brewhouse,
                                                    variable_type=variable_type)
            status_code = status.HTTP_200_OK
        # Otherwise create one for recording data
        except ObjectDoesNotExist:
            LOGGER.debug('Creating new asset sensor %s for asset %s',
                         name, brewhouse)
            sensor = models.AssetSensor.objects.create(
                name=name, brewhouse=brewhouse, variable_type=variable_type)
            status_code = status.HTTP_201_CREATED

        response = JsonResponse({'sensor': sensor.pk})
        response.status_code = status_code
        return response
Example #20
0
def group_reject_request(request,group,player):
    group = get_object_or_404(Group, pk=group)
    player = get_object_or_404(Player, pk=player)
    request.user.player.reject_request_group(group,player)
    response = JsonResponse({
        "message" : "%s rejected into group %s" % (player,group.name)
    })
    response.status_code = 200
    return response
Example #21
0
def upload_img(request):
    form = ImageUploadForm(request.POST, request.FILES)
    if form.is_valid():
        result = form.save()
        return JsonResponse({'status': 'successful', 'url': result.img.url})

    response = JsonResponse({'error': form.errors})
    response.status_code = 400
    return response
Example #22
0
    def post(self, request, *args, **kwargs):
        w = self.get_window()

        ids = [(i[len('number_'):], request.POST[i]) for i in request.POST if i.startswith('number_')]
        seats = [(i[len('seats_'):], request.POST[i].split(',')) for i in request.POST if i.startswith('seats_')]
        print_format = request.POST.get('print-format', self.DEFAULT_PF)
        discount = request.POST.get('discount', '')
        if discount:
            discount = Discount.objects.get(id=discount)

        data = request.POST.copy()
        data['email'] = settings.FROM_EMAIL

        form = MPRegisterForm(data,
                              event=w.event, ids=ids, seats=seats,
                              client=request.session.get('client', ''))

        keys = list(form.fields.keys())
        for k in keys:
            # email is required
            if k == 'email':
                continue
            # removing not required fields
            form.fields.pop(k)

        if form.is_valid():
            mp = form.save(commit=False)
            if discount:
                mp.discount = discount
                mp.price = mp.get_window_price()
            mp.confirm()
            for tk in mp.tickets.all():
                tk.sold_in_window = True
                tk.price = tk.get_window_price()
                tk.save()

            price = float(data.get('price', 0))
            payed = data.get('payed', 0)
            if payed:
                payed = float(payed)
            else:
                payed = 0

            change = float(data.get('change', 0))
            payment = data.get('payment', 'cash')
            sale = TicketWindowSale(purchase=mp, window=w, user=request.user,
                                    price=price, payed=payed,
                                    change=change, payment=payment)
            sale.save()
            url = reverse('window_ticket', kwargs={'ev': mp.ev.slug, 'w': w.slug, 'pf': print_format, 'order': mp.order})
            data = {'url': url, 'mp': mp.order_tpv, 'wc': mp.window_code(), 'nt': mp.tickets.count()}
            return JsonResponse(data)
        data = {"message": _("There was an error, please try again"), "status": "ok"}
        resp = JsonResponse(data)
        resp.status_code = 400
        return resp
Example #23
0
def cookie_test(request):
    # o = request.COOKIES['login_cookie']
    # decrypted = crypto.decrypt(o,crypto.PRIVATE_KEY)
    print request.COOKIES

    print request.method
    decrypted = "helloWorld"
    resp = JsonResponse({})
    resp.set_cookie("tempcokie","fdgfdgfdg",httponly=True,secure=True,max_age=30);
    return resp
Example #24
0
def report_build(request):
    try:
        payload = json.loads(str(request.body, encoding='utf-8'))
        build = Build.objects.get(pk=payload['id'])
        build.handle_worker_report(payload)
        response = JsonResponse({'message': 'Thanks for building it'})
    except Build.DoesNotExist:
        response = JsonResponse({'error': 'Build not found'})
        response.status_code = 404
    return response
Example #25
0
 def dispatch(self, request, *args, **kwargs):
     try:
         response = super(JsonView, self).dispatch(request, *args, **kwargs)
         if not isinstance(response, JsonResponse):
             response = JsonResponse(response, encoder=ModelJSONEncoder, safe=False)
     except ObjectDoesNotExist:
         logger.warning('Not Found: %s', request.path,
             extra={'status_code': 404, 'request': request})
         response = JsonResponse({'error': 'Not Found'})
         response.status_code = 404
     except PermissionDenied:
         logger.warning('Forbidden (Permission denied): %s', request.path,
             extra={'status_code': 403, 'request': request})
         response = JsonResponse({'error': 'Forbidden'})
         response.status_code = 403
     except SuspiciousOperation as e:
         logger.error(force_text(e),
             extra={'status_code': 400, 'request': request})
         response = JsonResponse({'error': 'Bad Request'})
         response.status_code = 400
     except SystemExit:
         # Allow sys.exit()
         raise
     except:
         logger.exception('Failed to handle request: %s', request.path,
             extra={'status_code': 500, 'request': request})
         response = JsonResponse({'error': 'Internal Server Error'})
         response.status_code = 500
     return response
Example #26
0
 def get(self, request, *args, **kwargs):
     try:
         threatsList = loadMetaFiles()
         threatsList["dir_path"] = metaDirectory
         resp = JsonResponse(threatsList)
         resp.status_code = 200
         return resp
     except IOError:
         return HttpResponseNotFound("Cannot find directory " + metaDirectory)
     except Exception as e:
         return HttpResponseServerError(e.message)
Example #27
0
 def process_exception(self, request, exception):
     if type(exception) == AuthAlreadyAssociated:
         # this can happen when a user is already logged in via one backend (e.g. facebook)
         # and then tries to sign in via another one (e.g. google)
         # clients should check the session before trying to log in, but if they don't
         # provide a more meaningful error message
         response = JsonResponse({'error': unicode(_(
             'You are already logged in via another OAuth provider. '
             'Sign out first if you want to log in with another account.'))})
         response.status_code = 400
         return response
Example #28
0
def api_details(request, rt_id):
    try:
        m = Movie.objects.get(rt_id=rt_id)
    except ObjectDoesNotExist:
        r = JsonResponse({
            'error': "Movie with id '{}' was not found.".format(rt_id)
        })
        r.status_code = 404
        return r

    return JsonResponse(_details(m))
Example #29
0
def authorize(r):
    username, password = r.POST['username'], r.POST['password']
    user = authenticate(username=username, password=password)
    if user is None:
        print('invalid username/password: {} and {}'.format(username, password))
        return JsonResponse({'status': 'invalid'}, status=403)
    resp = JsonResponse({'status': 'valid'})
    auth = ClientAuthorization.objects.create(user=user)
    resp.set_cookie('user_id', user.pk)
    resp.set_cookie('token', auth.token)
    return resp
Example #30
0
def save_photo(request):
    '''
    Takes a JSON-formatted search result from the Flickr Search API, fetches the
    photo in multiple sizes from the Flickr API and saves them.
    '''
    if not request.user.is_authenticated():
        rsp = JsonResponse({'error': 'Login required'})
        rsp.status_code = 401
        return rsp
    search_result = request.POST
    download_photo(request.user, search_result)
    return JsonResponse({'saved': True})
Example #31
0
def total_chart_area(request):
    data, date_distance, checks = [], -1, 12
    accounts = Account.objects.filter(user=request.user)
    profile_currency = Profile.objects.get(user=request.user).currency
    object = Income if request.get_full_path(
    ) == '/users/dashboard/incomes-chart-area/' else Spending
    first_object = object.objects.filter(user=request.user).first()
    last_object = object.objects.filter(user=request.user).last()
    if first_object and last_object:
        date_distance = (last_object.created_date -
                         first_object.created_date).days
    if 1 <= date_distance <= 365:
        year, month = first_object.created_date.year, first_object.created_date.month
        while checks:
            date = datetime(year, month, 1)
            if month == 12:
                objects = total_currency_converter(request.user, object,
                                                   accounts, profile_currency,
                                                   year, month)
                data.append({date.strftime('%b'): objects})
                month = 1
                year += 1
            else:
                objects = total_currency_converter(request.user, object,
                                                   accounts, profile_currency,
                                                   year, month)
                data.append({date.strftime('%b'): objects})
                month += 1
            checks -= 1
    elif date_distance > 0:
        year, month = last_object.created_date.year - 1, last_object.created_date.month + 1
        while checks:
            date = datetime(year, month, 1)
            if month == 12:
                objects = total_currency_converter(request.user, object,
                                                   accounts, profile_currency,
                                                   year, month)
                data.append({date.strftime('%b'): objects})
                month = 1
                year += 1
            else:
                objects = total_currency_converter(request.user, object,
                                                   accounts, profile_currency,
                                                   year, month)
                data.append({date.strftime('%b'): objects})
                month += 1
            checks -= 1
    elif date_distance == 0:
        year, month = first_object.created_date.year, first_object.created_date.month
        while checks:
            date = datetime(year, month, 1)
            if month == 12:
                objects = total_currency_converter(request.user, object,
                                                   accounts, profile_currency,
                                                   year, month)
                data.append({date.strftime('%b'): objects})
                month = 1
                year += 1
            else:
                objects = total_currency_converter(request.user, object,
                                                   accounts, profile_currency,
                                                   year, month)
                data.append({date.strftime('%b'): objects})
                month += 1
            checks -= 1
    return JsonResponse(data, safe=False)
Example #32
0
def register_exist(request):
    uname = request.GET.get('uname')
    count = UserInfo.object.filter(uname=uname).count()
    return JsonResponse ({'conut':count})
Example #33
0
 def response(data={}, message='', status=200):
     result = {
         'data': data,
         'message': message,
     }
     return JsonResponse(result, status=status)
Example #34
0
def article_view_all(request):
    articles = Article.objects.all()
    data = list(articles.values())
    return JsonResponse(data,
                        safe=False,
                        json_dumps_params={'ensure_ascii': False})
Example #35
0
def JsonResponseMessage(status=500, message=None, status_message='error'):
    response = {'status': status_message}
    if message is not None:
        response['message'] = message
    return JsonResponse(response, status=status)
Example #36
0
def vacancies_top(request, top_number):
    vacancies = Vacancy.objects.all()
    vacancies = vacancies.order_by('salary').reverse()[:top_number]
    vacancies_json = [vacancy.to_json() for vacancy in vacancies]
    return JsonResponse(vacancies_json, safe=False)
Example #37
0
 def render_json_response(context):
     return JsonResponse(context)
Example #38
0
def vacancies_list(request):
    vacancies = Vacancy.objects.all()
    vacancies_json = [vacancy.to_json() for vacancy in vacancies]
    return JsonResponse(vacancies_json, safe=False)
Example #39
0
def vacancy_detail(request, vacancy_id):
    try:
        vacancy = Vacancy.objects.get(id=vacancy_id)
    except Vacancy.DoesNotExist as e:
        return JsonResponse({'error': str(e)})
    return JsonResponse(vacancy.to_json())
Example #40
0
def company_detail(request, company_id):
    try:
        company = Company.objects.get(id=company_id)
    except Company.DoesNotExist as e:
        return JsonResponse({'error': str(e)})
    return JsonResponse(company.to_json())
Example #41
0
def hello3(request):
    jsonresult = {
        'result': 'success',
        'data': ['hello', 1, 2, True, ('a', 'b', 'c')]
    }
    return JsonResponse(jsonresult)
Example #42
0
def requestDownload(request):
    if request.is_ajax():
        if request.method == 'POST':
            json_data = json.loads(request.body)
            try:
                downRequest = downman_models.DownloadRequest()
                """
                # if any of the resoures requires authorization:
                usage = json_data.get('downloadAuthorizationUsage', '')
                if not usage:
                    # return an error
                    pass
                """
                if request.user and not request.user.is_anonymous():
                    downRequest.requested_by_user = request.user.username
                else:
                    downRequest.requested_by_external = json_data.get(
                        'email', '')
                    if not downRequest.requested_by_external:
                        pass
                downRequest.language = get_language()
                downRequest.validity = downman_models.get_default_validity()
                downRequest.request_random_id = date.today().strftime(
                    "%Y%m%d") + get_random_string(length=32)
                downRequest.json_request = request.body.decode("UTF-8")
                tracking_url = reverse('download-request-tracking',
                                       args=(downRequest.request_random_id, ))
                resources = json_data.get('resources', [])
                if downman_models.get_shopping_cart_max_items() > 0 and len(
                        resources
                ) > downman_models.get_shopping_cart_max_items():
                    return JsonResponse({
                        "status": "error",
                        'error_message': "Invalid request"
                    })

                if len(resources) == 0 and json_data.get('request_desc'):
                    downRequest.pending_authorization = True
                    downRequest.generic_request = True
                    shared_view_state = json_data.get('shared_view_state')
                    shv_pid = shared_view_state.get('pid')
                    shv_state = shared_view_state.get('view_state')
                    shv_description = shared_view_state.get('description', '')
                    shv_expiration = date(9999, 12, 31)
                    shv = gvsigol_core.views.do_save_shared_view(
                        shv_pid, shv_description, shv_state, shv_expiration,
                        request.user, True)
                    downRequest.shared_view_url = shv.url
                downRequest.save()
                for resource in json_data.get('resources', []):
                    createResourceLocator(resource, downRequest)
            except:
                logger.exception('error creating DownloadRequest')
                raise

            try:
                #processDownloadRequest(downRequest.id)
                # this requires the Celery worker to be started, see README
                processDownloadRequest.apply_async(
                    args=[downRequest.id],
                    queue='resolvreq')  #@UndefinedVariable
                notifyReceivedRequest.apply_async(
                    args=[downRequest.id], queue='notify')  #@UndefinedVariable
            except:
                logger.exception("error queuing task")
                downRequest.request_status = downman_models.DownloadRequest.QUEUEING_ERROR
                downRequest.save()

            return JsonResponse({
                "status_code": downRequest.request_status,
                "status": downRequest.status_desc,
                'download_id': downRequest.request_random_id,
                'tracking_url': tracking_url
            })
    # TODO: error handling
    return JsonResponse({"status": "error"})
Example #43
0
def chart_area(request, pk):
    data, date_distance, checks = [], -1, 12
    account = Account.objects.get(id=pk) if pk else None
    object = Income if '/users/dashboard/incomes-chart-area/' in request.get_full_path(
    ) else Spending
    first_object = object.objects.filter(
        user=request.user,
        account=account).first() if account else object.objects.filter(
            user=request.user).first()
    last_object = object.objects.filter(
        user=request.user,
        account=account).last() if account else object.objects.filter(
            user=request.user).last()
    if first_object and last_object:
        date_distance = (last_object.created_date -
                         first_object.created_date).days
    if 1 <= date_distance <= 365:
        year, month = first_object.created_date.year, first_object.created_date.month
        while checks:
            date = datetime(year, month, 1)
            if month == 12:
                objects = object.objects.filter(user=request.user,
                                                account=account,
                                                created_date__year=year,
                                                created_date__month=month)
                data.append({date.strftime('%b'): assembly(objects)})
                month = 1
                year += 1
            else:
                objects = object.objects.filter(user=request.user,
                                                account=account,
                                                created_date__year=year,
                                                created_date__month=month)
                data.append({date.strftime('%b'): assembly(objects)})
                month += 1
            checks -= 1
    elif date_distance > 0:
        year, month = last_object.created_date.year - 1, last_object.created_date.month + 1
        while checks:
            date = datetime(year, month, 1)
            if month == 12:
                objects = object.objects.filter(user=request.user,
                                                account=account,
                                                created_date__year=year,
                                                created_date__month=month)
                data.append({date.strftime('%b'): assembly(objects)})
                month = 1
                year += 1
            else:
                objects = object.objects.filter(user=request.user,
                                                account=account,
                                                created_date__year=year,
                                                created_date__month=month)
                data.append({date.strftime('%b'): assembly(objects)})
                month += 1
            checks -= 1
    elif date_distance == 0:
        year, month = first_object.created_date.year, first_object.created_date.month
        while checks:
            date = datetime(year, month, 1)
            if month == 12:
                objects = object.objects.filter(user=request.user,
                                                account=account,
                                                created_date__year=year,
                                                created_date__month=month)
                data.append({date.strftime('%b'): assembly(objects)})
                month = 1
                year += 1
            else:
                objects = object.objects.filter(user=request.user,
                                                account=account,
                                                created_date__year=year,
                                                created_date__month=month)
                data.append({date.strftime('%b'): assembly(objects)})
                month += 1
            checks -= 1
    return JsonResponse(data, safe=False)
Example #44
0
def status(request):
    return JsonResponse({'status':'OK'})
Example #45
0
 def get_queryset(self):
     if self.request.is_ajax():
         return JsonResponse(list(Doctor.objects.all().values('id_number', 'name', 'surname', 'clinic__doctor__name')), safe=False)
     return None
Example #46
0
def modal_cookie(request):
    username = request.GET.get('username', None)
    return JsonResponse(username)
Example #47
0
 def wrapper(request, *args, **kwargs):
     if not request.session['issuperuser']:
         return JsonResponse({"code": 403, "err": "无权限"})
     return func(request, *args, **kwargs)
Example #48
0
def GetProfilePicture(data):
    username = data.GET.get('username')
    profilePic = User.objects.filter(username=username).first()
    profilePic = profilePic.profile.profile_picture.url
    print("sadfsdfsafasdfasdfasdfasdfasdfsd\n\n\n")
    return JsonResponse({"profile_picture": profilePic})
Example #49
0
def getRooms(request):
    if request.method == 'GET':
        return JsonResponse({'rooms':roomMapper.getRooms()})
    else:
        return JsonResponse({'getRoomsError': 'Resource only accepts GET requests'}, status=405)
Example #50
0
def routes(request):
    if request.method == "GET":
        routes = Route.objects.all()
        serializer = RouteSerializer(routes, many=True)
        return JsonResponse(serializer.data, safe=False)
Example #51
0
def article_view(request, pk):
    article = Article.objects.filter(pk=pk)
    data = list(article.values())
    return JsonResponse(data,
                        safe=False,
                        json_dumps_params={'ensure_ascii': False})
Example #52
0
def save_case(request):
    '''保存&更新case'''
    if request.method == "POST":
        case_id = request.POST.get('cid', "")
        url = request.POST.get('url', "")
        method = request.POST.get('method', "")
        per_type = request.POST.get('per_type', "")
        header = request.POST.get('header', "")
        per_value = request.POST.get('per_value', "")
        result_text = request.POST.get('result_text', "")
        assert_text = request.POST.get('assert_text', "")
        assert_type = request.POST.get('assert_type', "")
        module_id = request.POST.get('module_id', "")
        case_name = request.POST.get('case_name', "")
        if method == "get":
            method_int = 1
        elif method == "post":
            method_int = 2
        else:
            return JsonResponse({"code": 10101, "message": "请求方法错误"})

        if per_type == "form":
            per_type_int = 1
        elif per_type == "json":
            per_type_int = 2
        else:
            return JsonResponse({"code": 10102, "message": "参数类型错误"})

        if assert_type == "include":
            assert_type_int = 1
        elif assert_type == "equal":
            assert_type_int = 2
        else:
            return JsonResponse({"code": 10103, "message": "断言类型错误"})
        if case_id == "":
            TestCase.objects.create(module_id=module_id,
                                    name=case_name,
                                    url=url,
                                    method=method_int,
                                    header=header,
                                    parameter_type=per_type_int,
                                    parameter_body=per_value,
                                    result=result_text,
                                    assert_type=assert_type_int,
                                    assert_text=assert_text,
                                    )
            return JsonResponse({"code": 10200, "message": "create success"})
        else:
            case = TestCase.objects.get(id=case_id)
            case.module_id = module_id
            case.name = case_name
            case.url = url
            case.method = method_int
            case.case.header = header
            case.parameter_type = per_type_int
            case.parameter_body = per_value
            case.result = result_text
            case.assert_type = assert_type_int
            case.assert_text = assert_text
            case.save()
            return JsonResponse({"code": 10200, "message": "save success"})
Example #53
0
def goods_del(request,id):
    if request.method == 'POST':
        # ajax删除商品 JsonResponse
        Goods.objects.filter(pk=id).delete()
        return JsonResponse({'code':200,'msg':'请求成功'})
Example #54
0
def get_conf(request):
    response = {
        "shopping_cart_max_items":
        downman_models.get_shopping_cart_max_items()
    }
    return JsonResponse(response)
Example #55
0
def compiHistoryView(request):
    
    return JsonResponse({'Access_Token':'Hello'})
Example #56
0
def view_endorsement_payload(request, endorsement_id):
    e = get_object_or_404(Endorsement, id=endorsement_id)
    return JsonResponse(e.payload())
Example #57
0
def friendShowDetails(request, format=None):
    details = UserDetails.objects.get(
        userId__username=request.GET.get('username'))
    username = request.GET.get('username')
    full_name = User.objects.get(username=request.GET.get(
        'username')).first_name + " " + User.objects.get(
            username=request.GET.get('username')).last_name
    img_url = details.profilePhoto.url
    occupation = details.occupation
    total_friends = UserFriends.objects.get(userId=UserDetails.objects.get(
        userId__username=request.GET.get('username'))).friends.all().count()
    curr_lat = details.current_lat
    curr_long = details.current_long
    formedAt = ""
    isFriend = False
    if (FriendsFormedDetails.objects.filter(
            Q(user__userId__username=request.GET.get('username'))
            | Q(friend_name__userId__username=request.GET.get('username'))).
            count() > 0):
        obj = FriendsFormedDetails.objects.get(
            Q(user__userId__username=request.GET.get('username'),
              friend_name__userId__username=request.user.username)
            | Q(friend_name__userId__username=request.GET.get('username'),
                user__userId__username=request.user.username))
        formedAt = obj.formedAt
        isFriend = obj.friend_or_Request
    total_notes = NotesDetails.objects.filter(
        admin__userId__username=request.GET.get('username')).count()

    curr_ShowUserFriends = FriendsFormedDetails.objects.filter(
        Q(user__userId__username=request.GET.get('username'),
          friend_or_Request=True)).values('friend_name__userId')
    curr_ShowUserFriends1 = FriendsFormedDetails.objects.filter(
        Q(friend_name__userId__username=request.GET.get('username'),
          friend_or_Request=True)).values('user__userId')

    mutual_friends = FriendsFormedDetails.objects.filter(
        Q(friend_name__userId__username=request.user.username,
          user__userId__in=curr_ShowUserFriends)
        | Q(friend_name__userId__in=curr_ShowUserFriends,
            user__userId__username=request.user.username)).count()
    mutual_friends1 = FriendsFormedDetails.objects.filter(
        Q(friend_name__userId__username=request.user.username,
          user__userId__in=curr_ShowUserFriends1)
        | Q(friend_name__userId__in=curr_ShowUserFriends1,
            user__userId__username=request.user.username)).count()
    print(mutual_friends, mutual_friends1)

    return JsonResponse({
        "username": username,
        "formedAt": formedAt,
        "isFriend": isFriend,
        "total_notes": total_notes,
        "img_url": img_url,
        "name": full_name,
        "occupation": occupation,
        "total_friends": total_friends,
        "curr_lat": curr_lat,
        "curr_long": curr_long,
        "mutual": mutual_friends,
        "mutual1": mutual_friends1,
        "status": "200"
    })
Example #58
0
 def wrapper(request, *args, **kwargs):
     if request.method != 'POST':
         return JsonResponse({"code": 405, "err": "方法不允许"})
     return func(request, *args, **kwargs)
Example #59
0
 def get(self, request, *args, **kwargs):
     return JsonResponse({
         "url": request.build_absolute_uri(),
         "status": 200,
         "data": [self.serialize(post) for post in self.get_queryset()],
     })
Example #60
0
def searchable_list(request, *args, **kwargs):
    searchables = Searchable.objects.exclude(location_name='')
    serializer = SearchableSerializer(searchables, many=True)
    return JsonResponse(serializer.data, safe=False)