Ejemplo n.º 1
0
    def get(self, request, country_name):
        if country_name == 'world' or country_name == 'World':
            country_name = 'World'
        country_cache = os.path.join(settings.CLUSTER_CACHE_DIR, country_name)
        metadata_file = os.path.join(country_cache, 'metadata')
        try:
            f = open(metadata_file, 'r')
            file_content = f.read()
            if file_content == 'Start':
                return Response('Start')
            try:
                metadata = json.loads(file_content)
            except ValueError:
                return Response('Start')
            if metadata['total'] == metadata['index']:
                # check metadata
                if country_name == 'world' or country_name == 'World':
                    country_name = 'World'
                    queryset = LocalityOSMView.objects.all().order_by('row')
                else:
                    country = Country.objects.get(name__iexact=country_name)
                    polygons = country.polygon_geometry
                    queryset = LocalityOSMView.objects.in_polygon(
                        polygons).order_by('row')
                if metadata['total'] == queryset.count() and \
                        metadata['row'] == queryset.last().row:
                    return Response(metadata)
            else:
                return Response(metadata)
        except IOError:
            if not os.path.exists(country_cache):
                os.makedirs(country_cache)

        try:
            country_data_into_shapefile_task.delay(country_name)
            try:
                file = open(metadata_file, 'w+')
                file.write('Start')
                file.close()
            except Exception:
                pass
            return Response('Start')
        except Country.DoesNotExist:
            return HttpResponseBadRequest('%s is not found or not a country.' %
                                          country_name)
Ejemplo n.º 2
0
    def get(self, request, username):
        try:
            user = User.objects.get(username=username)
            osm_user = get_osm_name(user)
            if osm_user:
                username = osm_user
        except User.DoesNotExist:
            pass

        updates_osm = all_locality().filter(changeset_user=username).exclude(
            changeset_timestamp__isnull=True).order_by('-changeset_timestamp')

        try:
            queryset = self.get_query_by_page(updates_osm)
        except (LessThanOneException, NotANumberException) as e:
            return HttpResponseBadRequest('%s' % e)

        return Response(LocalityOSMBasicSerializer(queryset, many=True).data)
Ejemplo n.º 3
0
def ajax_get_dataset_options(request):
    selected_dataset_name = request.GET.get('dataset_id')
    filter_widget_id = request.GET.get('filter_widget_id')
    param_filter_widget_id = request.GET.get('param_filter_widget_id')

    try:
        selected_dataset = Dataset.objects.get(pk=selected_dataset_name)
    except:
        return HttpResponseBadRequest("Not a valid dataset")

    response_data = {
        'versions': __render_options(selected_dataset.versions.all().order_by('-pretty_name')),
        'variables': __render_options(selected_dataset.variables.all().order_by('id')),
        'filters': __render_filters(selected_dataset.filters.filter(parameterised=False), filter_widget_id, parametrised = False),
        'paramfilters': __render_filters(selected_dataset.filters.filter(parameterised=True), param_filter_widget_id, parametrised = True),
        }

    return JsonResponse(response_data)
Ejemplo n.º 4
0
 def __decorator(self, request, *args, **kwargs):
     if request.method not in methods:
         return view(request, *args, **kwargs)
     try:
         request.access_token = re.match(
             '^token (\w+)',
             request.META['HTTP_AUTHORIZATION']).groups()[0]
     except (KeyError, AttributeError):
         request.access_token = None
     # client_info = ClientTokenHelper.verify(request.access_token)
     # if not client_info:
     #     return HttpResponseForbidden(json.dumps({
     #         "message": "Authorization failed"}))
     # request.client_id = client_info['client_id']
     if not _deal_request(request):
         return HttpResponseBadRequest(
             json.dumps({"message": "Problems parsing JSON"}))
     return view(self, request, *args, **kwargs)
Ejemplo n.º 5
0
    def post(self,request,*args, **kwargs):
        uuid=kwargs['uuid']

        if request.user.is_authenticated :
            return HttpResponseForbidden()

        user=request.user

        try:
            folder = CodeFolder.objects.get(folder_uuid=uuid,user=user)

            folder.delete()

        except CodeFolder.DoesNotExist:
            return HttpResponseNotFound()

        except:
            return HttpResponseBadRequest()
