Пример #1
0
    def get_javascript(self):
        """
        Returns the url of the javascript bundle into which the provider's JS will be loaded
        """
        # use the defined npm_module name, or else the python package name
        package = getattr(self, 'npm_module',
                          self.__class__.__module__.split('.')[0])
        js_url = ''
        try:
            bundle_chunks = get_files(package, config="WORKERS")
            # still necessary to check, since webpack_loader can be
            # configured to ignore all matching packages
            if bundle_chunks:
                js_url = bundle_chunks[0]["url"]

        except WebpackBundleLookupError:
            warnings.warn(
                u'Could not find webpack bundle for proctoring backend {package}.'
                u' Check whether webpack is configured to build such a bundle'.
                format(package=package))
        except BaseWebpackLoaderException:
            warnings.warn(
                u'Could not find webpack bundle for proctoring backend {package}.'
                .format(package=package))
        except IOError as err:
            warnings.warn(
                u'Webpack stats file corresponding to WebWorkers not found: {}'
                .format(str(err)))
        return js_url
Пример #2
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        scenario = context['scenario']
        component = context['component']

        try:
            obj = _COMPONENTS[scenario][component]
        except KeyError:
            raise Http404

        jsfiles = webpack.get_files('dataviz', 'js')
        cssfiles = webpack.get_files('dataviz', 'css')

        def geturl(f):
            url = f['url']
            if url.startswith('/'):
                url = '//' + self.request.get_host() + url
            return url

        props = {
            'datasource':
            self.request.build_absolute_uri(reverse("api:" + scenario)),
        }

        # this is ugly, nasty and not nice
        if scenario in ("grants", "projects") and component == "xmap":
            props['detailsDatasource'] = self.request.build_absolute_uri(
                reverse("api:%s-beneficiary-detail" % scenario, args=("XX", )))
        elif scenario in ("partners", "projects") and component == "projects":
            props['detailsDatasource'] = self.request.build_absolute_uri(
                reverse("api:project-list"))
        elif scenario in ("partners", "projects") and component == "sidebar":
            props['projectsDatasource'] = self.request.build_absolute_uri(
                reverse("api:project-list"))

        context.update({
            'jsfiles': [geturl(f) for f in jsfiles],
            'cssfiles': [geturl(f) for f in cssfiles],
            'object': obj,
            'props': props,
            'opts': {k: v
                     for k, v in self.request.GET.items()},
            'embedurl': self.request.build_absolute_uri(),
            'randomness': utils.mkrandstr(),
        })
        return context
Пример #3
0
 def media(self):
     super_media = super(BranchSettingsMenuItem, self).media
     js = super_media._js
     css = super_media._css
     js.append(
         webpack_loader_utils.get_files('janisBranchSettings')[0]
         ['url'])
     return forms.Media(css=css, js=js)
Пример #4
0
def dynamic_bundle(request, config, bundle_name):
    bundle_name = re.sub(r'-(bundle|chunk).*', '', bundle_name)
    files = get_files(bundle_name, None, config.upper())
    if len(files) == 1:
        return HttpResponseRedirect(files[0]['url'])
    return render("404.mako",
                  request,
                  dict(uri=request.build_absolute_uri()),
                  status=404)
Пример #5
0
def render_main(request):
    main = get_files('main')
    print(main)
    # main_component = render_component('/Users/mazurbeam/dev/projects/wagtail-react/wagtail-react-project/assets/bundles/js/main.51c7f8a2.js')
    # rendered = render_component(main_component, timeout=None)
    # rendered = 'rendered'
    # print(main[0]['path'])
    # print(rendered)
    return render(request, 'index.html')
