예제 #1
0
    def get(self, request, format=None, **kwargs):
        if 'id' in self.kwargs:
            try:
                object = ApplicationHandle.objects.get(pk=uri_to_iri(
                    self.kwargs['id']))  # uri_to_iri translates %xx
            except ApplicationHandle.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
            serializer = Software_Community_Serializer(object)
        elif 'resourceid' in self.kwargs:
            objects = ApplicationHandle.objects.filter(
                ResourceID__exact=self.kwargs['resourceid'])
            serializer = Software_Community_Serializer(objects, many=True)


#        elif 'siteid' in self.kwargs:
#            objects = ApplicationHandle.objects.filter(ResourceID__exact=self.kwargs['siteid'])
#            serializer = Software_Community_Serializer(objects, many=True)
        elif 'appname' in self.kwargs:
            objects = ApplicationHandle.objects.filter(
                ApplicationEnvironment__AppName__exact=uri_to_iri(
                    self.kwargs['appname']))
            serializer = Software_Community_Serializer(objects, many=True)
        else:
            objects = ApplicationHandle.objects.all()
            serializer = Software_Community_Serializer(objects, many=True)
        return Response(serializer.data)
예제 #2
0
 def get(self, request, format=None, **kwargs):
     returnformat = request.query_params.get('format', None)
     active_resourceids = RDR_Active_Resources(affiliation='XSEDE',
                                               allocated=True,
                                               type='ALL',
                                               result='RESOURCEID')
     if 'info_siteid' in self.kwargs:
         try:
             sort_by = request.GET.get('sort')
             objects = RDRResource.objects.filter(
                 rdr_type='resource').filter(info_siteid__exact=uri_to_iri(
                     self.kwargs['info_siteid'])).order_by(sort_by)
         except:
             objects = RDRResource.objects.filter(
                 rdr_type='resource').filter(info_siteid__exact=uri_to_iri(
                     self.kwargs['info_siteid']))
     else:
         try:
             sort_by = request.GET.get('sort')
             objects = RDRResource.objects.filter(
                 rdr_type='resource').order_by(sort_by)
         except:
             objects = RDRResource.objects.filter(
                 rdr_type='resource').order_by('info_resourceid')
     for o in objects:
         o.Active = o.info_resourceid in active_resourceids
     serializer = RDRResource_Serializer_Plus(objects,
                                              context={'request': request},
                                              many=True)
     if returnformat != 'html':
         return Response(serializer.data)
     else:
         return render(request, 'warehouse_views/warehouse_resources.html',
                       {'resource_list': serializer.data})
예제 #3
0
def convert_gif_to_webm(link, file, ext, post_id):
    """
    Конвертим гифки в webm
    """
    clip = VideoFileClip(file)
    w, h = clip.size
    webm = BeautifulSoup("", "html5lib").new_tag("video")
    webm['autoplay'] = ""
    webm['loop'] = ""
    webm['controls'] = ""
    webm['style'] = "max-width: " + str(w) + "px;"
    source = BeautifulSoup("", "html5lib").new_tag("source")
    if ext == "webm":
        source['src'] = "/media" + link.group()
    else:
        file_out = uri_to_iri(
            "/root/myblog/myblog/blog/static/media/{}/{}/{}/{}-{}.webm".format(
                link.group("year"), link.group("month"), link.group("day"),
                link.group("file"), str(post_id)))
        link_out = uri_to_iri('/media/{}/{}/{}/{}-{}.webm'.format(
            link.group("year"), link.group("month"), link.group("day"),
            link.group("file"), str(post_id)))

        clip = VideoFileClip(file)
        video = CompositeVideoClip([clip])
        video.write_videofile(file_out,
                              codec='libvpx',
                              audio=False,
                              preset='superslow')

        source['src'] = link_out
    source['type'] = "video/webm"
    webm.insert(0, source)

    return webm
예제 #4
0
    def test_uri_to_iri(self):
        cases = [
            (None, None),
            # Valid UTF-8 sequences are decoded.
            ("/%e2%89%Ab%E2%99%a5%E2%89%aB/", "/≫♥≫/"),
            ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"),
            ("/%41%5a%6B/", "/AZk/"),
            # Reserved and non-URL valid ASCII chars are not decoded.
            ("/%25%20%02%41%7b/", "/%25%20%02A%7b/"),
            # Broken UTF-8 sequences remain escaped.
            ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"),
            ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"),
            ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"),
            ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"),
            (
                "/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93",
                "/♥♥/?utf8=%9C%93✓%9C%93",
            ),
        ]

        for uri, iri in cases:
            with self.subTest(uri):
                self.assertEqual(uri_to_iri(uri), iri)

                # Test idempotency.
                self.assertEqual(uri_to_iri(uri_to_iri(uri)), iri)
예제 #5
0
    def test_complementarity(self):
        cases = [
            (
                "/blog/for/J%C3%BCrgen%20M%C3%BCnster/",
                "/blog/for/J\xfcrgen%20M\xfcnster/",
            ),
            ("%&", "%&"),
            ("red&%E2%99%A5ros%#red", "red&♥ros%#red"),
            ("/%E2%99%A5%E2%99%A5/", "/♥♥/"),
            ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"),
            ("/%25%20%02%7b/", "/%25%20%02%7b/"),
            ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"),
            ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"),
            ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"),
            ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"),
            (
                "/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93",
                "/♥♥/?utf8=%9C%93✓%9C%93",
            ),
        ]

        for uri, iri in cases:
            with self.subTest(uri):
                self.assertEqual(iri_to_uri(uri_to_iri(uri)), uri)
                self.assertEqual(uri_to_iri(iri_to_uri(iri)), iri)
예제 #6
0
 def test_with_user_not_logged(self):
     self.client.logout()
     response = self.client.get(self.url)
     from django.utils.encoding import uri_to_iri
     self.assertEqual(uri_to_iri(uri_to_iri(response.url)),
                      '/login/?next={}'.format(self.url))
     self.assertEqual(response.status_code, 302)
예제 #7
0
    def get_context_data(self, **kwargs):
        context = super(Search, self).get_context_data(**kwargs)

        context['query'] = uri_to_iri(self.kwargs.get('query'))
        busqueda = context['query']

        print uri_to_iri(busqueda)
        return context
