Пример #1
0
    def post(self, request, *args, **kwargs):
        attachment = request.FILES.get('uploaded_file')
        upload_redirect = request.POST.get("upload_redirect")
        if not attachment:
            messages.add_message(request, messages.INFO, 'File is required')
            if upload_redirect:
                return HttpResponseRedirect(upload_redirect)
            else:
                return HttpResponseRedirect(reverse(resolve(request.path_info).url_name))

        file_name = str(request.user.id) + "-" + str(uuid.uuid4()) + "." + attachment._name[
                                                                           attachment._name.rindex(".") + 1:]
        file_write_path = os.path.join(settings.MEDIA_TEMP_PATH, file_name)
        with open(file_write_path, 'wb+') as destination:
            for chunk in attachment.chunks():
                destination.write(chunk)

        reader_class = self.model.get_reader_class()
        reader = reader_class(file_name=file_write_path, sheet_name='Sheet1')
        data = reader.get_data()
        uploader_class = self.model.get_uploader_class()
        uploader = uploader_class(data=data)
        uploaded = uploader.handle_upload()
        os.remove(file_write_path)
        if uploaded:
            messages.add_message(request, messages.INFO, 'File uploaded successfully')
        else:
            messages.add_message(request, messages.INFO, 'File upload failed')

        if upload_redirect:
            return HttpResponseRedirect(upload_redirect)
        else:
            return HttpResponseRedirect(reverse(resolve(request.path_info).url_name))
 def _is_excluded_path(self, actual_path):
     paths = settings.PASSWORD_CHANGE_MIDDLEWARE_EXCLUDED_PATHS
     path = r'^%s$' % self.url
     paths.append(path)
     media_url = settings.MEDIA_URL
     if media_url:
         paths.append(r'^%s?' % media_url)
     static_url = settings.STATIC_URL
     if static_url:
         paths.append(r'^%s?' % static_url)
     if settings.PASSWORD_CHANGE_MIDDLEWARE_ALLOW_LOGOUT:
         try:
             logout_url = reverse('logout')
         except NoReverseMatch:
             pass
         else:
             paths.append(r'^%s$' % logout_url)
         try:
             logout_url = u'/admin/logout/'
             resolve(logout_url)
         except Resolver404:
             pass
         else:
             paths.append(r'^%s$' % logout_url)
     for path in paths:
         if re.match(path, actual_path):
             return True
     return False
Пример #3
0
 def get_handler(self):
     '''returns handler mapped to url.
     '''
     try:
         func, args, kwargs = resolve(self.get_app_url() + '0/')
         self.detected_as_auto = False
     except Exception:
         func, args, kwargs = resolve(self.get_app_url())
         self.detected_as_auto = True
     return func
Пример #4
0
def is_valid_path(path, urlconf=None):
    """
    Return True if the given path resolves against the default URL resolver,
    False otherwise. This is a convenience method to make working with "is
    this a match?" cases easier, avoiding try...except blocks.
    """
    from django.urls.base import resolve
    try:
        resolve(path, urlconf)
        return True
    except Resolver404:
        return False
Пример #5
0
def is_valid_path(path, urlconf=None):
    """
    Return True if the given path resolves against the default URL resolver,
    False otherwise. This is a convenience method to make working with "is
    this a match?" cases easier, avoiding try...except blocks.
    """
    from django.urls.base import resolve
    try:
        resolve(path, urlconf)
        return True
    except Resolver404:
        return False
Пример #6
0
    def __call__(self, request: HttpRequest):
        """ Install monkey-patch on demand.

        If monkey-patch has not been run in for this process (assuming multiple preforked processes),
        then do it now.

        """
        from ee.clickhouse import client

        route = resolve(request.path)
        client._request_information = {
            "save":
            (is_clickhouse_enabled() and request.user.pk
             and (request.user.is_staff or is_impersonated_session(request)
                  or settings.DEBUG)),
            "user_id":
            request.user.pk,
            "kind":
            "request",
            "id":
            f"{route.route} ({route.func.__name__})",
        }

        response: HttpResponse = self.get_response(request)

        client._request_information = None

        return response