Пример #6
0
def parse_html(content):
    try:
        document = html5lib.parse(content, namespaceHTMLElements=False)

        if not document:
            # Could not parse
            return content

        # Because html5lib parses like a browser, it will
        # always create head and body tags if they are missing.
        head = document.find("head")
        for file in get_files("htmlScreenshot", "js"):
            SubElement(head, "script", attrib={"src": file['url']})
        # Currently, html5lib strips the doctype, but it's important for correct rendering, so check the original
        # content for the doctype and, if found, prepend it to the content serialized by html5lib
        doctype = None
        try:
            # Now parse the content as a dom tree instead, so that we capture
            # any doctype node as a dom node that we can read.
            tree_builder_dom = html5lib.treebuilders.getTreeBuilder("dom")
            parser_dom = html5lib.HTMLParser(tree_builder_dom,
                                             namespaceHTMLElements=False)
            tree = parser_dom.parse(content)
            # By HTML Spec if doctype is included, it must be the first thing
            # in the document, so it has to be the first child node of the document
            doctype_node = tree.childNodes[0]

            # Check that this node is in fact a doctype node
            if doctype_node.nodeType == doctype_node.DOCUMENT_TYPE_NODE:
                # render to a string by calling the toxml method
                # toxml uses single quotes by default, replace with ""
                doctype = doctype_node.toxml().replace("'", '"')
        except Exception as e:
            logging.warn(
                "Error in HTML5 parsing to determine doctype {}".format(e))

        html = html5lib.serialize(
            document,
            quote_attr_values="always",
            omit_optional_tags=False,
            minimize_boolean_attributes=False,
            use_trailing_solidus=True,
            space_before_trailing_solidus=False,
        )

        if doctype:
            html = doctype + html

        return html
    except html5lib.html5parser.ParseError:
        return content
Пример #7
0
def sefaria_js(request):
    """
    Packaged Sefaria.js.
    """
    data_js = render_to_string("js/data.js",context={}, request=request)
    webpack_files = webpack_utils.get_files('main', config="SEFARIA_JS")
    bundle_path = relative_to_abs_path('..' + webpack_files[0]["url"])
    with open(bundle_path, 'r') as file:
        sefaria_js=file.read()
    attrs = {
        "data_js": data_js,
        "sefaria_js": sefaria_js,
    }

    return render(request,"js/sefaria.js", attrs, content_type= "text/javascript")
Пример #8
0
def sefaria_js(request):
    """
    Packaged Sefaria.js.
    """
    data_js = render_to_string("js/data.js", {}, RequestContext(request))
    webpack_files = webpack_utils.get_files('main', config="SEFARIA_JS")
    bundle_path = webpack_files[0]["path"]
    with open(bundle_path, 'r') as file:
        sefaria_js=file.read()
    attrs = {
        "data_js": data_js,
        "sefaria_js": sefaria_js,
    }

    return render_to_response("js/sefaria.js", attrs, RequestContext(request), mimetype= "text/javascript")
Пример #9
0
def render_bundle_css(bundle_name, config='DEFAULT', attrs=''):
    """
    A tag to conditionally load css depending on whether the page is being rendered for
    an LTR or RTL language. Using webpack-rtl-plugin, we now have two css files for every
    bundle. One that just ends in .css for LTR, and the other that ends in .rtl.css for RTL.
    This will conditionally load the correct one depending on the current language setting.
    """
    bidi = get_language_info(get_language())['bidi']
    files = utils.get_files(bundle_name, extension='css', config=config)
    if bidi:
        files = filter(lambda x: x['name'].endswith('rtl.css'), files)
    else:
        files = filter(lambda x: not x['name'].endswith('rtl.css'), files)
    tags = []
    for chunk in files:
        tags.append(
            ('<link type="text/css" href="{0}" rel="stylesheet" {1}/>').format(
                chunk['url'], attrs))
    return mark_safe('\n'.join(tags))
def render_bundle_css(bundle_name, config='DEFAULT', attrs=''):
    """
    A tag to conditionally load css depending on whether the page is being rendered for
    an LTR or RTL language. Using webpack-rtl-plugin, we now have two css files for every
    bundle. One that just ends in .css for LTR, and the other that ends in .rtl.css for RTL.
    This will conditionally load the correct one depending on the current language setting.
    """
    bidi = get_language_info(get_language())['bidi']
    files = utils.get_files(bundle_name, extension='css', config=config)
    if bidi:
        files = filter(lambda x: x['name'].endswith('rtl.css'), files)
    else:
        files = filter(lambda x: not x['name'].endswith('rtl.css'), files)
    tags = []
    for chunk in files:
        tags.append((
            '<link type="text/css" href="{0}" rel="stylesheet" {1}/>'
        ).format(chunk['url'], attrs))
    return mark_safe('\n'.join(tags))