예제 #8
0
    def save(self, without_valid=False, *args, **kwargs):
        p = Pinyin()
        full_pinyin = p.get_pinyin(smart_str(self.title), '')
        first_pinyin = p.get_initials(smart_str(self.title), '').lower()
        self.search_word = " ".join([full_pinyin, first_pinyin])
        update_logger.info('video path: ' + str(self.video))

        if self.description is None or self.description == "":
            self.description = default_description(self)

        if self.local_video != '' and self.local_video is not None:
            basename = Path(self.local_video).relative_to(
                Path(settings.LOCAL_MEDIA_ROOT))
            self.video.name = str(Path(settings.LOCAL_MEDIA_URL) / basename)
            update_logger.debug("save local_video to filefield done")

        if without_valid:
            ret = super(Vod, self).save(*args, **kwargs)
            return ret
        super(Vod, self).save(*args, **kwargs)

        if os.path.splitext(str(self.video))[1] not in ['.mp4', '.m3u8']:
            p = threading.Thread(target=ff, args=(self, ))
            p.start()

        try:
            if self.video != None and self.video != '':
                relative_path = Path(self.video.name).relative_to(
                    settings.MEDIA_URL)  # Djan%20go.mp4
                rel_name = uri_to_iri(relative_path)  # Djan go.mp4

                #  Make sure the self.video.name is not in the LOCAL_FOLDER
                if not self.video.name.startswith(settings.LOCAL_FOLDER_NAME) and \
                        not self.video.name.startswith(settings.RECORD_MEDIA_FOLDER):
                    self.video.name = str(rel_name)
                update_logger.info('save path: ' + self.save_path)
                update_logger.info('video name: ' + str(self.video.name))
                update_logger.info('size: ' + self.video.file.size)
                self.file_size = humanfriendly.format_size(
                    self.video.file.size)
                # duration = VideoFileClip(self.video.path).duration
                # self.duration = time_formate(duration)
            else:
                print("video file is None")
        except:
            pass

        try:
            if self.image:
                self.image.name = str(
                    uri_to_iri(
                        Path(self.image.name).relative_to(settings.MEDIA_URL)))
        except:
            pass
        return super(Vod, self).save(*args, **kwargs)
예제 #9
0
def path_to_iri(path):
    '''
    OS-independant attempt at converting any OS absolute path to an
    RFC3987-defined IRI along with the file scheme from RFC8089.
    '''
    # Looking to see if the path starts with a drive letter or UNC path
    # (eg. 'D:\' or '\\')
    windows = re.match(r'^(?:[A-Za-z]:|\\)\\', path)
    if windows:
        return uri_to_iri(urljoin('file:', ntpathname2url(path)))
    return uri_to_iri(urljoin('file:', pathname2url(path)))
예제 #10
0
    def wrap(request, *args, **kwargs):
        if 'country' in kwargs:
            kwargs['country'] = uri_to_iri(kwargs['country'])

        if 'voivodeship' in kwargs:
            kwargs['voivodeship'] = uri_to_iri(kwargs['voivodeship'])

        if 'county' in kwargs:
            kwargs['county'] = uri_to_iri(kwargs['county'])

        return function(request, *args, **kwargs)
예제 #11
0
def strip_media_from_path(file):
    """
    Удаляем "media/" из путей к файлам
    """
    if re.search(r"^/media/", file):
        path = file.split(os.sep)[2:]
        new_path = ""
        for i in path:
            new_path = os.path.join(new_path, i)
        return uri_to_iri(new_path)
    else:
        return uri_to_iri(file)
예제 #12
0
 def get(self, request, format=None, **kwargs):
     if 'about' in self.kwargs:
         try:
             object = ProcessingRecord.objects.filter(About__exact=uri_to_iri(self.kwargs['about'])).latest('ProcessingStart')
         except ProcessingRecord.DoesNotExist:
             raise MyAPIException(code=status.HTTP_404_NOT_FOUND, detail='Specified about not found')
     elif 'topic' in self.kwargs:
         try:
             object = ProcessingRecord.objects.filter(Topic__exact=uri_to_iri(self.kwargs['topic'])).latest('ProcessingStart')
         except ProcessingRecord.DoesNotExist:
             raise MyAPIException(code=status.HTTP_404_NOT_FOUND, detail='Specified topic not found')
     else:
         raise MyAPIException(code=status.HTTP_404_NOT_FOUND, detail='Not found')
     serializer = ProcessingRecord_DbSerializer(object)
     return MyAPIResponse({'record_list': [serializer.data]}, template_name='processing_status/detail.html')
예제 #13
0
    def save(self, without_valid=False, *args, **kwargs):
        print("------- save vod -------")
        p = Pinyin()
        full_pinyin = p.get_pinyin(smart_str(self.title), '')
        first_pinyin = p.get_initials(smart_str(self.title), '').lower()
        self.search_word = " ".join([full_pinyin, first_pinyin])
        print("video path:", self.video)

        if self.description is None or self.description == "":
            self.description = default_description(self)

        if self.local_video != '' and self.local_video is not None:
            basename = Path(self.local_video).relative_to(Path(settings.LOCAL_MEDIA_ROOT))
            self.video.name = str(Path(settings.LOCAL_MEDIA_URL) / basename)
            print("save local_video to filefield done")

        if without_valid:
            ret = super(Vod, self).save(*args, **kwargs)
            return ret
        super(Vod, self).save(*args, **kwargs)
        try:
            if self.video != None and self.video != '':
                basename = Path(self.video.name).name  # Djan%20go.mp4
                rel_name = uri_to_iri(basename)  # Djan go.mp4

                #  Make sure the self.video.name is not in the LOCAL_FOLDER
                if not self.video.name.startswith(settings.LOCAL_FOLDER_NAME) and \
                        not self.video.name.startswith(settings.RECORD_MEDIA_FOLDER):
                    self.video.name = str(Path(self.save_path) / rel_name)
                print("save_path:", self.save_path)
                print(self.video.name)
                print('size:', self.video.file.size)
                self.file_size = humanfriendly.format_size(self.video.file.size)
                # duration = VideoFileClip(self.video.path).duration
                # self.duration = time_formate(duration)
                # print(self.duration)
            else:
                print("video file is None")
        except:
            pass

        try:
            if self.image:
                # self.image.name = os.path.join(self.save_path, os.path.basename(uri_to_iri(self.image.name)))
                self.image.name = Path(self.save_path) / Path(uri_to_iri(self.image.name)).name
        except:
            pass
        return super(Vod, self).save(*args, **kwargs)
예제 #14
0
def make_srcsets(text, wrap_a, post_id=None):
    """
    Создаём srcsetы из картинок
    Аргументы:
    Принимает текст поста, оборачивать ли картинку в ссылку и опционально id поста
    Возвращает готовый html код
    """
    soup = BeautifulSoup(uri_to_iri(text), "html5lib")  # текст поста

    img_links = find_img(soup)

    if len(img_links) != 0:
        for img in img_links:
            # находим ссылку, файл и вых. файл
            del img['style']  # удаляем стиль

            link = find_link(iri_to_uri(img))
            file = uri_to_iri(find_file(link))
            original_pic = uri_to_iri('/media/{}/{}/{}/{}.{}'.format(
                link.group("year"), link.group("month"), link.group("day"),
                link.group("file"), link.group("ext")))

            if os.path.isfile(file):

                img['class'] = 'responsive-img post-image'
                ext = img['src'].split('.')[-1].lower()

                if ext == "gif" or ext == "webm":
                    webm = convert_gif_to_webm(link, file, ext, post_id)
                    img.replaceWith(webm)
                    # if ext == "gif":
                    #    os.remove(file)
                else:
                    # если картинка больше нужного размера создаём миниатюру
                    srcset, alt = convert_img_to_srcset(
                        link, file, original_pic, src_szs)
                    img['srcset'] = srcset
                    img['src'] = alt
                    img['sizes'] = "60vw"

                    if wrap_a:
                        a_tag = soup.new_tag("a")
                        # оборачиваем в ссылку на оригинал
                        a_tag['href'] = original_pic
                        a_tag['data-gallery'] = ""
                        # img = img.wrap(a_tag)

    return soup