Ejemplo n.º 6
0
    def post(self,request,*args, **kwargs):
        uuid=kwargs['uuid']

        user=request.user

        try:
            paste = CodePaste.objects.get(paste_uuid=uuid,user=user)

            paste.delete()

            return JsonResponse({'detail':'success'})

        except CodePaste.DoesNotExist:
            print('not_forund')
            return HttpResponseNotFound()

        except:
            return HttpResponseBadRequest()
Ejemplo n.º 7
0
    def get_graphql_params(request, data):
        query = request.GET.get("query") or data.get("query")
        variables = request.GET.get("variables") or data.get("variables")
        id = request.GET.get("id") or data.get("id")

        if variables and isinstance(variables, str):
            try:
                variables = json.loads(variables)
            except Exception:
                raise HttpError(
                    HttpResponseBadRequest("Variables are invalid JSON."))

        operation_name = request.GET.get("operationName") or data.get(
            "operationName")
        if operation_name == "null":
            operation_name = None

        return query, variables, operation_name, id
Ejemplo n.º 8
0
def generate_element(request, explore_data_structure_id):
    """ Generate an element absent from the form.

    Args:
        request:
        explore_data_structure_id:

    Returns:

    """
    try:
        element_id = request.POST['id']
        explore_data_structure = explore_data_structure_api.get_by_id(
            explore_data_structure_id)
        html_form = generate_element_absent(
            request, element_id, explore_data_structure.template.content)
    except Exception, e:
        return HttpResponseBadRequest()
Ejemplo n.º 9
0
def run(request):
    resp = get_chooser_or_response(request)
    if type(resp) == Chooser:
        route = resp.get_grouped_route()
    else:
        return resp
    if route == None:
        return HttpResponseBadRequest('Not enough orbs to finish a run!')
    params = resp.settings.to_display_dict()
    #used for the next run
    newseed = random.getrandbits(32)
    params.update({
        'run': route,
        'setting_str': resp.settings.to_setting_str(),
        'seed': resp.seed,
        'newseed': newseed
    })
    return render(request, 'run.html', params)
Ejemplo n.º 10
0
def answer(request):
    if not util.check_active_student(request): return redirect("student_login")

    if request.method == "GET" and all([x in request.GET for x in ("qid", "ans")]):
        data = request.GET

        q = TeambuildingQuestion.objects.get(id=data['qid'])
        r, created = TeambuildingResponse.objects.get_or_create(question=q, student_id=request.session['sid'])
        r.answer = q.get_answers()[int(data['ans'])]

        r.save()

        q.used = True
        q.save()

        return redirect('index')

    return HttpResponseBadRequest()
Ejemplo n.º 11
0
    def get(self, request, username):
        page = self.request.GET.get('page', None)
        if page:
            try:
                queryset = self.get_query_by_page(
                    PendingUpdate.objects.filter(uploader__username=username))
            except (LessThanOneException, NotANumberException) as e:
                return HttpResponseBadRequest('%s' % e)
        else:
            queryset = PendingUpdate.objects.filter(
                uploader__username=username)
            for pending in queryset:
                validate_pending_update(pending.extension.osm_type,
                                        pending.extension.osm_id)
            queryset = PendingUpdate.objects.filter(
                uploader__username=username)

        return Response(PendingUpdateSerializer(queryset, many=True).data)
Ejemplo n.º 12
0
def order_progress(request, order_pk):
    """
    Returns the current progress of the order in the following format:
    {
        “created”: 5,
        “total”: 20,
        “progress”: “25%”
    }
    """
    if not request.is_ajax():
        return HttpResponseBadRequest()

    order = get_object_or_404(Order,
                              service_type=Order.SOCIAL_PROFILES,
                              pk=order_pk)
    if "view_order" not in get_perms(request.user, order):
        raise Http404
    return JsonResponse(order.order_progress)