Пример #7
0
    def test_hompage_url_resolvers_homepageView(self):
        view = resolve('/')

        self.assertEqual(
            view.func.__name__ ,
            homePageView.as_view().__name__
        )
Пример #8
0
def translate_url(url, lang_code):
    """
    Given a URL (absolute or relative), try to get its translated version in
    the `lang_code` language (either by i18n_patterns or by translated regex).
    Return the original URL if no translated version is found.
    """
    from django.urls import resolve, reverse
    parsed = urlsplit(url)
    try:
        match = resolve(parsed.path)
    except Resolver404:
        pass
    else:
        to_be_reversed = "%s:%s" % (match.namespace, match.url_name
                                    ) if match.namespace else match.url_name
        with override(lang_code):
            try:
                url = reverse(to_be_reversed,
                              args=match.args,
                              kwargs=match.kwargs)
            except NoReverseMatch:
                pass
            else:
                url = urlunsplit((parsed.scheme, parsed.netloc, url,
                                  parsed.query, parsed.fragment))
    return url
Пример #9
0
def IpUserget(*args):
    '''
    Get user,IP,path,function name
    input:request
    return: Get list
    author: Jia Liu
    '''
    #假如有Request參數,印出 IP、User、URL、view name 並組合字串丟到log裡面
    request = str(args)
    if 'Request' in request:
        ip = None
        ip = args[0].META.get('REMOTE_ADDR')
        user = None
        if args[0].user.is_authenticated:
            user = args[0].user.username
        else:
            try:
                basic_auth_str = args[0].headers['Authorization'][6:]
                username, password = base64.b64decode(basic_auth_str).decode(
                    'utf-8').split(':')
                user = username
            except:
                user = "******"
        path = None
        path = args[0].META['PATH_INFO']
        url_name = resolve(path).url_name
        listall = [ip] + [user] + [path] + [url_name]
        alls = str(listall)
        return alls
    else:
        ip = "localhost"
        source = "system"
        listall = [ip] + [source]
        alls = str(listall)
        return alls
Пример #10
0
    def __call__(self, request: HttpRequest):
        """ Install monkey-patch on demand.

        If monkey-patch has not been run in for this process (assuming multiple preforked processes),
        then do it now.

        """
        from ee.clickhouse import client

        route = resolve(request.path)
        route_id = f"{route.route} ({route.func.__name__})"
        client._request_information = {
            "save": (request.user.pk and (request.user.is_staff or is_impersonated_session(request) or settings.DEBUG)),
            "user_id": request.user.pk,
            "kind": "request",
            "id": route_id,
        }

        response: HttpResponse = self.get_response(request)

        if "api/" in route_id and "capture" not in route_id:
            incr("http_api_request_response", tags={"id": route_id, "status_code": response.status_code})

        client._request_information = None

        return response
Пример #11
0
def contact(request):
    current_url = resolve(request.path_info).url_name
    current_path = request.get_full_path()
    if request.method == 'POST':
        # form = CommentForm(request.POST)
        # if form.is_valid():
        #    new_comment = Comment(name=request.POST['atrb_name'],  email=request.POST['atrb_email'], comment=request.POST['atrb_comment'])
        #    new_comment.save()
        #    return redirect('comment')
        new_comment = Comment(name=request.POST['atrb_name'],
                              email=request.POST['atrb_email'],
                              comment=request.POST['atrb_comment'],
                              url_name=current_url)
        new_comment.save()
        return HttpResponse('')
    else:
        form = CommentForm()

    # comments = Comment.objects.order_by('-date_added')
    comments = Comment.objects.filter(
        url_name=current_url).order_by('-date_added')
    print('The URL name: ' + current_url)
    context = {
        'comments': comments,
        'form': form,
        'page_name': current_url,
        'current_path': current_path
    }
    return render(request, 'webcontext/contact.html', context)