예제 #15
0
def preview(request, token):
    pk = decode_token_to_pk(token)
    link = get_object_or_404(Link, pk=pk)
    token_uri = reverse('token_redirect', args=[token])
    short_url = request.build_absolute_uri(token_uri)
    short_iri = uri_to_iri(short_url)  # this is the more human-readable form
    full_iri = uri_to_iri(link.url)  # this is the more human-readable form
    context = {
        'token': token,
        'short_iri': short_iri,
        'short_url': short_url,
        'full_url': link.url,
        'full_iri': full_iri,
        'characters_saved': len(full_iri) - len(short_iri),
    }
    return render(request, 'preview.html', context)
예제 #16
0
 def thumbnail(self, obj):
     img = Item.objects.filter(id=obj.id)
     all_thumbs = ""
     for i in range(img.count()):
         url = uri_to_iri(img[i].image)
         all_thumbs = all_thumbs + '<img src="' + url + '" style="height:85px; width:auto;" />'
     return all_thumbs
예제 #17
0
        def to_internal_value(self, data):
            self.source_attrs = ['source']  # Must set

            # Was the value already entered?
            if isinstance(data, Adjudicator) or isinstance(data, Team):
                return data

            try:
                http_prefix = data.startswith(('http:', 'https:'))
            except AttributeError:
                self.fail('incorrect_type', data_type=type(data).__name__)

            if http_prefix:
                # If needed convert absolute URLs to relative path
                data = parse.urlparse(data).path
                prefix = get_script_prefix()
                if data.startswith(prefix):
                    data = '/' + data[len(prefix):]

            data = uri_to_iri(data)
            try:
                match = resolve(data)
            except Resolver404:
                self.fail('no_match')

            self.model = {
                'api-adjudicator-detail': Adjudicator,
                'api-team-detail': Team,
            }[match.view_name]

            try:
                return self.get_object(match.view_name, match.args,
                                       match.kwargs)
            except self.model.DoesNotExist:
                self.fail('does_not_exist')
예제 #18
0
파일: views.py 프로젝트: siadyhr/web
    def get_redirect_url(self, *args, **kwargs):

        folder = self.request.GET.get('folder', '')
        # Some of the old string are double encoded.
        folder = uri_to_iri(folder)

        if not folder:
            logger.warning('GalleryShowFolderRedirectView: The \'folder\' '
                           'request parameter cold not be parsed. Returning '
                           '410. \'folder\' doubledecoded was %s' % (folder))
            # The old page prints a load of garbage. This will
            # return a 410 GONE instead.
            return None

        albums = Album.objects.filter(oldFolder__startswith = folder)
        if not albums:
            logger.warning('GalleryShowFolderRedirectView: The album could '
                           'not be found when comparing the \'folder\' '
                           'request parameter with \'oldFolder\' on albums. '
                           'Returning 404. \'folder\' doubledecoded was %s'
                           % (folder))
            raise Http404("Albummet kan ikke findes")

        gfyear = albums[0].gfyear
        album_slug = albums[0].slug
        return reverse('album', kwargs={'gfyear': gfyear,
                                        'album_slug': album_slug})
    def get_RDR_Declared_Status(self, RDRResource):
        if RDRResource.latest_status in ['production']:
            self.RDR_Label = 'Green'
        elif RDRResource.latest_status in [
                'post-production', 'pre-production', 'friendly'
        ]:
            self.RDR_Label = 'Yellow'
        else:
            self.RDR_Label = 'Red'
        self.RDR_Summary = 'In "{}"'.format(RDRResource.latest_status)
        if RDRResource.latest_status_begin:
            self.RDR_Summary += ' starting {}'.format(
                RDRResource.latest_status_begin)
        if RDRResource.latest_status_end:
            self.RDR_Summary += ' until {}'.format(
                RDRResource.latest_status_end)

        http_request = self.context.get("request")
        if http_request:
            RDR_URL = http_request.build_absolute_uri(
                uri_to_iri(
                    reverse('rdr-detail', args=[RDRResource.rdr_resource_id])))
        else:
            RDR_URL = ''

        return {
            'Label': self.RDR_Label,
            'Declared_Status': RDRResource.latest_status,
            'Declared_Status_Begin': RDRResource.latest_status_begin,
            'Declared_Status_End': RDRResource.latest_status_end,
            'Summary': self.RDR_Summary,
            'References_URLs': RDR_URL
        }
예제 #20
0
 def get_queryset(self):
     search_word = self.request.GET.get("word")
     if not search_word:
         return Word.objects.filter(is_not_display=False,
                                    user=self.request.user)
     return Word.objects.filter(word__icontains=uri_to_iri(search_word),
                                user=self.request.user)
예제 #21
0
    def to_internal_value(self, data):
        try:
            http_prefix = data.startswith(('http:', 'https:'))
        except AttributeError:
            self.fail('incorrect_type', data_type=type(data).__name__)

        if http_prefix:
            # If needed convert absolute URLs to relative path
            data = parse.urlparse(data).path
            prefix = get_script_prefix()
            if data.startswith(prefix):
                data = '/' + data[len(prefix):]

        data = uri_to_iri(parse.unquote(data))

        try:
            match = resolve(data)
        except Resolver404:
            self.fail('no_match')

        if match.view_name.split("-")[1] not in [
                'team', 'adjudicator', 'venue'
        ]:
            self.fail('incorrect_match')

        try:
            return self.get_object(match.view_name, match.args, match.kwargs)
        except (ObjectDoesNotExist, ValueError, TypeError):
            self.fail('does_not_exist')
예제 #22
0
def test(request):
    #if request.method == 'POST':
    '''
    json_data="""
    [{ "no":"1000",
    "location":[
    {"lat":122.5, "lon" : 56.7},
    {"lat":124.5, "lon" : 55.7}
    ],
    "inter":
    }
    ]
    """
    '''
    jdata = json.loads(request.body.decode("utf-8"))
    #jdata = json.loads(json_data)
    for i in range(len(jdata)) :
        for j in range(len(jdata[i]['location'])):
            t_inter = jdata[i]['inter']
            tmp_msg = uri_to_iri(t_inter)
            inter = tmp_msg.encode('utf8')
            data = record.objects.create(
            lon=jdata[i]['location'][j]['lon'],
            lat=jdata[i]['location'][j]['lat'],
            no=jdata[i]['no'],
            inter=inter
            )
            data.save()

    return HttpResponse("Received Successfully.")
예제 #23
0
 def delete(self, request, pk, format=None):
     try:
         object = ApplicationHandle.objects.get(pk=uri_to_iri(pk))
     except ApplicationHandle.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
     object.delete()
     return Response(status=status.HTTP_204_NO_CONTENT)
예제 #24
0
    def get(self, request, pk, format=None):
        try:
            object = ApplicationHandle.objects.get(pk=uri_to_iri(pk))
        except ApplicationHandle.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
#        serializer = ApplicationHandle_DbSerializer(object, context={'request', request})
        return Response(ApplicationHandle_DbSerializer(object).data)