Ejemplo n.º 13
0
def update_transaccion_modal(request, id_transaccion):
    """ Returns a form that can be used to edit an existing
    transaccion.
    """
    if request.is_ajax():
        context = {}
        transaccion = get_object_or_404(Transaccion, pk=id_transaccion)
        id_familia = transaccion.familia.pk
        context['id_familia'] = id_familia
        id_transaccion = transaccion.pk
        context['transaccion_form'] = TransaccionForm(
            instance=transaccion, initial={'id_transaccion': id_transaccion})
        if hasattr(transaccion, 'ingreso'):
            context['ingreso_form'] = IngresoForm(id_familia,
                                                  instance=transaccion.ingreso)
        return render(request, 'captura/edit_ingreso_egreso_form.html',
                      context)
    return HttpResponseBadRequest()
Ejemplo n.º 14
0
    def post(self, request, *args, **kwargs):

        form = forms.CreateIssueCommentForm(request.POST)
        if not form.is_valid():
            return HttpResponseBadRequest()

        i = self.get_object()
        comment_id = request.POST.get('comment_id', None)
        try:
            c = i.comments.get(pk=int(comment_id))
            c.content = enhance_html(form.cleaned_data['content'])
            c.save()
            return json_response({'comment_id': c.id})
        except:
            c = i.comments.create(content=enhance_html(
                form.cleaned_data['content']),
                                  created_by=request.user)
            return json_response({'comment_id': c.id})
Ejemplo n.º 15
0
def get_statuses(request):
    request_params = request.GET.dict()
    request_path = request_params.get('request_path')
    if not request_path:
        return HttpResponseBadRequest(
            "Bad request: missing request_path param")

    url = KIKAR_URL_BASE + request_params.pop('request_path')
    if 'filter' in request_params:
        request_filter = request_params.pop('filter').split('=')
        request_params[request_filter[0]] = request_filter[1]

    # TODO: Jesus how can this be even tested? should be separated to proxy
    kikar_res = requests.get(url, params=request_params)
    logger.debug(kikar_res.url)
    res = HttpResponse(content=kikar_res.content,
                       content_type='application/json')
    return res
Ejemplo n.º 16
0
    def post(self, request, *args, **kwargs):
        if not CourseAccess.allowed(request):
            return HttpResponseForbidden()

        wid = self.request.POST.get('metadata-wardenclyffe-id', None)
        if not wid:
            return HttpResponseNotFound()

        qs = self.get_matching_assets(wid)
        if qs.count() == 0:
            return HttpResponseNotFound()

        for asset in self.get_matching_assets(wid):
            items = request.POST.items()
            if not self.update_asset(asset, items):
                return HttpResponseBadRequest()

        return HttpResponse('updated')
Ejemplo n.º 17
0
    def post(self, request, *args, **kwargs):
        """ Used to change a proposal status (accept/reject)
            or a proposal's property completed/not completed
        """
        p = self.get_object()
        v = request.POST.get('accepted', None)
        if v:
            v = int(v)
            if v not in [
                    p.statuses.ACCEPTED, p.statuses.REJECTED,
                    p.statuses.IN_DISCUSSION
            ]:
                return HttpResponseBadRequest(
                    "Bad value for accepted POST parameter")

            p.status = v
            p.save()
        return redirect(p)
Ejemplo n.º 18
0
    def get_graphql_params(request, data):
        query = request.GET.get('query') or data.get('query')
        variables = request.GET.get('variables') or data.get('variables')
        id = request.GET.get('id') or data.get('id')

        if variables and isinstance(variables, six.text_type):
            try:
                variables = json.loads(variables)
            except Exception:
                raise HttpError(
                    HttpResponseBadRequest('Variables are invalid JSON.'))

        operation_name = request.GET.get('operationName') or data.get(
            'operationName')
        if operation_name == "null":
            operation_name = None

        return query, variables, operation_name, id
Ejemplo n.º 19
0
 def get(self,request):
     '''
     1接收前端传递过来的uuid
     2判断uuid是否获取到
     3通过调用captcha来生成图片验证码(图片二进制和图片内容)
     4将图片内容保存到redis中 uuid-key,图片内容-value,同时设置一个时效
     5返回图片二进制
     :param request:
     :return:
     '''
     uuid = request.GET.get('uuid')
     if uuid is None:
         return HttpResponseBadRequest('没有传递uuid')
     text,image = captcha.generate_captcha()
     redis_conn = get_redis_connection('default')
     #uuid 过期秒数 图片二进制内容
     redis_conn.setex('img:%s'%uuid,300,text)
     return HttpResponse(image,content_type='image/jpeg')
