Example #1
0
    def test_soft_delete_coupon(self):  # pylint: disable=E1101
        self.add_coupon(self.course_key, True)
        coupon = Coupon(code='TestCode', description='testing', course_id=self.course_key,
                        percentage_discount=12, created_by=self.user, is_active=True)
        coupon.save()
        self.assertEquals(coupon.__unicode__(), '[Coupon] code: TestCode course: MITx/999/Robot_Super_Course')
        admin = User.objects.create_user('Mark', '*****@*****.**', 'foo')
        admin.is_staff = True
        get_coupon = Coupon.objects.get(id=1)
        request = HttpRequest()
        request.user = admin
        setattr(request, 'session', 'session')  # pylint: disable=E1101
        messages = FallbackStorage(request)  # pylint: disable=E1101
        setattr(request, '_messages', messages)  # pylint: disable=E1101
        coupon_admin = SoftDeleteCouponAdmin(Coupon, AdminSite())
        test_query_set = coupon_admin.queryset(request)
        test_actions = coupon_admin.get_actions(request)
        self.assertTrue('really_delete_selected' in test_actions['really_delete_selected'])
        self.assertEqual(get_coupon.is_active, True)
        coupon_admin.really_delete_selected(request, test_query_set)  # pylint: disable=E1101
        for coupon in test_query_set:
            self.assertEqual(coupon.is_active, False)
        coupon_admin.delete_model(request, get_coupon)  # pylint: disable=E1101
        self.assertEqual(get_coupon.is_active, False)

        coupon = Coupon(code='TestCode123', description='testing123', course_id=self.course_key,
                        percentage_discount=22, created_by=self.user, is_active=True)
        coupon.save()
        test_query_set = coupon_admin.queryset(request)
        coupon_admin.really_delete_selected(request, test_query_set)  # pylint: disable=E1101
        for coupon in test_query_set:
            self.assertEqual(coupon.is_active, False)
Example #2
0
    def _build_report_and_view(self):
        # Create report
        data_source_config = DataSourceConfiguration(
            domain=self.domain,
            display_name='foo',
            referenced_doc_type='CommCareCase',
            table_id="woop_woop",
            configured_filter={
                "type": "boolean_expression",
                "operator": "eq",
                "expression": {
                    "type": "property_name",
                    "property_name": "type"
                },
                "property_value": self.case_type,
            },
            configured_indicators=[
                {
                    "type": "expression",
                    "expression": {
                        "type": "property_name",
                        "property_name": 'fruit'
                    },
                    "column_id": 'indicator_col_id_fruit',
                    "display_name": 'indicator_display_name_fruit',
                    "datatype": "string"
                },
                {
                    "type": "expression",
                    "expression": {
                        "type": "property_name",
                        "property_name": 'num1'
                    },
                    "column_id": 'indicator_col_id_num1',
                    "datatype": "integer"
                },
                {
                    "type": "expression",
                    "expression": {
                        "type": "property_name",
                        "property_name": 'num2'
                    },
                    "column_id": 'indicator_col_id_num2',
                    "datatype": "integer"
                },
            ],
        )
        data_source_config.validate()
        data_source_config.save()
        self.addCleanup(data_source_config.delete)
        tasks.rebuild_indicators(data_source_config._id)
        adapter = get_indicator_adapter(data_source_config)
        adapter.refresh_table()

        report_config = ReportConfiguration(
            domain=self.domain,
            config_id=data_source_config._id,
            title='foo',
            aggregation_columns=['doc_id'],
            columns=[
                {
                    "type": "field",
                    "display": "report_column_display_fruit",
                    "field": 'indicator_col_id_fruit',
                    'column_id': 'report_column_col_id_fruit',
                    'aggregation': 'simple'
                },
                {
                    "type": "percent",
                    "display": "report_column_display_percent",
                    'column_id': 'report_column_col_id_percent',
                    'format': 'percent',
                    "denominator": {
                        "type": "field",
                        "aggregation": "sum",
                        "field": "indicator_col_id_num1",
                        "column_id": "report_column_col_id_percent_num1"
                    },
                    "numerator": {
                        "type": "field",
                        "aggregation": "sum",
                        "field": "indicator_col_id_num2",
                        "column_id": "report_column_col_id_percent_num2"
                    }
                },
            ],
        )
        report_config.save()
        self.addCleanup(report_config.delete)

        view = ConfigurableReport(request=HttpRequest())
        view._domain = self.domain
        view._lang = "en"
        view._report_config_id = report_config._id

        return report_config, view