예제 #25
0
 def delete(self, request, pk, format=None):
     try:
         object = AcceleratorEnvironment.objects.get(pk=uri_to_iri(pk))
     except AcceleratorEnvironment.DoesNotExist:
         raise MyAPIException(code=status.HTTP_404_NOT_FOUND, detail='Not found')
     object.delete()
     return MyAPIResponse(None, code=status.HTTP_204_NO_CONTENT)
예제 #26
0
 def get(self, request, pk, format=None):
     try:
         object = AcceleratorEnvironment.objects.get(pk=uri_to_iri(pk)) # uri_to_iri translates %xx
     except AcceleratorEnvironment.DoesNotExist:
         raise MyAPIException(code=status.HTTP_404_NOT_FOUND, detail='Not found')
     serializer = AcceleratorEnvironment_DbSerializer(object)
     return MyAPIResponse({'results': [serializer.data]})
예제 #27
0
    def get(self, request, format=None, **kwargs):
        returnformat = request.query_params.get('format', 'json')
        #Note:  the query_param 'format' is used for magical things 
        #If we use it, it will work fine for json or html, but won't 
        #let us accept a random string as 'format' and still return json

        if 'resourceid' in self.kwargs:
            try:
                objects = RDRResource.objects.filter(info_resourceid__exact=uri_to_iri(self.kwargs['resourceid'])).filter(rdr_type__in=['compute','storage'])
            except RDRResource.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
        else:
            objects = RDR_Active_Resources(affiliation='XSEDE', allocated=True, type='SUB', result='OBJECTS')
        serializer = Resource_Status_Serializer(objects, context={'request': request}, many=True)
        if returnformat != 'html':
            #Thought I was having a problem when not specifying a format at all
            #was getting OrderedDict returned in browser instead of json.
            #Turns out, that's django magic when hitting the REST endpoint 
            #from a browser.  The following two lines will make it always
            #really return JSON, but we're not doing that in other views...
            #returnresponse =  JSONRenderer().render(serializer.data)
            #return Response(returnresponse)
            return Response(serializer.data)
        else:
            return render(request, 'resource_status_api/resources.html', {'resource_list': serializer.data})
    def get_Outage_Status(self, RDRResource):
        now = timezone.now()
        outsearch = Outages.objects.filter(
            ResourceID=RDRResource.info_resourceid,
            OutageStart__lte=now,
            OutageEnd__gte=now)
        outurls = set()
        Full_Outage = False
        http_request = self.context.get("request")
        for out in outsearch:
            if http_request:
                outurls.add(
                    http_request.build_absolute_uri(
                        uri_to_iri(
                            reverse('outages-detail', args=[out.OutageID]))))
            if out.OutageType.upper() == 'FULL':
                Full_Outage = True
        if Full_Outage:
            self.Outage_Label = 'Red'
            self.Outage_Summary = 'Full outage reported'
        elif outsearch:
            self.Outage_Label = 'Yellow'
            self.Outage_Summary = 'Partial outage repoted (%s)' % len(
                outsearch)
        else:
            self.Outage_Label = 'Green'
            self.Outage_Summary = ''

        return {
            'Label': self.Outage_Label,
            'Summary': self.Outage_Summary,
            'References_URLs': outurls
        }
예제 #29
0
    def to_internal_value(self, data):
        request = self.context.get('request', None)
        try:
            http_prefix = data.startswith(('http:', 'https:'))
        except AttributeError:
            self.fail('incorrect_type', data_type=type(data).__name__)

        if http_prefix:
            # If needed convert absolute URLs to relative path
            data = urlparse.urlparse(data).path
            prefix = get_script_prefix()
            if data.startswith(prefix):
                data = '/' + data[len(prefix):]

        data = uri_to_iri(data)

        try:
            match = resolve(data)
        except Resolver404:
            self.fail('no_match')

        try:
            expected_viewname = request.versioning_scheme.get_versioned_viewname(
                self.view_name, request
            )
        except AttributeError:
            expected_viewname = self.view_name

        if match.view_name != expected_viewname:
            self.fail('incorrect_match')

        try:
            return self.get_object(match.view_name, match.args, match.kwargs)
        except (ObjectDoesNotExist, TypeError, ValueError):
            self.fail('does_not_exist')
예제 #30
0
def directory_list(request, directory_slug, category_parent_slug):

    if directory_slug:
        directory_slug = uri_to_iri(directory_slug)

    if directory_slug is None:
        object = None
        root = getattr(settings, 'MEDIA_GALLERIES_ROOT', None)
        if root:
            obj_root = Folder.objects.get(name=root)
            object_list = Folder.objects.filter(parent=obj_root)
        else:
            object_list = Folder.objects.filter(parent=None)
    else:
        try:
            object = Folder.objects.get(id=directory_slug)
        except:
            object = Folder.objects.get(name=directory_slug)
        object_list = object.files.all()

    return render(
        request,
        'media/directory_list.html',
        {
            'object_list': object_list,
        }
    )
예제 #31
0
    def to_internal_value(self, data):
        request = self.context.get("request", None)
        try:
            http_prefix = data.startswith(("http:", "https:"))
        except AttributeError:
            self.fail("incorrect_type", data_type=type(data).__name__)

        if http_prefix:
            # If needed convert absolute URLs to relative path
            data = parse.urlparse(data).path
            prefix = get_script_prefix()
            if data.startswith(prefix):
                data = "/" + data[len(prefix) :]

        data = uri_to_iri(parse.unquote(data))

        try:
            match = resolve(data)
        except Resolver404:
            self.fail("no_match")

        try:
            expected_viewname = request.versioning_scheme.get_versioned_viewname(
                self.view_name, request
            )
        except AttributeError:
            expected_viewname = self.view_name

        if match.view_name != expected_viewname:
            self.fail("incorrect_match")

        try:
            return self.get_object(match.view_name, match.args, match.kwargs)
        except (ObjectDoesNotExist, ObjectValueError, ObjectTypeError):
            self.fail("does_not_exist")
 def get_DetailURL(self, Outages):
     http_request = self.context.get('request')
     if http_request:
         return http_request.build_absolute_uri(
             uri_to_iri(reverse('outages-detail', args=[Outages.ID])))
     else:
         return ''
예제 #33
0
        def to_internal_value(self, data):
            self.source_attrs = [self.field_source_name]  # Must set

            # Was the value already entered?
            if isinstance(data, tuple(model for model, field in self.models.values())):
                return data

            try:
                http_prefix = data.startswith(('http:', 'https:'))
            except AttributeError:
                self.fail('incorrect_type', data_type=type(data).__name__)

            if http_prefix:
                # If needed convert absolute URLs to relative path
                data = parse.urlparse(data).path
                prefix = get_script_prefix()
                if data.startswith(prefix):
                    data = '/' + data[len(prefix):]

            data = uri_to_iri(data)
            try:
                match = resolve(data)
            except Resolver404:
                self.fail('no_match')

            self.model = {view: model for view, (model, field) in self.models.items()}[match.view_name]

            try:
                return self.get_object(match.view_name, match.args, match.kwargs)
            except self.model.DoesNotExist:
                self.fail('does_not_exist')