Пример #12
0
 def process_request(self, request):
     if request.method != 'GET':
         return
     try:
         resolve(request.path_info)
     except Resolver404:
         return
     self.now = timezone.now()
     self.url = reverse('password_change')
     if settings.PASSWORD_DURATION_SECONDS and \
             request.user.is_authenticated() and \
             not self._is_excluded_path(request.path):
         self.check = PasswordCheck(request.user)
         self.expiry_datetime = self.check.get_expiry_datetime()
         self._check_necessary(request)
         return self._redirect(request)
Пример #13
0
    def test_get_for_list_of_accounts(self):
        self.populate_accounts()
        AccountTestFactory.create_batch(3)
        accs = list(Account.objects.all())

        request = self.req_fact.get('/accounts/')
        resp = resolve('/accounts/').func(request)
        self.assertEqual(AccountSerializer(accs, many=True).data, resp.data)
Пример #14
0
def get_active_menu(request, menu_list):

    for menu in menu_list:
        if menu['submenu']:
            result = get_active_menu(request, menu['submenu'])
            if result: return result
        else:
            if resolve(request.path).url_name in menu['url_names']:
                return menu['obj']
Пример #15
0
def get_view_by_url(url_name=None):
    """
    **view generator**
    :param url_name: get url_name as string
    :return: view function (Though it is class or something)
    """
    if not url_name:
        return None
    url = reverse_lazy(url_name)
    resolver_match = resolve(url)
    return resolver_match.func
Пример #16
0
 def test_post_for_new_account(self):
     self.populate_accounts()
     root_acc = get_root_acc()
     acc_data = {
         "name": "MyAcc",
         "acc_type": "Branch",
         "parent": root_acc.pk
     }
     request = self.req_fact.post(f'/accounts/', acc_data)
     resp = resolve(f'/accounts/').func(request)
     assert resp.status_code == 201, resp.data
     assert Account.objects.filter(name="MyAcc").exists()
Пример #17
0
def get_hreflang_info(path, default=True):
	"""
	@param path: Current path (request.path).
	@param default: Include the default landing page (x-default without language code).
	:return: A list of (code, url) tuples for all language versions.
	"""
	reverse_match = resolve(path)
	info = []
	if default:
		info.append(('x-default', reverse(reverse_match.view_name, use_lang_prefix=False, kwargs=reverse_match.kwargs)))
	for lang in language_codes():
		info.append((lang, reverse(reverse_match.view_name, lang=lang, use_lang_prefix=True, kwargs=reverse_match.kwargs)))
	return info
Пример #18
0
    def middleware(request):
        if request.method not in ("GET", "OPTIONS"):
            try:
                resolver_match = resolve(request.path)
                key = api.key_from_resolvermatch(resolver_match)
                collective = api.collective_from_key(key)
                if collective.readonly:
                    raise CollectiveReadOnlyError(collective)
            except (KeyError, Collective.DoesNotExist):
                pass

        response = get_response(request)
        return response
Пример #19
0
    def __call__(self, request):
        url = resolve(request.path)

        # we need to get the person (and set the language) right at the start
        if request.user.is_authenticated or url.url_name == 'login' or url.url_name == 'admin_api_workout':

            if request.user.is_anonymous:
                response = self.get_response(request)
                return response

            response = self.get_response(request)
            return response
        return HttpResponseRedirect('/login/')
Пример #20
0
def translate_url(context, lang, view_name=None, *args, **kwargs):
    """
	Translate an url to a specific language.
	
	@param lang: Which language should the url be translated to.
	@param view_name: Which view to get url from, current if not set.
	"""
    assert 'request' in context, 'translate_url needs request context'
    if view_name is None:
        reverse_match = resolve(context['request'].path)
        view_name = reverse_match.view_name
        args = reverse_match.args
        kwargs = reverse_match.kwargs
    return reverse(view_name, lang=lang, *args, **kwargs)
