コード例 #1
0
def get_organization(user):
    """Gets a users active organization"""

    return cache_get_or_set(
        u'sb:%s:user_org' % user.username, lambda: user.profile.organization,
        settings.DEFAULT_CACHE_TIMEOUT
    )
コード例 #2
0
def get_organizations(user):
    """Gets all of the users organizations"""

    return cache_get_or_set(
        u'sb:%s:user_orgs' % user.username, lambda: user.organizations.
        order_by('-individual', 'name'), settings.DEFAULT_CACHE_TIMEOUT
    )
コード例 #3
0
def sidebar_broadcast(user):
    """Displays a broadcast to a given usertype"""
    def load_broadcast(user_class):
        """Return a function to load the correct broadcast"""
        def inner():
            """Argument-less function to load correct broadcast"""
            try:
                # exclude stale broadcasts from displaying
                last_week = timezone.now() - timedelta(7)
                broadcast = Broadcast.objects.get(updated__gte=last_week,
                                                  context=user_class).text
            except Broadcast.DoesNotExist:
                broadcast = ''
            return broadcast

        return inner

    try:
        user_class = (user.profile.acct_type
                      if user.is_authenticated() else 'anonymous')
    except Profile.DoesNotExist:
        user_class = 'anonymous'
    return cache_get_or_set('sb:%s:broadcast' % user_class,
                            load_broadcast(user_class),
                            settings.DEFAULT_CACHE_TIMEOUT)
コード例 #4
0
ファイル: crowdfund_tags.py プロジェクト: clytwynec/muckrock
def generate_crowdfund_context(the_crowdfund, the_url_name, the_form,
                               the_context):
    """Generates context in a way that's agnostic towards the object being crowdfunded."""
    endpoint = reverse(the_url_name, kwargs={'pk': the_crowdfund.pk})
    payment_form = crowdfund_form(the_crowdfund, the_form)
    logged_in, user_email = crowdfund_user(the_context)
    the_request = the_context.request
    named, contrib_count, anon_count = (cache_get_or_set(
        'cf:%s:crowdfund_widget_data' % the_crowdfund.pk, lambda: (
            list(the_crowdfund.named_contributors()),
            the_crowdfund.contributors_count(),
            the_crowdfund.anonymous_contributors_count(),
        ), settings.DEFAULT_CACHE_TIMEOUT))
    contrib_sum = contributor_summary(named, contrib_count, anon_count)
    obj_url = the_crowdfund.get_crowdfund_object().get_absolute_url()
    # Remove the autofocus attribute from the login form in order to not scroll down
    # to the crowdfund widget on page load
    login_form = AuthenticationForm()
    login_form.fields['username'].widget.attrs.pop('autofocus', None)
    return {
        'crowdfund': the_crowdfund,
        'named_contributors': named,
        'contributors_count': contrib_count,
        'anon_contributors_count': anon_count,
        'contributor_summary': contrib_sum,
        'endpoint': endpoint,
        'login_form': login_form,
        'logged_in': logged_in,
        'user_email': user_email,
        'payment_form': payment_form,
        'request': the_request,
        'stripe_pk': settings.STRIPE_PUB_KEY,
        'obj_url': obj_url,
        'domain': the_context['domain'],
    }
コード例 #5
0
ファイル: views.py プロジェクト: clytwynec/muckrock
 def get_context_data(self, **kwargs):
     """Adds interesting articles to the explore page."""
     context = super(NewsExploreView, self).get_context_data(**kwargs)
     recent_articles = cache_get_or_set(
         'hp:articles', lambda: (
             Article.objects.get_published().prefetch_related(
                 'authors',
                 'authors__profile',
                 'projects',
             )[:5]
         ), 600
     )
     context['featured_projects'] = (
         Project.objects.get_visible(
             self.request.user
         ).filter(featured=True).prefetch_related(
             Prefetch(
                 'articles__authors',
                 queryset=User.objects.select_related('profile')
             )
         ).optimize()
     )
     context['recent_articles'] = recent_articles
     context['top_tags'] = Article.tags.most_common()[:15]
     return context