Example #3
0
 def test_redirect_custom_report(self):
     report, view = self._build_report_and_view()
     request = HttpRequest()
     self.assertFalse(view.should_redirect_to_paywall(request))
Example #4
0
 def test_set_with_xheader_right(self):
     self.settings_module.SECURE_PROXY_SSL_HEADER = (
         'HTTP_X_FORWARDED_PROTOCOL', 'https')
     req = HttpRequest()
     req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https'
     self.assertEqual(req.is_secure(), True)
Example #5
0
 def test_none(self):
     self.settings_module.SECURE_PROXY_SSL_HEADER = None
     req = HttpRequest()
     self.assertEqual(req.is_secure(), False)
Example #6
0
 def process_request(self, request: HttpRequest) -> None:
     request.user = SimpleLazyObject(lambda: get_user(request))
Example #7
0
 def test_akismet_spam(self):
     self.mock_akismet('true')
     self.assertTrue(is_spam('text', HttpRequest()))
Example #8
0
 def test_home_page_returns_correct_html(self):
     request = HttpRequest()
     response = home_page(request)
     html = response.content.decode('utf8')
     expected_html = render_to_string('home.html')
     self.assertEqual(html, expected_html)
Example #9
0
 def test_get_user(self):
     self.client.force_login(self.user)
     request = HttpRequest()
     request.session = self.client.session
     user = get_user(request)
     self.assertEqual(user, self.user)
Example #10
0
 def assertBackendInSession(self, backend):
     request = HttpRequest()
     request.session = self.client.session
     self.assertEqual(request.session[BACKEND_SESSION_KEY], backend)
Example #11
0
	def test_home_page_only_saves_items_when_neccessary(self):
		request = HttpRequest()
		home_page(request)
		self.assertEqual(Item.objects.count(), 0)
Example #12
0
	def test_home_page_returns_correct_html(self):
		request = HttpRequest()
		response = home_page(request)
		expected_html = render_to_string('home.html', {'new_item_text': 'A new list item'})
		self.assertEqual(response.content.decode(), expected_html)
Example #13
0
 def test_home_page_returns_correct_html(self):
     request = HttpRequest()
     response = home_page(request)
     expected_html = render_to_string('home.html', {'form': ItemForm()})
     self.assertMultiLineEqual(response.content.decode(), expected_html)
Example #14
0
 def test_coverage_data_view_provides_court_data(self):
     response = coverage_data(HttpRequest(), 'v2', 'ca9')
     self.assertEqual(response.status_code, 200)
     self.assertIsInstance(response, JsonResponse)
     self.assertContains(response, 'annual_counts')
     self.assertContains(response, 'total')