예제 #34
0
    def test_complementarity(self):
        cases = [
            ('/blog/for/J%C3%BCrgen%20M%C3%BCnster/', '/blog/for/J\xfcrgen M\xfcnster/'),
            ('%&', '%&'),
            ('red&%E2%99%A5ros%#red', 'red&♥ros%#red'),
            ('/%E2%99%A5%E2%99%A5/', '/♥♥/'),
            ('/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93', '/♥♥/?utf8=✓'),
            ('/%AAd%AAj%AAa%AAn%AAg%AAo%AA/', '/%AAd%AAj%AAa%AAn%AAg%AAo%AA/'),
            ('/%E2%99%A5%E2%E2%99%A5/', '/♥%E2♥/'),
            ('/%E2%99%A5%E2%99%E2%99%A5/', '/♥%E2%99♥/'),
            ('/%E2%E2%99%A5%E2%99%A5%99/', '/%E2♥♥%99/'),
            ('/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93', '/♥♥/?utf8=%9C%93✓%9C%93'),
        ]

        for uri, iri in cases:
            self.assertEqual(iri_to_uri(uri_to_iri(uri)), uri)
            self.assertEqual(uri_to_iri(iri_to_uri(iri)), iri)
예제 #35
0
    def test_complementarity(self):
        cases = [
            ("/blog/for/J%C3%BCrgen%20M%C3%BCnster/", "/blog/for/J\xfcrgen M\xfcnster/"),
            ("%&", "%&"),
            ("red&%E2%99%A5ros%#red", "red&♥ros%#red"),
            ("/%E2%99%A5%E2%99%A5/", "/♥♥/"),
            ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"),
            ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"),
            ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"),
            ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"),
            ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"),
            ("/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93", "/♥♥/?utf8=%9C%93✓%9C%93"),
        ]

        for uri, iri in cases:
            self.assertEqual(iri_to_uri(uri_to_iri(uri)), uri)
            self.assertEqual(uri_to_iri(iri_to_uri(iri)), iri)
예제 #36
0
    def test_uri_to_iri(self):
        cases = [
            # Valid UTF-8 sequences are decoded.
            ("/%E2%99%A5%E2%99%A5/", "/♥♥/"),
            ("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93", "/♥♥/?utf8=✓"),
            # Broken UTF-8 sequences remain escaped.
            ("/%AAd%AAj%AAa%AAn%AAg%AAo%AA/", "/%AAd%AAj%AAa%AAn%AAg%AAo%AA/"),
            ("/%E2%99%A5%E2%E2%99%A5/", "/♥%E2♥/"),
            ("/%E2%99%A5%E2%99%E2%99%A5/", "/♥%E2%99♥/"),
            ("/%E2%E2%99%A5%E2%99%A5%99/", "/%E2♥♥%99/"),
            ("/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93", "/♥♥/?utf8=%9C%93✓%9C%93"),
        ]

        for uri, iri in cases:
            self.assertEqual(uri_to_iri(uri), iri)

            # Test idempotency.
            self.assertEqual(uri_to_iri(uri_to_iri(uri)), iri)
 def build_bib_dct( self, querystring ):
     """ Calls bibjsontools.
         Called by views.availability() """
     log.debug( 'querystring, ```{}```'.format(querystring) )
     log.debug( 'type(querystring), `{}`'.format(type(querystring)) )
     assert type(querystring) == unicode
     iri_querystring = uri_to_iri( querystring )
     bib_dct = bibjsontools.from_openurl( iri_querystring )
     log.debug( 'bib_dct, ```{}```'.format(pprint.pformat(bib_dct)) )
     return bib_dct
예제 #38
0
파일: client.py 프로젝트: aetos1918/Django
 def _get_path(self, parsed):
     path = force_str(parsed[2])
     # If there are parameters, add them
     if parsed[3]:
         path += str(";") + force_str(parsed[3])
     path = uri_to_iri(path).encode(UTF_8)
     # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily
     # decoded with ISO-8859-1. We replicate this behavior here.
     # Refs comment in `get_bytes_from_wsgi()`.
     return path.decode(ISO_8859_1) if six.PY3 else path
예제 #39
0
def post_test2_4(request):
	#srcData  = {'Name':'김성환'}
	#response = JsonResponse(srcData, safe=False)
	#print(response.content)
	#return HttpResponse(response.content)
	
	destData = json.loads(uri_to_iri(b'''{"Name": "\uae40\uc131\ud658"}'''))
	#destData = json.loads('''{"Name": "김성환"}''')
	print(destData)
	return HttpResponse(destData['Name'])
예제 #40
0
 def _get_path(self, parsed):
     path = parsed.path
     # If there are parameters, add them
     if parsed.params:
         path += ";" + parsed.params
     path = uri_to_iri(path).encode(UTF_8)
     # Replace the behavior where non-ASCII values in the WSGI environ are
     # arbitrarily decoded with ISO-8859-1.
     # Refs comment in `get_bytes_from_wsgi()`.
     return path.decode(ISO_8859_1)
예제 #41
0
def incentivadorView(request):

    filter_args = {}
    link_args = u''
    form_initial = {}

    if request.method == 'POST':
        incentivador = IncentivadorForm(request.POST)

        if len(incentivador.data['cgccpf']) > 0:
            filter_args['cgccpf'] = incentivador.data['cgccpf']

        if len(incentivador.data['nome']) > 0:
            filter_args['nome'] = incentivador.data['nome']


        if incentivador.data['tipo_pessoa'] != 'tipodepessoa':
            filter_args['tipo_pessoa'] = incentivador.data['tipo_pessoa']

        if incentivador.data['UF'] != 'ESTADO':
            filter_args['UF'] = incentivador.data['UF']

        if len(incentivador.data['municipio']) > 0:
            filter_args['municipio'] = incentivador.data['municipio']

        form_initial = filter_args.copy()

        for key in filter_args:
            link_args += key+"="+filter_args[key]+"&"


    if request.method == 'GET':
        query_params = request.META['QUERY_STRING'].split('&')
        #   print 'Query params : ' + str(query_params)

        for param in query_params:
            if param != '':
                k, v = param.split('=')
                form_initial[k] = uri_to_iri(v)
                if k != 'page'  and k != 'sort' and k != 'captacao'  and k != 'conclusao':
                    filter_args[k] = v

        #print 'filter_args : ' + str(filter_args)

    incentivadores = Incentivador.objects.filter(**filter_args)


    table = IncentivadorTable(incentivadores)
    table.link_args = link_args
    table.data.verbose_name_plural = 'Incentivadores'
    table.data.verbose_name = 'Incentivador'
    RequestConfig(request, paginate={"per_page": 10}).configure(table)

    return render(request, 'incentivador.html', {'table' : table, "link" : "/incentivadores/", 'searchForm' : IncentivadorForm(form_initial)})
