当前位置: 首页>>代码示例>>Python>>正文


Python middlewares.ThreadLocal类代码示例

本文整理汇总了Python中django_tools.middlewares.ThreadLocal的典型用法代码示例。如果您正苦于以下问题:Python ThreadLocal类的具体用法?Python ThreadLocal怎么用?Python ThreadLocal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ThreadLocal类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: done

    def done(self, form_list, **kwargs):
        invoice = None

        from django_tools.middlewares import ThreadLocal

        user = ThreadLocal.get_current_user().username
        klient = Klient.objects.get(nazwa=user)

        for form in form_list:
            if isinstance(form, ZamowienieForm):
                invoiceData = form.cleaned_data
                invoiceData.update({
                    'klient': klient
                })
                invoice = Zamowienie(**invoiceData)
                invoice.save()
            elif isinstance(form, BaseFormSet):
                for posForm in form.forms:
                    if isinstance(posForm, PozycjaZamowieniaForm):
                        positionData = posForm.cleaned_data
                        positionData.update({
                            'zamowienie': invoice
                        })
                        position = PozycjaZamowienia(**positionData)
                        position.save()
                    else:
                        posForm.save()

        self.storage.reset()

        return render_to_response('wizard/stepDone.html',
                                  {'zamowienie': invoice,
                                   'pozycje': PozycjaZamowienia.objects.filter(zamowienie_id=invoice.pk)},
                                  context_instance=RequestContext(ThreadLocal.get_current_request()))
开发者ID:kornicameister,项目名称:InvoiceManager,代码行数:34,代码来源:forms.py

示例2: get_ols_url

def get_ols_url():
    req = ThreadLocal.get_current_request()
    protocol = req.META['wsgi.url_scheme']
    r = req.build_absolute_uri()
    ols_url = protocol + '://' + ThreadLocal.get_current_request().META['HTTP_HOST'] + reverse(
        'copo:ajax_search_ontology')

    return ols_url
开发者ID:ISA-tools,项目名称:COPO,代码行数:8,代码来源:html_tags.py

示例3: process_request

    def process_request(self, request):
        url = request.get_full_path()
        if url.startswith('/copo', 0, 5):

            doc = Submission().get_incomplete_submissions_for_user(request.user.id, figshare)
            data_dict = dict()
            token = None

            if doc.count() > 0:

                if 'code' in request.GET and 'state' in request.GET:

                    token_obtained = True

                    for d in doc:
                        if d.get('token_obtained') == 'false':
                            token_obtained = False
                            break

                    if not token_obtained:

                        # get new token from Figshare
                        code = request.GET.get('code')
                        client_id = FIGSHARE_CREDENTIALS['client_id']
                        token_url = FIGSHARE_API_URLS['authorization_token']

                        # now get token
                        data = {
                            'client_id': client_id,
                            'code': code,
                            'client_secret': FIGSHARE_CREDENTIALS['client_secret'],
                            'grant_type': 'authorization_code',
                            'scope': 'all'
                        }
                        try:
                            r = requests.post(token_url, data)
                            data_dict = ast.literal_eval(r.content.decode('utf-8'))
                            token = data_dict['token']
                            t = Figshare().put_token_for_user(user_id=ThreadLocal.get_current_user().id, token=token)
                            if t:
                                # mark fighshare submissions for this user as token obtained
                                Submission().mark_all_token_obtained(user_id=request.user.id)

                                # if all is well, the access token will be stored in FigshareSubmussionCollection
                        except Exception as e:
                            print(e)

                    else:
                        # retrieve token
                        token = Figshare().get_token_for_user(user_id=ThreadLocal.get_current_user().id)


                        # request.session['partial_submissions'] = doc
            else:
                request.session['partial_submissions'] = None
开发者ID:ISA-tools,项目名称:COPO,代码行数:55,代码来源:FigshareMiddleware.py

示例4: get_absolute_url

    def get_absolute_url(self):
        """
        absolute url (without domain/host part)
        TODO: Should be used a cache here?
        """
        if not self.url_name:
            return "" # menu section

        url = self.get_url()
        if url is None: # can't resolve url, message was created.
            return "#resolve-error" # XXX: return something else?

        request = ThreadLocal.get_current_request()
        get_data = {}
        if self.get_pagetree and hasattr(request.PYLUCID, "pagetree"):
            get_data["pagetree"] = request.PYLUCID.pagetree.pk
        if self.get_pagemeta and hasattr(request.PYLUCID, "pagemeta"):
            get_data["pagemeta"] = request.PYLUCID.pagemeta.pk
        if self.get_page:
            if hasattr(request.PYLUCID, "pagecontent"):
                get_data["pagecontent"] = request.PYLUCID.pagecontent.pk
            elif hasattr(request.PYLUCID, "pluginpage"):
                get_data["pluginpage"] = request.PYLUCID.pluginpage.pk

        if get_data:
            # FIXME: There must be a better was to to this.
            # TODO: escape it.
            url += "?" + "&".join(["%s=%s" % (key, value) for key, value in get_data.items()])

        return url