Example #15
0
 def collect_resource_instances_for_couch(self):
     """
     Uses the data definition configs of a mobile survey object to search for
     resource instances relevant to a mobile survey. Takes a user object which
     is required for search.
     """
     query = self.datadownloadconfig['custom']
     resource_types = self.datadownloadconfig['resources']
     all_instances = {}
     if query in ('', None) and len(resource_types) == 0:
         print "No resources or data query defined"
     else:
         request = HttpRequest()
         request.user = self.lasteditedby
         request.GET['mobiledownload'] = True
         request.GET['resourcecount'] = self.datadownloadconfig['count']
         if query in ('', None):
             if len(self.bounds.coords) == 0:
                 default_bounds = settings.DEFAULT_BOUNDS
                 default_bounds['features'][0]['properties'][
                     'inverted'] = False
                 map_filter = json.dumps(default_bounds)
             else:
                 map_filter = json.dumps({
                     u'type':
                     u'FeatureCollection',
                     'features': [{
                         'geometry': json.loads(self.bounds.json)
                     }]
                 })
             try:
                 for res_type in resource_types:
                     instances = {}
                     request.GET['resource-type-filter'] = json.dumps([{
                         'graphid':
                         res_type,
                         'inverted':
                         False
                     }])
                     request.GET['map-filter'] = map_filter
                     request.GET['resourcecount'] = self.datadownloadconfig[
                         'count']
                     self.append_to_instances(request, instances, res_type)
                     if len(instances.keys()) < int(
                             self.datadownloadconfig['count']):
                         request.GET['map-filter'] = '{}'
                         request.GET['resourcecount'] = int(
                             self.datadownloadconfig['count']) - len(
                                 instances.keys())
                         self.append_to_instances(request, instances,
                                                  res_type)
                     for key, value in instances.iteritems():
                         all_instances[key] = value
             except KeyError:
                 print 'no instances found in', search_res
         else:
             try:
                 instances = {}
                 parsed = urlparse.urlparse(query)
                 urlparams = urlparse.parse_qs(parsed.query)
                 for k, v in urlparams.iteritems():
                     request.GET[k] = v[0]
                 search_res_json = search.search_results(request)
                 search_res = JSONDeserializer().deserialize(
                     search_res_json.content)
                 for hit in search_res['results']['hits']['hits']:
                     instances[hit['_source']
                               ['resourceinstanceid']] = hit['_source']
                 for key, value in instances.iteritems():
                     all_instances[key] = value
             except KeyError:
                 print 'no instances found in', search_res
     return all_instances
Example #16
0
def home_real(request: HttpRequest) -> HttpResponse:
    # Before we do any real work, check if the app is banned.
    client_user_agent = request.META.get("HTTP_USER_AGENT", "")
    (insecure_desktop_app, banned_desktop_app,
     auto_update_broken) = is_outdated_desktop_app(client_user_agent)
    if banned_desktop_app:
        return render(
            request,
            "zerver/insecure_desktop_app.html",
            context={
                "auto_update_broken": auto_update_broken,
            },
        )
    (unsupported_browser,
     browser_name) = is_unsupported_browser(client_user_agent)
    if unsupported_browser:
        return render(
            request,
            "zerver/unsupported_browser.html",
            context={
                "browser_name": browser_name,
            },
        )

    # We need to modify the session object every two weeks or it will expire.
    # This line makes reloading the page a sufficient action to keep the
    # session alive.
    request.session.modified = True

    if request.user.is_authenticated:
        user_profile = request.user
        realm = user_profile.realm

        # User is logged in and hence no longer `prefers_web_public_view`.
        if "prefers_web_public_view" in request.session.keys():
            del request.session["prefers_web_public_view"]
    else:
        realm = get_valid_realm_from_request(request)

        # TODO: Ideally, we'd open Zulip directly as a spectator if
        # the URL had clicked a link to content on a web-public
        # stream.  We could maybe do this by parsing `next`, but it's
        # not super convenient with Zulip's hash-based URL scheme.

        # The "Access without an account" button on the login page
        # submits a POST to this page with this hidden field set.
        if request.POST.get("prefers_web_public_view") == "true":
            request.session["prefers_web_public_view"] = True
            # We serve a redirect here, rather than serving a page, to
            # avoid browser "Confirm form resubmission" prompts on reload.
            redirect_to = get_safe_redirect_to(request.POST.get("next"),
                                               realm.uri)
            return redirect(redirect_to)

        # See the assert in `home` above for why this must be true.
        assert request.session.get("prefers_web_public_view")

        # For users who have selected public access, we load the
        # spectator experience.  We fall through to the shared code
        # for loading the application, with user_profile=None encoding
        # that we're a spectator, not a logged-in user.
        user_profile = None

    update_last_reminder(user_profile)

    statsd.incr("views.home")

    # If a user hasn't signed the current Terms of Service, send them there
    if need_accept_tos(user_profile):
        return accounts_accept_terms(request)

    narrow, narrow_stream, narrow_topic = detect_narrowed_window(
        request, user_profile)

    if user_profile is not None:
        first_in_realm = realm_user_count(user_profile.realm) == 1
        # If you are the only person in the realm and you didn't invite
        # anyone, we'll continue to encourage you to do so on the frontend.
        prompt_for_invites = (first_in_realm
                              and not PreregistrationUser.objects.filter(
                                  referred_by=user_profile).count())
        needs_tutorial = user_profile.tutorial_status == UserProfile.TUTORIAL_WAITING

    else:
        first_in_realm = False
        prompt_for_invites = False
        # The current tutorial doesn't super make sense for logged-out users.
        needs_tutorial = False

    queue_id, page_params = build_page_params_for_home_page_load(
        request=request,
        user_profile=user_profile,
        realm=realm,
        insecure_desktop_app=insecure_desktop_app,
        narrow=narrow,
        narrow_stream=narrow_stream,
        narrow_topic=narrow_topic,
        first_in_realm=first_in_realm,
        prompt_for_invites=prompt_for_invites,
        needs_tutorial=needs_tutorial,
    )

    log_data = RequestNotes.get_notes(request).log_data
    assert log_data is not None
    log_data["extra"] = f"[{queue_id}]"

    csp_nonce = secrets.token_hex(24)

    user_permission_info = get_user_permission_info(user_profile)

    response = render(
        request,
        "zerver/app/index.html",
        context={
            "user_profile": user_profile,
            "page_params": page_params,
            "csp_nonce": csp_nonce,
            "color_scheme": user_permission_info.color_scheme,
        },
    )
    patch_cache_control(response,
                        no_cache=True,
                        no_store=True,
                        must_revalidate=True)
    return response