예제 #42
0
    def test_uri_to_iri(self):
        cases = [
            # Valid UTF-8 sequences are decoded.
            ('/%e2%89%Ab%E2%99%a5%E2%89%aB/', '/≫♥≫/'),
            ('/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93', '/♥♥/?utf8=✓'),
            ('/%41%5a%6B/', '/AZk/'),
            # Reserved and non-URL valid ASCII chars are not decoded.
            ('/%25%20%02%41%7b/', '/%25%20%02A%7b/'),
            # Broken UTF-8 sequences remain escaped.
            ('/%AAd%AAj%AAa%AAn%AAg%AAo%AA/', '/%AAd%AAj%AAa%AAn%AAg%AAo%AA/'),
            ('/%E2%99%A5%E2%E2%99%A5/', '/♥%E2♥/'),
            ('/%E2%99%A5%E2%99%E2%99%A5/', '/♥%E2%99♥/'),
            ('/%E2%E2%99%A5%E2%99%A5%99/', '/%E2♥♥%99/'),
            ('/%E2%99%A5%E2%99%A5/?utf8=%9C%93%E2%9C%93%9C%93', '/♥♥/?utf8=%9C%93✓%9C%93'),
        ]

        for uri, iri in cases:
            self.assertEqual(uri_to_iri(uri), iri)

            # Test idempotency.
            self.assertEqual(uri_to_iri(uri_to_iri(uri)), iri)
예제 #43
0
파일: basehttp.py 프로젝트: AlfiyaZi/django
    def get_environ(self):
        env = super(WSGIRequestHandler, self).get_environ()

        path = self.path
        if '?' in path:
            path = path.partition('?')[0]

        path = uri_to_iri(path).encode(UTF_8)
        # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily
        # decoded with ISO-8859-1. We replicate this behavior here.
        # Refs comment in `get_bytes_from_wsgi()`.
        env['PATH_INFO'] = path.decode(ISO_8859_1) if six.PY3 else path

        return env
예제 #44
0
 def get(self, request, *args, **kwargs):
     if 'ps_q' in request.GET:
         # Keeping Unicode in URL, replacing space with '+'
         query = uri_to_iri(urlquote_plus(request.GET['ps_q']))
         params = {'query': query} if query else None
         return HttpResponseRedirect(reverse_lazy('search', kwargs=params))
     query = kwargs['query'] or ''  # Avoiding query=None
     self.query = unquote_plus(query)
     if self.query:
         try:
             geocoder = geopy.geocoders.OpenCage(settings.OPENCAGE_KEY, timeout=5)
             self.locations = geocoder.geocode(self.query, language=lang, exactly_one=False)
         except (GeocoderTimedOut, GeocoderServiceError) as e:
             self.locations = []
     return super(SearchView, self).get(request, *args, **kwargs)
예제 #45
0
def post_test2_1(request):
	#absname   = os.path.dirname(os.path.abspath(__file__)) + r'\static\text\test.txt'	# 절대경로
	#response  = FileResponse(open(absname, 'rb'))
	#return HttpResponse(response)
	
	#localname = 'blog/static/text/test.txt'											# 상대경로
	#response  = FileResponse(open(localname, 'rb'))
	#return HttpResponse(response)

	#request.encoding = 'koi8-r'
	text = '''name='김성환'&age=43'''
	url  = iri_to_uri(text)
	org  = uri_to_iri(url)
	print('text -> url : ', url)
	print('url -> text : ', org)
	return HttpResponse('')
예제 #46
0
def proponenteView(request):

    filter_args = {}
    link_args = u''
    form_initial = {}

    if request.method == 'POST':
        proponente = ProponenteForm(request.POST)

        if len(proponente.data['cgccpf']) > 0:
            filter_args['cgccpf'] = proponente.data['cgccpf']

        if len(proponente.data['nome']) > 0:
            filter_args['nome'] = proponente.data['nome']


        if proponente.data['tipo_pessoa'] != 'tipodepessoa':
            filter_args['tipo_pessoa'] = proponente.data['tipo_pessoa']

        if proponente.data['UF'] != 'ESTADO':
            filter_args['UF'] = proponente.data['UF']

        if len(proponente.data['municipio']) > 0:
            filter_args['municipio'] = proponente.data['municipio']

        form_initial = filter_args.copy()

        for key in filter_args:
            link_args += key+"="+filter_args[key]+"&"

    if request.method == 'GET':
        query_params = request.META['QUERY_STRING'].split('&')
        #   print 'Query params : ' + str(query_params)

        for param in query_params:
            if param != '':
                k, v = param.split('=')
                form_initial[k] = uri_to_iri(v)
                if k != 'page'  and k != 'sort' and k != 'captacao'  and k != 'conclusao':
                    filter_args[k] = v

        #print 'filter_args : ' + str(filter_args)

    table = ProponenteTable()
    table.data_url+=link_args

    return render(request, 'proponente.html', {'table' : table, 'searchForm' : ProponenteForm(form_initial)})
예제 #47
0
def post_test3_1(request):
	print(uri_to_iri('http://127.0.0.1:8000/post/test3_1/?name=%EA%B9%80%EC%84%B1%ED%99%98&age=43'))
	print(iri_to_uri('http://127.0.0.1:8000/post/test3_1/?name=김성환&age=43'))
	print('경로명 합치기 : ', os.path.join(r'D:\WorkRoom', r'Django', r'girls\blog'))			# D:\WorkRoom\Django\girls\blog
	print('중간 경로 슬래쉬 제거 : ', os.path.normpath(r'D:\WorkRoom\Django\..\girls\blog'))	# D:\WorkRoom\girls\blog
	
	currpath   = os.getcwd()
	absolutely = os.path.abspath(__file__)
	relatively = os.path.relpath(absolutely, currpath)
	dirname    = os.path.dirname(absolutely)
	filename   = os.path.basename(__file__)
	name       = request.GET.get('name', '')
	age        = request.GET.get('age', 0)
	template   = Template('''
	<html>
		<head>
			<title>{{ module_name }}</title>
		</head>
		<body>
			<ol>				
				<li><strong>현재 실행경로 : {{ currpath }}</strong></li>
				<li><strong>파일 절대경로 : {{ absolutely }}</strong></li>
				<li><strong>파일 상대경로 : {{ relatively }}</strong></li>
				<li><strong>폴더 절대경로 : {{ dirname }}</strong></li>
				<li><strong>파일명 : {{ filename }}</strong></li>
				<li><strong>이름 : {{ name }}</strong></li>
				<li><strong>나이 : {{ age }}</strong></li>
			</ol>
		</body>
	</html>
	''')
	context = Context({
		'module_name':__name__,
		'currpath':currpath.replace('\\', '/'),
		'absolutely':absolutely.replace('\\', '/'),
		'relatively':relatively.replace('\\', '/'),
		'dirname':dirname.replace('\\', '/'),
		'filename':filename,
		'name':name,
		'age':age})
	return HttpResponse(template.render(context))
예제 #48
0
    def get_environ(self):
        # Strip all headers with underscores in the name before constructing
        # the WSGI environ. This prevents header-spoofing based on ambiguity
        # between underscores and dashes both normalized to underscores in WSGI
        # env vars. Nginx and Apache 2.4+ both do this as well.
        for k, v in self.headers.items():
            if '_' in k:
                del self.headers[k]

        env = super(WSGIRequestHandler, self).get_environ()

        path = self.path
        if '?' in path:
            path = path.partition('?')[0]

        path = uri_to_iri(path).encode(UTF_8)
        # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily
        # decoded with ISO-8859-1. We replicate this behavior here.
        # Refs comment in `get_bytes_from_wsgi()`.
        env['PATH_INFO'] = path.decode(ISO_8859_1) if six.PY3 else path

        return env