Ejemplo n.º 20
0
 def process_response(self, request, response):
     if self.is_not_ignorable_request(request):
         url = '{0}{1}'.format(settings.NODE_SERVER, self.path)
         req = urllib2.Request(url, headers=request.META)
         try:
             conn = urllib2.urlopen(req)
             info = conn.info()
             data = conn.read()
             return HttpResponse(data,
                                 content_type=info.get("content-type"))
         except HTTPError as e:
             if e.code == '400':
                 return HttpResponseBadRequest()
             if e.code == '404':
                 return HttpResponseNotFound()
             if e.code == '500':
                 return HttpResponseServerError()
     return response
Ejemplo n.º 21
0
    def post(self, request):
        # 1.接收数据
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        smscode = request.POST.get('sms_code')
        # 2.验证数据
        #     2.1 判断参数是否齐全
        if not all([mobile, password, password2, smscode]):
            return HttpResponseBadRequest('参数不全')
        #     2.2 手机号是否符合格则
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('手机号不符合格则')
        #     2.3 判断密码是否符合格则
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseBadRequest('密码不符合格则')
        #     2.4 判断确认密码和密码是否一致
        if password2 != password:
            return HttpResponseBadRequest('密码不一致')
        #     2.5 判断短信验证码是否正确
        redis_conn = get_redis_connection('default')
        redis_sms_code = redis_conn.get('sms:%s' % mobile)
        if redis_sms_code is None:
            return HttpResponseBadRequest('短信验证码已过期')
        if redis_sms_code.decode() != smscode:
            return HttpResponseBadRequest('短信验证码错误')
        # 3.根据手机号进行用户信息的查询
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 5.如果手机号没有查询出用户信息,则进行新用户的创建
            try:
                User.objects.create_user(username=mobile,
                                         mobile=mobile,
                                         password=password)
            except Exception:
                return HttpResponseBadRequest('修改失败,请稍后再试')
        else:
            # 4.如果手机号查询出用户信息则进行用户密码的修改
            user.set_password(password)
            # 注意,保存用户信息
            user.save()

        # 6.进行页面跳转,跳转到登录页面
        response = redirect(reverse('users:login'))
        # 7.返回响应
        return response
Ejemplo n.º 22
0
 def set_background(self, request: Request, slug: str):
     """Set Flow background"""
     flow: Flow = self.get_object()
     background = request.FILES.get("file", None)
     clear = request.data.get("clear", "false").lower() == "true"
     if clear:
         if flow.background_url.startswith("/media"):
             # .delete() saves the model by default
             flow.background.delete()
         else:
             flow.background = None
             flow.save()
         return Response({})
     if background:
         flow.background = background
         flow.save()
         return Response({})
     return HttpResponseBadRequest()
Ejemplo n.º 23
0
def archive_misconfigured_response() -> HttpResponse:
    """
    Returns an error :class:`HttpResponse` describing how the archive is
    misconfigured.
    """
    missing = []  # type: List[str]
    if not _archive_attachment_dir:
        missing.append(SettingsKeys.ARCHIVE_ATTACHMENT_DIR)
    if not _archive_root_template:
        missing.append(SettingsKeys.ARCHIVE_ROOT_TEMPLATE)
    if not _archive_static_dir:
        missing.append(SettingsKeys.ARCHIVE_STATIC_DIR)
    if not _archive_template_cache_dir:
        missing.append(SettingsKeys.ARCHIVE_TEMPLATE_CACHE_DIR)
    if not _archive_template_dir:
        missing.append(SettingsKeys.ARCHIVE_TEMPLATE_DIR)
    return HttpResponseBadRequest(
        f"Archive not configured. Administrator has not set: {missing!r}")