Example #17
0
 def make_request(self, user=None, auth=None, method=None):
     request = HttpRequest()
     if method:
         request.method = method
     request.META['REMOTE_ADDR'] = '127.0.0.1'
     request.META['SERVER_NAME'] = 'testserver'
     request.META['SERVER_PORT'] = 80
     # order matters here, session -> user -> other things
     request.session = self.session
     request.auth = auth
     request.user = user or AnonymousUser()
     request.superuser = Superuser(request)
     request.is_superuser = lambda: request.superuser.is_active
     return request
Example #18
0
 def test_disabled(self):
     self.assertFalse(is_spam('text', HttpRequest()))
Example #19
0
def maybe_send_to_registration(
        request: HttpRequest,
        email: str,
        full_name: str = '',
        mobile_flow_otp: Optional[str] = None,
        desktop_flow_otp: Optional[str] = None,
        is_signup: bool = False,
        password_required: bool = True,
        multiuse_object_key: str = '',
        full_name_validated: bool = False) -> HttpResponse:
    """Given a successful authentication for an email address (i.e. we've
    confirmed the user controls the email address) that does not
    currently have a Zulip account in the target realm, send them to
    the registration flow or the "continue to registration" flow,
    depending on is_signup, whether the email address can join the
    organization (checked in HomepageForm), and similar details.
    """

    # In the desktop and mobile registration flows, the sign up
    # happens in the browser so the user can use their
    # already-logged-in social accounts.  Then at the end, with the
    # user account created, we pass the appropriate data to the app
    # via e.g. a `zulip://` redirect.  We store the OTP keys for the
    # mobile/desktop flow in the session with 1-hour expiry, because
    # we want this configuration of having a successful authentication
    # result in being logged into the app to persist if the user makes
    # mistakes while trying to authenticate (E.g. clicks the wrong
    # Google account, hits back, etc.) during a given browser session,
    # rather than just logging into the webapp in the target browser.
    #
    # We can't use our usual pre-account-creation state storage
    # approach of putting something in PreregistrationUser, because
    # that would apply to future registration attempts on other
    # devices, e.g. just creating an account on the web on their laptop.
    assert not (mobile_flow_otp and desktop_flow_otp)
    if mobile_flow_otp:
        set_expirable_session_var(request.session,
                                  'registration_mobile_flow_otp',
                                  mobile_flow_otp,
                                  expiry_seconds=3600)
    elif desktop_flow_otp:
        set_expirable_session_var(request.session,
                                  'registration_desktop_flow_otp',
                                  desktop_flow_otp,
                                  expiry_seconds=3600)

    if multiuse_object_key:
        from_multiuse_invite = True
        multiuse_obj = Confirmation.objects.get(
            confirmation_key=multiuse_object_key).content_object
        realm = multiuse_obj.realm
        invited_as = multiuse_obj.invited_as
    else:
        from_multiuse_invite = False
        multiuse_obj = None
        try:
            realm = get_realm(get_subdomain(request))
        except Realm.DoesNotExist:
            realm = None
        invited_as = PreregistrationUser.INVITE_AS['MEMBER']

    form = HomepageForm({'email': email},
                        realm=realm,
                        from_multiuse_invite=from_multiuse_invite)
    if form.is_valid():
        # If the email address is allowed to sign up for an account in
        # this organization, construct a PreregistrationUser and
        # Confirmation objects, and then send the user to account
        # creation or confirm-continue-registration depending on
        # is_signup.
        try:
            prereg_user = PreregistrationUser.objects.filter(
                email__iexact=email, realm=realm).latest("invited_at")

            # password_required and full_name data passed here as argument should take precedence
            # over the defaults with which the existing PreregistrationUser that we've just fetched
            # was created.
            prereg_user.password_required = password_required
            update_fields = ["password_required"]
            if full_name:
                prereg_user.full_name = full_name
                prereg_user.full_name_validated = full_name_validated
                update_fields.extend(["full_name", "full_name_validated"])
            prereg_user.save(update_fields=update_fields)
        except PreregistrationUser.DoesNotExist:
            prereg_user = create_preregistration_user(
                email,
                request,
                password_required=password_required,
                full_name=full_name,
                full_name_validated=full_name_validated)

        if multiuse_obj is not None:
            request.session.modified = True
            streams_to_subscribe = list(multiuse_obj.streams.all())
            prereg_user.streams.set(streams_to_subscribe)
            prereg_user.invited_as = invited_as
            prereg_user.save()

        # We want to create a confirmation link to create an account
        # in the current realm, i.e. one with a hostname of
        # realm.host.  For the Apache REMOTE_USER_SSO auth code path,
        # this is preferable over realm.get_host() because the latter
        # contains the port number of the Apache instance and we want
        # to send the user back to nginx.  But if we're in the realm
        # creation code path, there might not be a realm yet, so we
        # have to use request.get_host().
        if realm is not None:
            host = realm.host
        else:
            host = request.get_host()
        confirmation_link = create_confirmation_link(
            prereg_user, host, Confirmation.USER_REGISTRATION)
        if is_signup:
            return redirect(confirmation_link)

        context = {
            'email': email,
            'continue_link': confirmation_link,
            'full_name': full_name
        }
        return render(request,
                      'zerver/confirm_continue_registration.html',
                      context=context)

    # This email address it not allowed to join this organization, so
    # just send the user back to the registration page.
    url = reverse('register')
    context = login_context(request)
    extra_context = {
        'form': form,
        'current_url': lambda: url,
        'from_multiuse_invite': from_multiuse_invite,
        'multiuse_object_key': multiuse_object_key,
        'mobile_flow_otp': mobile_flow_otp,
        'desktop_flow_otp': desktop_flow_otp
    }  # type: Mapping[str, Any]
    context.update(extra_context)
    return render(request, 'zerver/accounts_home.html', context=context)