예제 #49
0
def projetosSearch(request):

    filter_args = {}
    link_args = u''
    form_initial = {}

    if request.method == 'POST':

        if  'submit' in request.POST:

            projeto = ProjetoForm(request.POST)

            if len(projeto.data['PRONAC']) > 0:
                filter_args['PRONAC'] = projeto.data['PRONAC']

            if len(projeto.data['cgccpf']) > 0:
                filter_args['cgccpf'] = projeto.data['cgccpf']

            if projeto.data['segmento'] != 'SEGMENTO':
                filter_args['segmento'] = projeto.data['segmento']

            if projeto.data['area'] != 'AREA':
                filter_args['area'] = projeto.data['area']

            if projeto.data['UF'] != 'ESTADO':
                filter_args['UF'] = projeto.data['UF']

            if projeto.data['ano_projeto'] != 'ano_projeto':
                filter_args['ano_projeto'] = projeto.data['ano_projeto']

            for key in filter_args:
                link_args += key+"="+filter_args[key]+"&"

            form_initial = filter_args.copy()

            if len(projeto.data['municipio']) > 0:
                filter_args['municipio__icontains'] = projeto.data['municipio']
                link_args +='municipio='+projeto.data['municipio']+'&'
                form_initial['municipio'] = projeto.data['municipio']

            if len(projeto.data['nome']) > 0:
                filter_args['nome__icontains'] = projeto.data['nome']
                link_args +='nome='+projeto.data['nome']+'&'
                form_initial['nome'] = projeto.data['nome']

            if len(projeto.data['proponente']) > 0:
                filter_args['proponente__icontains'] = projeto.data['proponente']
                link_args +='proponente='+projeto.data['proponente']+'&'
                form_initial['proponente'] = projeto.data['proponente']


            if projeto.data['captacao'] != 'captacao':
                form_initial['captacao'] = projeto.data['captacao']

                if form_initial['captacao'] == 'comcaptacoes':
                    filter_args['valor_captado__gt'] = 0
                else:
                    filter_args['valor_captado'] = 0

                link_args+="captacao="+projeto.data['captacao']+"&"

            if projeto.data['conclusao'] != 'conclusao':
                form_initial['conclusao'] = projeto.data['conclusao']
                link_args+="conclusao="+projeto.data['conclusao']+"&"

            #print "link args : " + link_args

    if request.method == 'GET':
        query_params = request.META['QUERY_STRING'].split('&')
        #   print 'Query params : ' + str(query_params)

        for param in query_params:
            if param != '':
                k, v = param.split('=')
                form_initial[k] = uri_to_iri(v)
                if k != 'page'  and k != 'sort' and k != 'captacao'  and k != 'conclusao':
                    filter_args[k] = v

        #print 'filter_args : ' + str(filter_args)


    projetos = Projeto.objects.filter(**filter_args).order_by('PRONAC').reverse()

        #projetos = Projeto.objects.filter(**filter_args)


    table = ProjetoTable(projetos)
    table.link_args = link_args
    table.data.verbose_name_plural = 'Projetos'
    table.data.verbose_name = 'Projeto'
    RequestConfig(request, paginate={"per_page": 10}).configure(table)
    #print 'Form initial: '+str(form_initial)
    return render(request, 'projetos.html', {'table': table, 'searchForm' : ProjetoForm(initial=form_initial),
        "link" : "/projetos/"})
예제 #50
0
def directory_list_nested(request,
                          directory_slug=None,
                          parent_directory_slug=None,
                          grandparent_directory_slug=None):

    if directory_slug:
        directory_slug = uri_to_iri(directory_slug)

    if parent_directory_slug:
        parent_directory_slug = uri_to_iri(parent_directory_slug)

    if directory_slug is None:
        object = None
        root = getattr(settings, 'MEDIA_GALLERIES_ROOT', None)
        if root:
            obj_root = Folder.objects.get(name=root)
            object_list = Folder.objects.filter(parent=obj_root)
        else:
            object_list = Folder.objects.filter(parent=None)
    else:
        if parent_directory_slug is None:
            try:
                object = Folder.objects.get(id=directory_slug)
            except:
                object = Folder.objects.get(name=directory_slug)
            object_list = object.files.all()
        else:
            if grandparent_directory_slug is None:
                object = Folder.objects.get(
                    name=directory_slug, parent__name=parent_directory_slug)
                object_list = object.files.all()
            else:
                object = Folder.objects.get(
                    name=directory_slug,
                    parent__name=parent_directory_slug,
                    parent__parent__name=grandparent_directory_slug)
                object_list = object.files.all()

    paginator = Paginator(object_list, config.MEDIA_PAGINATE_BY)

    page = request.GET.get('page')
    try:
        object_list = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        object_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        object_list = paginator.page(paginator.num_pages)

    return render(
        request,
        'media/directory_list_nested.html',
        {
            'object_list': object_list,
            'object': object,
            # TODO: filter permissions, this exposes private folders
            'folders': (object.media_folder_children.all().order_by(
                        *config.MEDIA_FOLDERS_ORDER_BY.split(","))
                        if config.MEDIA_LIST_SHOW_DIRS
                        else [])
        }
    )
예제 #51
0
파일: views.py 프로젝트: Atvo/DoWWWSHeroku
def newReply(request):
	#print("newReply")
	if request.method == 'POST':
		context = RequestContext(request)
		#print(request)
		form = ReplyForm(request.POST or None)

		if form.is_valid():
			#print(form.cleaned_data)

			serializedStr = uri_to_iri(request.POST)
			#print(serializedStr)
			arr = serializedStr.split("&")
			#arr = json.loads(serializedStr)
			#print("ARR")
			#postMessage = arr[0].split("=")[1].replace("+", " ")
			#postMessage = arr[0][0]
			#postMessage = arr.get("message")
			postMessage = request.POST.get("message")
			#print(postMessage)
			#postId = arr[1].split("=")[1].replace("+", " ")
			postId = request.POST.get("id")
			#print(postId)
			postTitle = form.cleaned_data.get("title")
			#postTitle = arr[2].split("=")[1].replace("+", " ")
			#print(postTitle)
			postAnswer = form.cleaned_data.get("answer")
			#postAnswer = arr[3].split("=")[1].replace("+", " ")
			#print(postAnswer)

			public = request.POST.get("public")
			emailResponse = request.POST.get("emailResponse")

			# last = arr[len(arr)-1]
			# secToLast = arr[len(arr)-2]

			# if last.split("=")[0] == "emailResponse":
			# 	emailResponse = last.split("=")[1].replace("+", " ")
			# 	if secToLast.split("=")[0] == "public":
			# 		public = secToLast.split("=")[1].replace("+", " ")

			# if last.split("=")[0] == "public":
			# 	public = last.split("=")[1].replace("+", " ")

			#print(public)
			#print(emailResponse)

			# if len(arr) > 4:
			# 	checkboxValue = arr[4].split("=")[1].replace("+", " ")
			# 	if arr[4].split("=")[0] == "public":
			# 		public = "on"
			# 	else: 
			# 		emailResponse = "on"
			# 	#print(public)

			# if len(arr) > 5:
			# 	emailResponse = arr[5].split("=")[1].replace("+", " ")
			# 	#print(emailResponse)

			querySet = Question.objects.all()
			querySet = querySet.filter(id = int(postId))
			question = querySet[0]
			#print(len(querySet))
			##print(str(question))
			#postAnswer = request.POST.get('answer')
			question.answer = postAnswer
			question.title = postTitle
			question.isAnswered = True
			if public != None and public == "on":
				question.isPublished = True

			if emailResponse != None and emailResponse == "on":
				#print("send Mail")
				send_mail('Subject here', 'Here is the message.', OUR_EMAIL, [question.email], fail_silently=False)


				#send_mail('Subject here', 'Here is the message.', '*****@*****.**',
	    #['*****@*****.**'], fail_silently=False)

			question.save()
			return moderate(request)