Пример #21
0
    def _get_api_instance(self, api_path: Optional[str] = None) -> NinjaAPI:
        if not api_path:
            return resolve("/api/").func.keywords["api"]  # type: ignore

        try:
            api = import_string(api_path)
        except ImportError:
            raise CommandError(
                f"Module or attribute for {api_path} not found!")

        if not isinstance(api, NinjaAPI):
            raise CommandError(f"{api_path} is not instance of NinjaAPI!")

        return api
Пример #22
0
    def _call_(self, request):
        url = request.path
        url_resolved = resolve(url)

        if 'api' in url_resolved.namespaces:
            return self.get_response(request)

        if self.app_name == url_resolved.app_name and not url_resolved.url_name in self.ls_urls_no_validadas:
            if self.has_permission(request):
                return self.get_response(request)
            else:
                return HttpResponseRedirect(self.url_redireccion)

        else:
            return self.get_response(request)
Пример #23
0
def diff_release_home(request):
    """
    View function for diff query page
    """
    # Render the HTML template index.html with data in the context variable
    current_url = resolve(request.path_info).url_name

    if "diff_home_release" in current_url:
        diff_release = True

    if request.method == 'POST':
        form = DiffFormRelease(request.POST)
        if form.is_valid():
            form_data_dict = form.get_cleaned_data()

            diff_dict = {}
            diff_dict['release_set_1'] = {
                "source": form_data_dict["diff_me_source"].lower(),
                "assembly": form_data_dict["diff_me_assembly"].lower(),
                "version": form_data_dict["diff_me_release"]
            }

            diff_dict['release_set_2'] = {
                "source": form_data_dict["diff_with_source"].lower(),
                "assembly": form_data_dict["diff_with_assembly"].lower(),
                "version": form_data_dict["diff_with_release"]
            }

            diff_result_release = ReleaseUtils.get_release_diff(diff_dict)

            return render(request,
                          'diff_compare_release_set_result.html',
                          context={
                              'form':
                              form,
                              'diff_release':
                              diff_release,
                              'diff_result_release':
                              json.dumps(diff_result_release),
                              'form_data_dict':
                              json.dumps(form_data_dict)
                          })
        else:
            logger.error(form.errors)
    else:
        form = DiffForm()
    return render(request, 'release_diff.html', context={'form': form})
Пример #24
0
 def process_request(self, request):
     '''
         curl http://localhost:8090/api/auth/test/ => the latest, v2 maybe
         curl -H "X-Version: v2" http://localhost:8090/api/auth/test/ => v2
         curl -H "X-Version: v1" http://localhost:8090/api/v2/auth/test/ => v2
     '''
     r = resolve(request.path_info)
     version = request.META.get('HTTP_X_VERSION', False)
     if r.namespace.startswith('api:') and version:
         # request.path_info will always be equal to or longer than request.path
         # so I choose request.path to test
         if '/'.join(r.namespaces[:2]) not in request.path:
             # version in request.path takes high priority
             request.path = request.path.replace('/api',
                                                 '/api/{}'.format(version))
             request.path_info = request.path_info.replace(
                 '/api', '/api/{}'.format(version))
Пример #25
0
 def process_request(self, request):
     # plz refer to
     # http://stackoverflow.com/questions/14269719/django-rest-framework-v1-versioning#answer-21839842
     # e.g.:
     #    curl -H "X-Version: v1" http://localhost:8090/api/auth/test/
     # and I've decided to do this in the old way (MiddlewareMixin)
     r = resolve(request.path_info)
     version = request.META.get("HTTP_X_VERSION", False)
     if r.namespace.startswith("api:") and version:
         # request.path_info will always be equal to or longer than request.path
         # so I choose request.path to test
         if "/".join(r.namespaces[:2]) not in request.path:
             # version in request.path takes high priority
             request.path = request.path.replace("/api",
                                                 "/api/{}".format(version))
             request.path_info = request.path_info.replace(
                 "/api", "/api/{}".format(version))