Example #20
0
 def test_akismet_nospam(self):
     self.mock_akismet('false')
     self.assertFalse(is_spam('text', HttpRequest()))
Example #21
0
 def setUp(self):
     request = HttpRequest()
     request.META = {'HTTP_HOST': 'example.com'}
     self.site = RequestSite(request)
Example #22
0
 def test_home_page_returns_correct_html(self):
     request = HttpRequest()
     response = home(request)
     self.assertIn(b'<h1>Contact Form</h1>', response.content)
Example #23
0
 def test_old_style_request(self):
     """The request has correct `site` attribute."""
     middleware = CurrentSiteMiddleware()
     request = HttpRequest()
     middleware.process_request(request)
     self.assertEqual(request.site.id, settings.SITE_ID)
Example #24
0
 def test_set_without_xheader(self):
     self.settings_module.SECURE_PROXY_SSL_HEADER = (
         'HTTP_X_FORWARDED_PROTOCOL', 'https')
     req = HttpRequest()
     self.assertEqual(req.is_secure(), False)
Example #25
0
 def test_request(self):
     def get_response(request):
         return HttpResponse(str(request.site.id))
     response = CurrentSiteMiddleware(get_response)(HttpRequest())
     self.assertContains(response, settings.SITE_ID)
Example #26
0
    def make_request(self, user=None, auth=None, method=None):
        request = HttpRequest()
        if method:
            request.method = method
        request.META["REMOTE_ADDR"] = "127.0.0.1"
        request.META["SERVER_NAME"] = "testserver"
        request.META["SERVER_PORT"] = 80
        request.GET = {}
        request.POST = {}

        # order matters here, session -> user -> other things
        request.session = self.session
        request.auth = auth
        request.user = user or AnonymousUser()
        request.superuser = Superuser(request)
        request.is_superuser = lambda: request.superuser.is_active
        request.successful_authenticator = None
        return request