コード例 #6
0
def get_organizations(user):
    """Gets all of the users organizations"""

    return cache_get_or_set(
        "sb:%s:user_orgs" % user.username,
        user.organizations.get_cache,
        settings.DEFAULT_CACHE_TIMEOUT,
    )
コード例 #7
0
    def get_value(self):
        """Get the page views so far for this month"""
        def inner():
            """Inner function for caching"""
            today = date.today()
            month_start = today.replace(day=1)

            # initalize google analytics api
            # we store the keyfile on s3
            conn = S3Connection(
                settings.AWS_ACCESS_KEY_ID,
                settings.AWS_SECRET_ACCESS_KEY,
            )
            bucket = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
            key = bucket.get_key('google/analytics_key.json')
            with smart_open(key) as key_file:
                credentials = ServiceAccountCredentials.from_json_keyfile_dict(
                    json.loads(key_file.read()),
                    ['https://www.googleapis.com/auth/analytics.readonly'],
                )
            try:
                analytics = build(
                    'analyticsreporting',
                    'v4',
                    credentials=credentials,
                    cache_discovery=False,
                )
                response = analytics.reports().batchGet(
                    body={
                        'reportRequests': [{
                            'viewId':
                            settings.VIEW_ID,
                            'dateRanges': [{
                                'startDate': month_start.isoformat(),
                                'endDate': today.isoformat(),
                            }],
                            'metrics': [{
                                'expression': 'ga:pageviews'
                            }],
                        }]
                    }).execute()
            except HttpError:
                return 'Error'
            try:
                # google really buries the useful data in the response
                # remove format if we want to go back to a comparison
                return '{:,}'.format(
                    int(response['reports'][0]['data']['rows'][0]['metrics'][0]
                        ['values'][0]))
            except KeyError:
                return 'Error'

        return cache_get_or_set('dashboard:pageviews', inner, 60 * 5)
コード例 #8
0
ファイル: models.py プロジェクト: WPMedia/muckrock
    def get_url_auth_token(self):
        """Get a URL auth token for the user
        Cache it so a single email will use a single auth token"""
        def get_url_auth_token_squarelet():
            """Get the URL auth token from squarelet"""
            try:
                resp = squarelet_get("/api/url_auth_tokens/{}/".format(
                    self.uuid))
                resp.raise_for_status()
            except requests.exceptions.RequestException:
                return None
            return resp.json().get("url_auth_token")

        return cache_get_or_set("url_auth_token:{}".format(self.uuid),
                                get_url_auth_token_squarelet, 10)
コード例 #9
0
ファイル: widgets.py プロジェクト: WPMedia/muckrock
    def get_value(self):
        """Get the page views so far for this month"""
        def inner():
            """Inner function for caching"""
            today = date.today()
            month_start = today.replace(day=1)

            # initalize google analytics api
            # we store the keyfile on s3
            key = f"s3://{settings.AWS_STORAGE_BUCKET_NAME}/google/analytics_key.json"
            with smart_open(key) as key_file:
                credentials = ServiceAccountCredentials.from_json_keyfile_dict(
                    json.loads(key_file.read()),
                    ["https://www.googleapis.com/auth/analytics.readonly"],
                )
            try:
                analytics = build(
                    "analyticsreporting",
                    "v4",
                    credentials=credentials,
                    cache_discovery=False,
                )
                response = (analytics.reports().batchGet(
                    body={
                        "reportRequests": [{
                            "viewId":
                            settings.VIEW_ID,
                            "dateRanges": [{
                                "startDate": month_start.isoformat(),
                                "endDate": today.isoformat(),
                            }],
                            "metrics": [{
                                "expression": "ga:pageviews"
                            }],
                        }]
                    }).execute())
            except HttpError:
                return "Error"
            try:
                # google really buries the useful data in the response
                # remove format if we want to go back to a comparison
                return "{:,}".format(
                    int(response["reports"][0]["data"]["rows"][0]["metrics"][0]
                        ["values"][0]))
            except KeyError:
                return "Error"

        return cache_get_or_set("dashboard:pageviews", inner, 60 * 5)
コード例 #10
0
def get_organization(user):
    """Gets organization, if it exists"""

    return cache_get_or_set('sb:%s:user_org' % user.username,
                            user.profile.get_org,
                            settings.DEFAULT_CACHE_TIMEOUT)