Пример #11
0
    def get_javascript(self):
        """
        Returns the url of the javascript bundle into which the provider's JS will be loaded
        """
        # use the defined npm_module name, or else the python package name
        package = getattr(self, 'npm_module', self.__class__.__module__.split('.')[0])
        js_url = ''
        try:
            bundle_chunks = get_files(package, config="WORKERS")
            # still necessary to check, since webpack_loader can be
            # configured to ignore all matching packages
            if bundle_chunks:
                js_url = bundle_chunks[0]["url"]

        except WebpackBundleLookupError:
            warnings.warn(
                u'Could not find webpack bundle for proctoring backend {package}.'
                u' Check whether webpack is configured to build such a bundle'.format(
                    package=package
                )
            )
        except BaseWebpackLoaderException:
            warnings.warn(
                u'Could not find webpack bundle for proctoring backend {package}.'.format(
                    package=package
                )
            )
        except IOError as err:
            warnings.warn(
                u'Webpack stats file corresponding to WebWorkers not found: {}'
                .format(str(err))
            )

        # if the Javascript URL is not an absolute URL (i.e. doesn't have a scheme), prepend
        # the LMS Root URL to it, if it is defined, to make it an absolute URL
        if not urlparse(js_url).scheme:
            if hasattr(settings, 'LMS_ROOT_URL'):
                js_url = settings.LMS_ROOT_URL + js_url

        return js_url
Пример #12
0
    def get_javascript(self):
        """
        Returns the url of the javascript bundle into which the provider's JS will be loaded
        """
        # use the defined npm_module name, or else the python package name
        package = getattr(self, 'npm_module', self.__class__.__module__.split('.')[0])
        js_url = ''
        try:
            bundle_chunks = get_files(package, config="WORKERS")
            # still necessary to check, since webpack_loader can be
            # configured to ignore all matching packages
            if bundle_chunks:
                js_url = bundle_chunks[0]["url"]

        except WebpackBundleLookupError:
            warnings.warn(
                u'Could not find webpack bundle for proctoring backend {package}.'
                u' Check whether webpack is configured to build such a bundle'.format(
                    package=package
                )
            )
        except BaseWebpackLoaderException:
            warnings.warn(
                u'Could not find webpack bundle for proctoring backend {package}.'.format(
                    package=package
                )
            )
        except IOError as err:
            warnings.warn(
                u'Webpack stats file corresponding to WebWorkers not found: {}'
                .format(str(err))
            )

        # if the Javascript URL is not an absolute URL (i.e. doesn't have a scheme), prepend
        # the LMS Root URL to it, if it is defined, to make it an absolute URL
        if not urlparse(js_url).scheme:
            if hasattr(settings, 'LMS_ROOT_URL'):
                js_url = settings.LMS_ROOT_URL + js_url

        return js_url
Пример #13
0
 def media(self):
     return forms.Media(js=(
         webpack_loader_utils.get_files("lib/adminJsonWidget")[0]["url"], ))
Пример #14
0
 def media(self):
     if self.attrs.get("data-group-selector") == "Y":
         return forms.Media(js=(webpack_loader_utils.get_files(
             "groups/groupSelector")[0]["url"], ))
     return forms.Media()
Пример #15
0
SOCIALACCOUNT_PROVIDERS = {
    'facebook': {
        'SCOPE': ['email'],
        'AUTH_PARAMS': {
            'auth_type': 'reauthenticate'
        },
        'METHOD': 'oauth2',
        'VERIFIED_EMAIL': False
    }
}

# Taggit-Selectize settings
TAGGIT_TAGS_FROM_STRING = 'taggit_selectize.utils.parse_tags'
TAGGIT_STRING_FROM_TAGS = 'taggit_selectize.utils.join_tags'

# Disable it if you need to work with taggit-selectize in django-admin
TAGGIT_SELECTIZE = {
    'CSS_FILENAMES':
    (os.path.basename(get_files('selectize', extension='css')[0]['path']), ),
}

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
    ],
    'PAGE_SIZE':
    10,
    'DEFAULT_PAGINATION_CLASS':
    'rest_framework.pagination.LimitOffsetPagination'
}
Пример #16
0
 class Media:
     js = (webpack_loader_utils.get_files("runtime")[0]["url"], )
Пример #17
0
 def media(self):
     return forms.Media(js=(
         webpack_loader_utils.get_files("front/richEditor")[0]["url"], ))
Пример #18
0
 def media(self):
     return forms.Media(js=(
         webpack_loader_utils.get_files("lib/communeField")[0]["url"], ))
Пример #19
0
 def media(self):
     return forms.Media(
         js=[script["url"] for script in get_files("lib/IBANField", "js")])
Пример #20
0
 def media(self):
     return forms.Media(js=[
         script["url"] for script in get_files("people/mandatesField", "js")
     ])