Example #27
0
def UploadFile(request):
    """上传文件"""
    if not request.method == "POST":
        return HttpResponse(json.dumps(u"{'state:'ERROR'}"),
                            content_type="application/javascript")

    state = "SUCCESS"
    action = request.GET.get("action")
    # 上传文件
    upload_field_name = {
        "uploadfile": "fileFieldName",
        "uploadimage": "imageFieldName",
        "uploadscrawl": "scrawlFieldName",
        "catchimage": "catcherFieldName",
        "uploadvideo": "videoFieldName",
    }
    UploadFieldName = request.GET.get(
        upload_field_name[action],
        USettings.UEditorUploadSettings.get(action, "upfile"))

    # 上传涂鸦,涂鸦是采用base64编码上传的,需要单独处理
    if action == "uploadscrawl":
        upload_file_name = "scrawl.png"
        upload_file_size = 0
    else:
        # 取得上传的文件
        file = request.FILES.get(UploadFieldName, None)
        if file is None:
            return HttpResponse(json.dumps(u"{'state:'ERROR'}"),
                                content_type="application/javascript")
        upload_file_name = file.name
        upload_file_size = file.size

    # 取得上传的文件的原始名称
    upload_original_name, upload_original_ext = os.path.splitext(
        upload_file_name)

    # 文件类型检验
    upload_allow_type = {
        "uploadfile": "fileAllowFiles",
        "uploadimage": "imageAllowFiles",
        "uploadvideo": "videoAllowFiles"
    }
    if action in upload_allow_type:
        allow_type = list(
            request.GET.get(
                upload_allow_type[action],
                USettings.UEditorUploadSettings.get(upload_allow_type[action],
                                                    "")))
        if upload_original_ext not in allow_type:
            state = u"服务器不允许上传%s类型的文件。" % upload_original_ext

    # 大小检验
    upload_max_size = {
        "uploadfile": "filwMaxSize",
        "uploadimage": "imageMaxSize",
        "uploadscrawl": "scrawlMaxSize",
        "uploadvideo": "videoMaxSize"
    }
    max_size = int(
        request.GET.get(
            upload_max_size[action],
            USettings.UEditorUploadSettings.get(upload_max_size[action], 0)))
    if max_size != 0:
        from .utils import FileSize
        MF = FileSize(max_size)
        if upload_file_size > MF.size:
            state = u"上传文件大小不允许超过%s。" % MF.FriendValue

    # 检测保存路径是否存在,如果不存在则需要创建
    upload_path_format = {
        "uploadfile": "filePathFormat",
        "uploadimage": "imagePathFormat",
        "uploadscrawl": "scrawlPathFormat",
        "uploadvideo": "videoPathFormat"
    }

    path_format_var = get_path_format_vars()
    path_format_var.update({
        "basename": upload_original_name,
        "extname": upload_original_ext[1:],
        "filename": upload_file_name,
    })
    # 取得输出文件的路径
    OutputPathFormat, OutputPath, OutputFile = get_output_path(
        request, upload_path_format[action], path_format_var)

    # 所有检测完成后写入文件
    if state == "SUCCESS":
        if action == "uploadscrawl":
            state = save_scrawl_file(request,
                                     os.path.join(OutputPath, OutputFile))
        else:
            # 保存到文件中,如果保存错误,需要返回ERROR
            state = save_upload_file(file,
                                     os.path.join(OutputPath, OutputFile))

    # 在django项目中配置你的产品域名

    # project_url_config = USettings.gSettings.PROJECT_URL

    project_url_config = 'http://' + HttpRequest.get_host(request)
    # 返回数据
    return_info = {
        # 保存后的文件名称
        # 'url': urljoin(project_url_config+USettings.gSettings.MEDIA_URL, OutputPathFormat),
        'url':
        urljoin(project_url_config + USettings.gSettings.MEDIA_URL,
                OutputPathFormat),
        # 原始文件名
        'original':
        upload_file_name,
        'type':
        upload_original_ext,
        # 上传状态,成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
        'state':
        state,
        'size':
        upload_file_size
    }
    return HttpResponse(json.dumps(return_info, ensure_ascii=False),
                        content_type="application/javascript")