Пример #26
0
def activate(request):
    current_url = resolve(request.path_info).url_name
    current_path = request.get_full_path()
    username = '******'
    if request.method == 'GET':
        parameter_code = request.GET.get('code', '')
        print('the code parameter', parameter_code)

        user_object = TemporaryUser.objects.get(activation_code=parameter_code)
        username = user_object.username
        # get user name from parameter and load username from database

    context = {
        'username': username,
        'page_name': current_url,
        'current_path': current_path
    }
    return render(request, 'webcontext/activate.html', context)
Пример #27
0
def default_context(request):
    referrer = ''
    if request.META.get("HTTP_REFERER"):
        referrer = request.META.get("HTTP_REFERER")

    # SITE_URL = settings.SITE_URL
    # STATIC_URL = settings.STATIC_URL
    # SITE_VERSION = settings.SITE_VERSION
    # MEDIA_URL = settings.MEDIA_URL

    try:
        current_url_name = resolve(request.path_info).url_name
    except Resolver404:
        current_url_name = ''

    # return {'referrer': referrer, 'SITE_URL': SITE_URL, 'STATIC_URL': STATIC_URL, 'SITE_VERSION': SITE_VERSION, 'MEDIA_URL': MEDIA_URL,
    #         'current_url_name': current_url_name}

    return {'referrer': referrer, 'current_url_name': current_url_name}
Пример #28
0
def translate_url(url, lang_code):
    """
    Given a URL (absolute or relative), try to get its translated version in
    the `lang_code` language (either by i18n_patterns or by translated regex).
    Return the original URL if no translated version is found.
    """
    from django.urls import resolve, reverse
    parsed = urlsplit(url)
    try:
        match = resolve(parsed.path)
    except Resolver404:
        pass
    else:
        to_be_reversed = "%s:%s" % (match.namespace, match.url_name) if match.namespace else match.url_name
        with override(lang_code):
            try:
                url = reverse(to_be_reversed, args=match.args, kwargs=match.kwargs)
            except NoReverseMatch:
                pass
            else:
                url = urlunsplit((parsed.scheme, parsed.netloc, url, parsed.query, parsed.fragment))
    return url
Пример #29
0
    def _(request, *fargs, **fkwargs):
        # The view that loaded the page the callback is on.
        referer_resolver_match = resolve(c.request.META["HTTP_X_PATHNAME"])

        @appstate(app_name, appstate_init)
        def wrap_view_with_hypergen(func_return, args):
            # Run the callback function.
            func_return["value"] = func(request, *args, **fkwargs)
            if type(func_return["value"]
                    ) is not HttpResponseRedirect and view is not None:
                # Render from a view.
                # Allow the view to issue commands. Eg. notifications.
                with c(commands=[], at="hypergen"):
                    view.original_func(request, *referer_resolver_match.args,
                                       **referer_resolver_match.kwargs)
                    func_return["commands"] = c.hypergen.commands

        assert c.request.method == "POST", "Only POST request are supported"
        assert c.request.is_ajax()
        # Store base_template for partial loading in the <a> class.
        c.base_template = base_template

        args = list(fargs)
        args.extend(loads(request.POST["hypergen_data"])["args"])
        with c(referer_resolver_match=referer_resolver_match):
            func_return = {}
            commands = hypergen(wrap_view_with_hypergen,
                                func_return,
                                args,
                                target_id=target_id,
                                wrap_elements=wrap_elements)
            # Commands are either default hypergen commands or commands from callback
            commands = commands if func_return[
                "value"] is None else func_return["value"]
            # Allow view to add commands
            if type(commands) is not HttpResponseRedirect:
                commands.extend(func_return.get("commands", []))
            return commands