开发者ID:BIGGANI,项目名称:PyLucid,代码行数:30,代码来源:models.py

示例5: GET_FOR_USER

 def GET_FOR_USER(self, user=None):
     if (user == None):
         user = ThreadLocal.get_current_user().id
     docs = Profiles.find({'user_id': user})
     if not docs:
         pass
     return docs
开发者ID:alexgarciac,项目名称:COPO,代码行数:7,代码来源:copo_base_da.py

示例6: create_sra_person

    def create_sra_person(self):
        """
        create an (SRA) person record and attach to profile

        Args:
            profile_id: to be linked to created record

        Returns:

        """
        user = ThreadLocal.get_current_user()

        auto_fields = {
            'copo.person.roles.annotationValue': 'SRA Inform On Status',
            'copo.person.lastName': user.last_name,
            'copo.person.firstName': user.first_name,
            'copo.person.roles.annotationValue_1': 'SRA Inform On Error',
            'copo.person.email': user.email
        }

        people = self.get_all_records()
        sra_roles = list()
        for record in people:
            for role in record.get("roles", list()):
                sra_roles.append(role.get("annotationValue", str()))

        # has sra roles?
        has_sra_roles = all(x in sra_roles for x in ['SRA Inform On Status', 'SRA Inform On Error'])

        if not has_sra_roles:
            kwargs = dict()
            self.save_record(auto_fields, **kwargs)

        return
开发者ID:ISA-tools,项目名称:COPO,代码行数:34,代码来源:copo_da.py

示例7: generate_copo_sample_form

def generate_copo_sample_form(source_id=None, sample_id=None):
    profile_id = ThreadLocal.get_current_request().session['profile_id']

    # if there are sources in the profile, create a dropdown showing the sources and a box to create a new one
    # if there are no sources in the profile, create the new source form
    output = ''
    if ProfileInfo(profile_id).source_count() > 0:
        # get sources
        sources = Source(profile_id).get_all_sources()

        output += "<div id='source_select'>"
        output += generate_copo_source_dropdown(sources)
        output += generate_copo_source_add_button()
        output += "</div>"
        output += "<div id='new_source_div'>"
        output += generate_copo_source_form_html()
        output += "</div>"
    else:
        output += "<div id='new_source_div'>"
        output += generate_copo_source_form_html()
        output += "</div>"

    output += generate_copo_sample_form_html()

    return output
开发者ID:alexgarciac,项目名称:COPO,代码行数:25,代码来源:html_tags.py

示例8: get_permalink

    def get_permalink(self):
        """
        return a permalink. Use page slug/name/title or nothing as additional text.
        """
        if self.pk in self._permalink_cache:
            #print "PageMeta permalink_cache len: %s, pk: %s" % (len(self._permalink_cache), self.pk)
            return self._permalink_cache[self.pk]

        # Get the system preferences
        request = ThreadLocal.get_current_request()
        sys_pref = request.PYLUCID.preferences
        sys_pref_form = request.PYLUCID.preferences_form

        use_additions = sys_pref.get("permalink_additions", sys_pref_form.PERMALINK_USE_TITLE)

        do_slugify = False
        if use_additions == sys_pref_form.PERMALINK_USE_TITLE:
            # Append the PageMeta title (language dependent)
            addition_txt = self.get_title()
            do_slugify = True
        elif use_additions == sys_pref_form.PERMALINK_USE_NAME:
            addition_txt = self.get_name()
            do_slugify = True
        elif use_additions == sys_pref_form.PERMALINK_USE_SLUG:
            addition_txt = self.pagetree.slug
        else:
            addition_txt = ""

        if do_slugify:
            addition_txt = slugify(addition_txt)

        url = reverse('PyLucid-permalink', kwargs={'page_id': self.pagetree.id, 'url_rest': addition_txt})
        self._permalink_cache[self.pk] = url
        return url
开发者ID:BIGGANI,项目名称:PyLucid,代码行数:34,代码来源:pagemeta.py

示例9: __init__

 def __init__(self, sub_id):
     self.BASE_URL = FIGSHARE_API_URLS['base_url']
     request = ThreadLocal.get_current_request()
     self.TOKEN = Figshare().get_token_for_user(request.user.id)['token']
     self.HEADERS = {'Authorization': 'token ' + self.TOKEN}
     self.MEDIA_ROOT = settings.MEDIA_ROOT
     self.transfer_token = RemoteDataFile().create_transfer(sub_id)['_id']