Example #28
0
 def test_redirect_report_builder(self):
     report, view = self._build_report_and_view()
     report.report_meta.created_by_builder = True
     report.save()
     request = HttpRequest()
     self.assertTrue(view.should_redirect_to_paywall(request))
Example #29
0
 def test_default_argument_suppresses_exceptions(self):
     response = HttpResponse()
     response.set_signed_cookie("c", "hello")
     request = HttpRequest()
     request.COOKIES["c"] = response.cookies["c"].value[:-2] + "$$"
     self.assertIsNone(request.get_signed_cookie("c", default=None))
Example #30
0
def getBaseState(request, area='', nowDate=''):
    if area is None and nowDate is None:
        return HttpRequest('parameters is not enough')
    try:
        d = datetime.strptime(nowDate, '%Y-%m-%d %H:%M')
    except Exception as err:
        # 为d赋值now时,注意需要加入时区
        d = datetime.utcnow().replace(tzinfo=utc)
    # 好像是时区问题所以必须加8小时才行
    # 此处暂时注释掉,不需要加8
    # d = d.astimezone(pytz.UTC)+timedelta(hours=8)
    #bbxinfolist = BBXInfo.objects.all().filter(area=area)
    timelimit = d.__str__()
    lst = []
    #for x in bbxinfolist:
    #    dic = dict()
    #    dic['code']=x.code
    #    dic['name']=x.code
    #    dt=x.bbxspacetempinfo_set.filter(nowdate__lte=timelimit).aggregate(Max('nowdate'))
    #    if dt['nowdate__max'] is not None:
    #        dic['state'] = dt['nowdate__max']
    #        dic['lastestTime'] = dt['nowdate__max'].strftime('%Y-%m-%d %H:%M:%S')
    #    else:
    #        dic['state']='invalid'
    #        dic['lastestTime']='近期没有数据'
    #    lst.append(dic)
    #不知道这么比是不是会有bug 直接用datetime比可能更稳一点
    querySet = BBXSpaceTempInfo.objects.values('code').annotate(
        Max('nowdate')).filter(bid__area=area, nowdate__lte=timelimit)
    for x in querySet:
        dic = dict()
        dic['code'] = x['code']
        dic['name'] = x['code']
        if x['nowdate__max'] is not None:
            dic['state'] = x['nowdate__max']
            dic['lastestTime'] = x['nowdate__max'].strftime(
                '%Y-%m-%d %H:%M:%S')
        else:
            dic['state'] = 'invalid'
            dic['lastesttime'] = '近期没有数据'
        lst.append(dic)

    ok_date = d - timedelta(hours=dateState_dict['normal'])
    late_date = d - timedelta(hours=dateState_dict['late'])
    notarrival_date = d - timedelta(hours=dateState_dict['noarrival'])

    #根据日期判断状态
    for x in lst:
        state = x['state']
        if state != 'invalid':
            #光用秒减的话int可能会溢出导致判断失败,所以加个days判断
            if state <= notarrival_date:
                state = 'invalid'
            elif state < ok_date:
                if state < late_date:
                    state = 'noarrival'
                else:
                    state = 'late'
            else:
                state = 'ok'
        x['state'] = state
    return HttpResponse(json.dumps(lst), content_type="application/json")