Пример #30
0
 def exec_auto_application(self):
     '''
     creates a test auto application for activities that don't yet have applications
     @rtype: bool
     '''
     try:
         if not self.activity.process.enabled:
             raise Exception('process %s disabled.' % self.activity.process.title)
         # no application: default auto app
         if not self.activity.application:
             return self.default_auto_app()
         
         func, args, kwargs = resolve(self.activity.application.get_app_url())
         params = self.activity.app_param
         # params values defined in activity override those defined in urls.py
         if params:
             params = eval('{' + params.lstrip('{').rstrip('}') + '}')
             kwargs.update(params)
         func(workitem=self , **kwargs)
         return True
     except Exception as v:
         log.error('execution wi %s:%s', self, v)
     return False
Пример #31
0
def registration(request):
    current_url = resolve(request.path_info).url_name
    current_path = request.get_full_path()
    if request.method == 'POST':
        print('Storing user ', request.POST['atrb_username'], '.')
        hashed_password = hash_password(request.POST['atrb_password'])
        temp_user = TemporaryUser(username=request.POST['atrb_username'],
                                  email=request.POST['atrb_email'],
                                  password=hashed_password,
                                  activation_code=uuid.uuid4())
        temp_user.save()
        send_email(temp_user.username, temp_user.email,
                   str(temp_user.activation_code))
        return HttpResponse('')
    else:
        form = TemporaryUserForm()

    print('The URL name: ' + current_url)
    context = {
        'form': form,
        'page_name': current_url,
        'current_path': current_path
    }
    return render(request, 'webcontext/registration.html', context)
 def test_有對應函式(self):
     對應 = resolve('/平臺項目/加外語')
     self.assertEqual(對應.func, 加外語請教條)
     對應 = resolve('/平臺項目/把測試資料藏起來')
     self.assertEqual(對應.func, 把測試資料藏起來)
Пример #33
0
 def test_url_for_specific_account_resolves_to_view_func(self):
     resolver = resolve('/accounts/1/')
     assert resolver.func.cls == AccountViewSet
     assert resolver.kwargs == {'pk': '1'}
 def test_對應函式(self):
     對應 = resolve('/使用者/看編號')
     self.assertEqual(對應.func, 登入狀況)
 def test_有對應函式(self):
     對應 = resolve('/平臺項目列表/揣列表')
     self.assertEqual(對應.func, 揣外語請教條)
 def test_有對應函式(self):
     對應 = resolve('/對齊結果')
     self.assertEqual(對應.func, 看對齊結果)
 def test_有對應函式(self):
     對應 = resolve('/平臺項目/看詳細內容')
     self.assertEqual(對應.func, 看資料詳細內容)
 def test_有對應函式(self):
     對應 = resolve('/標漢羅')
     self.assertEqual(對應.func, 斷詞介面.標漢羅)
 def test_有對應函式(self):
     對應 = resolve('/平臺項目/加新詞影音')
     self.assertEqual(對應.func, 加新詞影音)
 def test_對應函式(self):
     對應 = resolve('/平臺項目列表/揣上新貢獻的外語')
     self.assertEqual(對應.func, 揣上新貢獻的外語請教條)
 def test_有對應函式(self):
     對應 = resolve('/正規化團隊表')
     self.assertEqual(對應.func, 正規化團隊表)
 def test_有對應函式(self):
     對應 = resolve('/平臺項目/投票')
     self.assertEqual(對應.func, 投票)
 def test_有對應函式(self):
     對應 = resolve('/對齊音檔')
     self.assertEqual(對應.func, Kaldi對齊)
 def 有對應函式(self):
     對應 = resolve('/貢獻者表')
     self.assertEqual(對應.func, 貢獻者表)
 def test_有對應函式(self):
     對應 = resolve('/匯出資料')
     self.assertEqual(對應.func, 匯出辭典資料)
 def 有對應函式(self):
     對應 = resolve('/平臺項目/加新詞文本')
     self.assertEqual(對應.func, 外語加新詞文本)