Ejemplo n.º 24
0
    def post(self, request, *args, **kwargs):
        domain = request.GET.get('domain')
        case_type = request.GET.get('case_type')
        user_name = request.GET.get('user')
        properties = json.loads(request.body)
        case_id = properties['case_id']

        properties.pop('case_id')

        couch_user = CommCareUser.get_by_username(user_name)
        if not couch_user.is_member_of(domain):
            return HttpResponseForbidden(
                "This user does not have access to this domain.")

        case = get_case_or_404(domain, case_id)

        if not case.type == case_type:
            return HttpResponseBadRequest("Case type mismatch")
Ejemplo n.º 25
0
def import_students(request):
    if request.method == "POST" and "students" in request.POST:
        in_str = request.POST['students']

        for line in in_str.split("\n"):
            last, first, sid, homeroom = [x.strip() for x in line.split(",")]
            s, created = Student.objects.get_or_create(id=sid,
                                                       grade=int(homeroom[0]))

            s.fname = first
            s.lname = last
            s.homeroom = homeroom

            s.save()

        return redirect("admin")
    else:
        return HttpResponseBadRequest()
Ejemplo n.º 26
0
def delete_bucket(request):
    """Delete a bucket.

    Args:
        request:

    Returns:

    """
    try:
        bucket_id = request.POST["bucket_id"]

        bucket = bucket_api.get_by_id(bucket_id)
        bucket_api.delete(bucket)
    except Exception as e:
        return HttpResponseBadRequest(escape(str(e)))

    return HttpResponse(json.dumps({}), content_type="application/javascript")
Ejemplo n.º 27
0
def generate_choice(request, sandbox_data_structure_id):
    """Generate a choice branch absent from the form.

    Args:
        request:
        sandbox_data_structure_id:

    Returns:

    """
    try:
        element_id = request.POST['id']
        sandbox_data_structure = sandbox_data_structure_api.get_by_id(
            sandbox_data_structure_id)
        html_form = generate_choice_absent(
            request, element_id, sandbox_data_structure.template.content)
    except Exception, e:
        return HttpResponseBadRequest()
Ejemplo n.º 28
0
def register(request):
    post = request.data
    username = post.get("username", None)
    password = post.get("password", None)
    email = post.get("email", None)
    print(password)
    if username is None or password is None or email is None:
        return HttpResponseBadRequest()
    user = User.objects.create_user(username, email, password)
    user.save()
    return Response({
        "user":
        UserSerializer(user, context={
            "request": request
        }).data,
        "token":
        jwt_encode_handler(jwt_payload_handler(user))
    })
Ejemplo n.º 29
0
 def get(self, request, user_id):
     user = UserInfo.objects.get(id=user_id)
     name = user.realname
     email = user.email
     qq = user.qq
     phone = user.phone
     adress = user.adress
     if name and email and qq and phone and adress:
         dataList = {
             'name': name,
             'email': email,
             'qq': qq,
             'phone': phone,
             'adress': adress,
         }
         return JsonResponse(dataList)
     else:
         return HttpResponseBadRequest()
Ejemplo n.º 30
0
    def escaped_execute_graphql_request(self,
                                        request,
                                        data,
                                        query,
                                        variables,
                                        operation_name,
                                        show_graphiql=False):
        if not query:
            if show_graphiql:
                return None
            raise HttpError(
                HttpResponseBadRequest('Must provide query string.'))

        source = Source(query, name='GraphQL request')

        document_ast = parse(source)
        validation_errors = validate(self.schema, document_ast)
        if validation_errors:
            return ExecutionResult(
                errors=validation_errors,
                invalid=True,
            )

        if request.method.lower() == 'get':
            operation_ast = get_operation_ast(document_ast, operation_name)
            if operation_ast and operation_ast.operation != 'query':
                if show_graphiql:
                    return None

                raise HttpError(
                    HttpResponseNotAllowed(
                        ['POST'],
                        'Can only perform a {} operation from a POST request.'.
                        format(operation_ast.operation)))

        return self.execute(
            document_ast,
            root_value=self.get_root_value(request),
            variable_values=variables,
            operation_name=operation_name,
            context_value=self.get_context(request),
            middleware=self.get_middleware(request),
            executor=self.executor,
        )