Example #31
0
def send_email_report(self, recipient_emails, domain, report_slug, report_type,
                      request_data, once, cleaned_data):
    """
    Function invokes send_HTML_email to email the html text report.
    If the report is too large to fit into email then a download link is
    sent via email to download report
    :Parameter recipient_list:
            list of recipient to whom email is to be sent
    :Parameter domain:
            domain name
    :Parameter report_slug:
            report slug
    :Parameter report_type:
            type of the report
    :Parameter request_data:
            Dict containing request data
    :Parameter once
            boolean argument specifying whether the report is once off report
            or scheduled report
    :Parameter cleaned_data:
            Dict containing cleaned data from the submitted form
    """
    from corehq.apps.reports.views import _render_report_configs, render_full_report_notification

    user_id = request_data['couch_user']
    couch_user = CouchUser.get_by_user_id(user_id)
    mock_request = HttpRequest()

    mock_request.method = 'GET'
    mock_request.GET = request_data['GET']

    config = ReportConfig()

    # see ReportConfig.query_string()
    object.__setattr__(config, '_id', 'dummy')
    config.name = _("Emailed report")
    config.report_type = report_type
    config.report_slug = report_slug
    config.owner_id = user_id
    config.domain = domain

    config.start_date = request_data['datespan'].startdate.date()
    if request_data['datespan'].enddate:
        config.date_range = 'range'
        config.end_date = request_data['datespan'].enddate.date()
    else:
        config.date_range = 'since'

    GET = dict(six.iterlists(request_data['GET']))
    exclude = ['startdate', 'enddate', 'subject', 'send_to_owner', 'notes', 'recipient_emails']
    filters = {}
    for field in GET:
        if field not in exclude:
            filters[field] = GET.get(field)

    config.filters = filters

    subject = cleaned_data['subject'] or _("Email report from CommCare HQ")

    content = _render_report_configs(
        mock_request, [config], domain, user_id, couch_user, True, lang=couch_user.language,
        notes=cleaned_data['notes'], once=once
    )[0]
    body = render_full_report_notification(None, content).content

    try:
        for recipient in recipient_emails:
            send_HTML_email(subject, recipient,
                            body, email_from=settings.DEFAULT_FROM_EMAIL,
                            smtp_exception_skip_list=LARGE_FILE_SIZE_ERROR_CODES)

    except Exception as er:
        if getattr(er, 'smtp_code', None) in LARGE_FILE_SIZE_ERROR_CODES:
            # If the smtp server rejects the email because of its large size.
            # Then sends the report download link in the email.
            report_state = {
                'request': request_data,
                'request_params': json_request(request_data['GET']),
                'domain': domain,
                'context': {},
            }
            export_all_rows_task(config.report, report_state, recipient_list=recipient_emails)
        else:
            self.retry(exc=er)