예제 #52
0
"""
예제 #53
0
def context(request, ):
    #    from apps.product.models import Category
    #    try:
    #        all_categories_ = Category.manager.published()
    #    except Category.DoesNotExist:
    #        all_categories_ = None

    #    ajax_resolution_ = request.session.get(u'ajax_resolution', True, )
    print 'Django_Context_Processor:'
    print 'print request: ', request
    if str(request, ).find('WSGIRequest:', ):
        url = str(request, ).split("'")[1]
        print url
        try:
            value = url.decode('cp1252').encode('utf8')
        except:
            pass
        else:
            try:
                print 'cp1252 -1', type(value, ), value
            except:
                print 'cp1252 -1', type(value, ), 'print value: Error'
        try:
            value = url.encode('cp1252')
        except:
            pass
        else:
            try:
                print 'cp1252 -2', type(value, ), value
            except:
                print 'cp1252 -2', type(value, ), 'print value: Error'

    try:
        url = dict(request)
        print 'dict: ', url
        url = url['WSGIRequest']
    except Exception as e:
        print 'Exception: ', e
    except TypeError as e:
        print 'TypeError: ', e
    print 'WSGIRequest: ', url
    url = request.get_full_path()
    from django.shortcuts import redirect
    # return redirect(to=url)
    from django.utils.encoding import uri_to_iri
    url = uri_to_iri(url, )
    url = url.encode('cp1252', )
    print 'Next URL: request.get_full_path: ', url
    from django.core.urlresolvers import resolve, Resolver404
    view, args, kwargs = resolve(url, )
    print view, args, kwargs
    from apps.product.views import show_product
    if 'view' in locals() and view == show_product:
        try:
            product_pk = int(kwargs[u'id'], )
        except ValueError:
            pass
        else:
            print product_pk, kwargs[u'product_url'].encode('utf8')
            from apps.product.views import get_product
            """ Убираем НАХРЕН проверку именования товара product_url """
            # product = get_product(product_pk=product_pk, product_url=kwargs[u'product_url'], )
            product = get_product(product_pk=product_pk, )
            print product
            #return redirect(to=product.get_absolute_url(), )
    #return redirect(to='http://keksik.com.ua%s' % url, )
    return dict(url=product.get_absolute_url(), )
예제 #54
0
def get_redirect(request, path):
    redirect = _get_redirect(request, path)
    if not redirect:
        # try unencoding the path
        redirect = _get_redirect(request, uri_to_iri(path))
    return redirect
예제 #55
0
def projetosSearch(request):

    filter_args = {}
    link_args = u''
    form_initial = {}

    if request.method == 'POST':

        if  'submit' in request.POST:

            projeto = ProjetoForm(request.POST)

            if len(projeto.data['PRONAC']) > 0:
                filter_args['PRONAC'] = projeto.data['PRONAC']

            if len(projeto.data['cgccpf']) > 0:
                filter_args['cgccpf'] = projeto.data['cgccpf']

            if projeto.data['segmento'] != 'SEGMENTO':
                filter_args['segmento'] = projeto.data['segmento']

            if projeto.data['area'] != 'AREA':
                filter_args['area'] = projeto.data['area']

            if projeto.data['UF'] != 'ESTADO':
                filter_args['UF'] = projeto.data['UF']

            if projeto.data['ano_projeto'] != 'ano_projeto':
                filter_args['ano_projeto'] = projeto.data['ano_projeto']

            for key in filter_args:
                link_args += key+"="+filter_args[key]+"&"

            form_initial = filter_args.copy()

            if len(projeto.data['municipio']) > 0:
                filter_args['municipio__icontains'] = projeto.data['municipio']
                link_args +='municipio='+projeto.data['municipio']+'&'
                form_initial['municipio'] = projeto.data['municipio']

            if len(projeto.data['nome']) > 0:
                filter_args['nome__icontains'] = projeto.data['nome']
                link_args +='nome='+projeto.data['nome']+'&'
                form_initial['nome'] = projeto.data['nome']

            if len(projeto.data['proponente']) > 0:
                filter_args['proponente__icontains'] = projeto.data['proponente']
                link_args +='proponente='+projeto.data['proponente']+'&'
                form_initial['proponente'] = projeto.data['proponente']


            if projeto.data['captacao'] != 'captacao':
                form_initial['captacao'] = projeto.data['captacao']

                if form_initial['captacao'] == 'comcaptacoes':
                    filter_args['valor_captado__gt'] = 0
                else:
                    filter_args['valor_captado'] = 0

                link_args+="captacao="+projeto.data['captacao']+"&"

            if projeto.data['conclusao'] != 'conclusao':
                form_initial['conclusao'] = projeto.data['conclusao']
                link_args+="conclusao="+projeto.data['conclusao']+"&"

            #print "link args : " + link_args

    if request.method == 'GET':
        query_params = request.META['QUERY_STRING'].split('&')
        #   print 'Query params : ' + str(query_params)

        exclusion_fields = ['format', 'page', 'sort', 'captacao', 'conclusao', 'limit', 'offset', 'order']
        for param in query_params:
            if param != '':
                k, v = param.split('=')
                form_initial[k] = uri_to_iri(v)
                if k not in exclusion_fields:
                    filter_args[k] = v

        #print 'filter_args : ' + str(filter_args)

    table = ProjetoTable()
    table.data_url+=link_args

    return render(request, 'projetos.html', {'table' : table, 'searchForm' : ProjetoForm(initial=form_initial)})
예제 #56
0
파일: views.py 프로젝트: Tyapkin/djbookru
 def get_queryset(self):
     # transform a URL string to a string IRI
     company = uri_to_iri(self.kwargs['company'])
     return get_list_or_404(Jobs, company_name_slug__iexact=company)
예제 #57
0
from __future__ import unicode_literals
예제 #58
0
파일: results.py 프로젝트: eldarion/formly
 def answer_string(self):
     # decode answer_string, which is usually processed by iri_to_uri
     # if the url is constructed by Django's default `url` template tag
     return uri_to_iri(self.kwargs.get("answer_string"))