开发者ID:ISA-tools,项目名称:COPO,代码行数:7,代码来源:figshareSubmission.py

示例10: view_orcid_profile

def view_orcid_profile(request):
    user = ThreadLocal.get_current_user()
    op = Orcid().get_orcid_profile(user)
    data_dict = {'op': op}
    # data_dict = jsonpickle.encode(data_dict)

    return render(request, 'copo/orcid_profile.html', data_dict)
开发者ID:ISA-tools,项目名称:COPO,代码行数:7,代码来源:views.py

示例11: __init__

    def __init__(self, *args, **kwargs):
        """
        prepare the tag queryset filter
        """
        super(TagLanguageSitesFilter, self).__init__(*args, **kwargs)

        def get_data(field_name):
            return self.initial.get(field_name, None) or self.data.get(field_name, None)

        language = get_data("language")
        if not language:
            # Use current language for tag queryset filter
            request = ThreadLocal.get_current_request()
            language = request.PYLUCID.current_language

        sites = get_data("sites")
        if not sites:
            # Use current site for tag queryset filter
            sites = [settings.SITE_ID]

        # change the tag queryset filter:
        self.fields["tags"].widget.tag_queryset_filters = {
            "language": language,
            "sites__id__in": sites,
        }
开发者ID:daqing15,项目名称:PyLucid,代码行数:25,代码来源:utils.py

示例12: _setup_tag_filter

    def _setup_tag_filter(self):
        """
        prepare the tag queryset filter
        """
        def get_data(field_name):
            return self.initial.get(field_name, None) or self.data.get(field_name, None)

        language = get_data("language")
        if not language:
            # Use current language for tag queryset filter
            request = ThreadLocal.get_current_request()
            language = request.PYLUCID.current_language

        pagetree_id = get_data("pagetree")
        if pagetree_id:
            pagetree = PageTree.objects.only("site").get(id=pagetree_id)
            site = pagetree.site
        else:
            # Use current site for tag queryset filter
            site = settings.SITE_ID

        # change the tag queryset filter:
        self.fields["tags"].widget.tag_queryset_filters = {
            "language": language,
            "pagetree__site": site,
        }
开发者ID:BIGGANI,项目名称:PyLucid,代码行数:26,代码来源:pagemeta.py

示例13: get_permissions

    def get_permissions(self):
        """
        returns the access permissions for this menu entry.
        TODO: Should be cache this?
        """
        if not self.url_name: # a menu section
            # TODO: Check if at least one sub entry is accessible.
            return (False, (), False)

        url = self.get_url()
        if url is None: # can't resolve url, message was created.
            return (True, (), True) # view can only superusers use

        # Get the view function for this url_name
        view_func, func_args, func_kwargs = urlresolvers.resolve(url)

        # get the rights from pylucid_project.apps.pylucid.decorators.check_permissions
        try:
            access_permissions = view_func.access_permissions
        except AttributeError, err:
            # If no permissions available, fallback to superuser only
            request = ThreadLocal.get_current_request()
            if settings.DEBUG or request.user.is_staff:
                messages.error(request, (
                    "The view %s for url %r has no permissions attribute!"
                    " Please use pylucid_project.apps.pylucid.decorators.check_permissions!"
                    ) % (view_func.__name__, self.url_name)
                )
            access_permissions = (True, (), True)
开发者ID:BIGGANI,项目名称:PyLucid,代码行数:29,代码来源:models.py

示例14: log_action

    def log_action(self, app_label, action, request=None, message=None, long_message=None, data=None):
        if request is None:
            request = ThreadLocal.get_current_request()

        kwargs = {
            "uri": request.build_absolute_uri(),
            "app_label": app_label,
            "action": action,
            "message": message,
            "long_message": long_message,
            "data": data,
        }

        if hasattr(request, "PYLUCID"):
            kwargs["used_language"] = request.PYLUCID.current_language

        for key in META_KEYS:
            value = request.META.get(key)
            if value and len(value) > 255:
                value = "%s..." % value[:252]
            kwargs[key.lower()] = value

        new_entry = self.model(**kwargs)
        new_entry.save()
        return new_entry
开发者ID:daqing15,项目名称:PyLucid,代码行数:25,代码来源:log.py

示例15: save

    def save(self, *args, **kwargs):
        current_user = ThreadLocal.get_current_user()

        if current_user and isinstance(current_user, User):
            if self.pk == None or kwargs.get("force_insert", False): # New model entry
                self.createby = current_user
            self.lastupdateby = current_user

        return super(UpdateUserBaseModel, self).save(*args, **kwargs)
开发者ID:adfreeq,项目名称:django-tools,代码行数:9,代码来源:models.py


注:本文中的django_tools.middlewares.ThreadLocal类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。