Ejemplo n.º 1
0
 def test_mutable_copy(self):
     """A copy of a QueryDict is mutable."""
     q = QueryDict(str('')).copy()
     self.assertRaises(KeyError, q.__getitem__, "foo")
     q['name'] = 'john'
     self.assertEqual(q['name'], 'john')
Ejemplo n.º 2
0
def resultsearchrule(request, id=None):
    if request.FILES:
        uploaded_file = request.FILES['file']
        str_text = ''
        for line in uploaded_file:
            str_text = str_text + line.decode(
            )  # "str_text" will be of `str` type
        file_name_upload = str(request.FILES['file'])
        with open(file_name_upload, 'w') as f:
            f.write(str_text)
        dict_file.update([(str(request.FILES['file']), file_name_upload)])
    # do something
    elif request.method == "POST":
        response_data = {'result': {}}
        fromJs = QueryDict(request.body)

        listResult = []
        if fromJs['content'] == "":
            response_data = {"result": "Bạn chưa nhập dữ liệu."}

            return render(request,
                          'first_app/resultsearchrule.html',
                          context={"result": str(response_data)})
        else:
            #reg = web.list_regular(fromJs['content'])
            for name in dict_file:
                file_name = name
                list_command = open(file_name, 'r').readlines()
                list_ip = fromJs['content']
                # print(list_command)
                result_func = web.search_rule(file_name, list_command, list_ip)
                response_data['result'].update(result_func)
                # pprint.pprint(response_data)
            dict_file.clear()
            THIS_FOLDER = os.path.dirname(
                os.path.dirname(os.path.abspath(__file__)))
            os.chdir(THIS_FOLDER)
            my_folder = os.getcwd()
            my_file_source = os.path.join(my_folder, file_name + '.csv')
            with open(my_file_source, 'w', newline='') as file:
                writer = csv.writer(file)
                writer.writerow([
                    "Configuration", "Rule Type delete", "Device",
                    "Policy/Term name", "application", "Protocol",
                    "Source VLAN", "Source IP", "Source Port", "Dest VLAN",
                    "Dest IP", "Dest Port"
                ])
                for filename in response_data['result']:
                    for dict_rule in response_data['result'][filename]:
                        for rule in response_data['result'][filename][
                                dict_rule]:
                            rule_detail = response_data['result'][filename][
                                dict_rule][rule]
                            conf = rule_detail['config']
                            rule_type_delete = dict_rule
                            device = filename
                            term_name = rule_detail['term']
                            application = rule_detail['application']
                            protocol = rule_detail['protocol']
                            source_vlan = rule_detail['fzone']
                            source_ip = rule_detail['sourceip']
                            dest_ip = rule_detail['destip']
                            dest_vlan = rule_detail['tzone']
                            source_port = rule_detail['sourceport']
                            dest_port = rule_detail['destport']
                            writer.writerow([
                                conf, device, term_name, application, protocol,
                                source_vlan, source_ip, source_port, dest_vlan,
                                dest_ip, dest_port
                            ])
            my_file_dest = os.path.join(my_folder, "static",
                                        file_name + '.csv')
            shutil.move(my_file_source, my_file_dest)
            return render(request,
                          'first_app/resultsearchrule.html',
                          context={
                              "result": dict(response_data['result']),
                              "filename": file_name + ".csv"
                          })
    return render(request, 'first_app/resultsearchrule.html')
Ejemplo n.º 3
0
def _make_query_url(url, query):
    encoded = QueryDict('', mutable=True)
    encoded.update(query)
    return "%s?%s" % (url, encoded.urlencode())
Ejemplo n.º 4
0
def AssetsEditView(request, pk):
    data = QueryDict(request.body)
    jsondata = data.dict()
    Assets.objects.filter(pk=pk).update(**jsondata)

    return HttpResponse("编辑成功!")
Ejemplo n.º 5
0
 def GET(self):
     return QueryDict(self.META['QUERY_STRING'])
Ejemplo n.º 6
0
 def post(self, request):
     params = QueryDict(request.body)
     if request.META.get('HTTP_X_FORWARDED_FOR'):
         ip = request.META.get('HTTP_X_FORWARDED_FOR')
     else:
         ip = request.META.get('REMOTE_ADDR')
     if ip in getattr(settings, 'BLOCKED_IPS', []):
         return HttpResponseForbidden('<h1>Forbbidden</h1>')
     user = ShangmiUser.objects.get(
         pk=int(user_cache.get(params.get("token"))))
     order_id = params.get('order_id')
     amount = params.get("need")
     log = UserPayLog.objects.get(id=order_id)
     randuuid = uuid.uuid4()
     nonce_str = str(randuuid).replace('-', '')
     out_trade_no = log.wx_pay_num
     # log.wx_pay_num = out_trade_no
     # log.save()
     url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
     data = {}
     data['body'] = 'ShangMi'.encode('utf-8')
     data['mch_id'] = settings.MCHID
     data['nonce_str'] = nonce_str
     # data['device_info'] = 'WEB'
     data['total_fee'] = str(int(amount))
     data['spbill_create_ip'] = ip
     # data['fee_type'] = 'CNY'
     data['openid'] = user.openid
     data['out_trade_no'] = out_trade_no
     data['notify_url'] = 'https://sharemsg.cn/shangmi/api/v1/pay/notify'
     data['appid'] = settings.PAY_APPID
     data['trade_type'] = 'JSAPI'
     data['sign'] = sign(data, settings.PAY_KEY)
     template = """
                 <xml>
                 <appid>{appid}</appid>
                 <body>{body}</body>
                 <mch_id>{mch_id}</mch_id>
                 <nonce_str>{nonce_str}</nonce_str>
                 <notify_url>{notify_url}</notify_url>
                 <openid>{openid}</openid>
                 <out_trade_no>{out_trade_no}</out_trade_no>
                 <spbill_create_ip>{spbill_create_ip}</spbill_create_ip>
                 <total_fee>{total_fee}</total_fee>
                 <trade_type>{trade_type}</trade_type>
                 <sign>{sign}</sign>
                 </xml>
             """
     content = template.format(**data)
     headers = {'Content-Type': 'application/xml'}
     raw = requests.post(url, data=content, headers=headers)
     rdict = xml_response_to_dict(raw)
     # print('=------',rdict, '--------------')
     return_data = {}
     if rdict['return_code'] == 'SUCCESS' and rdict[
             'result_code'] == 'SUCCESS':
         randuuid = uuid.uuid4()
         nonce_str = str(randuuid).replace('-', '')
         time_stamp = str(int(time.time()))
         sign_data = {}
         sign_data['appId'] = rdict['appid']
         sign_data['nonceStr'] = nonce_str
         sign_data['package'] = 'prepay_id=%s' % rdict['prepay_id']
         sign_data['signType'] = 'MD5'
         sign_data['timeStamp'] = time_stamp
         paySign = sign(sign_data, settings.PAY_KEY)
         return_data['appId'] = rdict['appid']
         return_data['paySign'] = paySign
         return_data['nonceStr'] = nonce_str
         return_data['timeStamp'] = time_stamp
         return_data['package'] = 'prepay_id=%s' % rdict['prepay_id']
         return_data['signType'] = 'MD5'
         return JsonResponse({'data': return_data, "code": 0})
     else:
         return JsonResponse({'code': 1, 'data': u'支付失败'})
Ejemplo n.º 7
0
 def _build_POST(self, job_data):
     return QueryDict(job_data['POST'].encode('utf8'))
Ejemplo n.º 8
0
 def  put(self, request, **kwargs):
     webdata = QueryDict(request.body).dict()
     print(webdata)
     pk = kwargs.get('pk')
     self.model.objects.filter(pk=pk).update(**webdata)
     return JsonResponse({'status': 0})
Ejemplo n.º 9
0
def quiz_resultaat(request, quiz_id):
    quiz = Quiz.objects.get(pk=quiz_id)
    vragen_list = quiz.vraag_set.all()
    user_antwoorden = []
    max_score = 0
    score = 0

    q = QueryDict()
    q = request.POST
    user_antwoorden.extend(q.items())
    user_antwoorden.pop(0)
    
    user_antwoord_ids = [antwoord[0] for antwoord in user_antwoorden]
    
    user_antwoord_ids = [id for id in user_antwoord_ids if str.isdigit(id)]

    # Map list naar integers
    user_antwoord_ids = list(map(int, user_antwoord_ids))

    # Check of de vraag een ja/nee vraag is en indien ja, vervang vraag id naar antwoord id als het gegeven antwoord juist is.
    for id in user_antwoord_ids:
        for vraag in vragen_list:
            if vraag.id == id and vraag.vraag_type == 'jaNee':
                user_antwoord = request.POST.get(str(id))
                juiste_antwoord = vraag.antwoord_set.get(antwoord_juist=True)
                if user_antwoord.lower() == juiste_antwoord.antwoord_tekst.lower():
                    user_antwoord_ids.remove(id)
                    user_antwoord_ids.append(juiste_antwoord.id)
                else:
                    user_antwoord_ids.remove(id)
    
    juiste_antwoorden = Antwoord.objects.filter(antwoord_juist=True)

    # Totale score berekenen per quiz.
    for vraag in vragen_list:
        juiste_antwoorden_per_quiz = vraag.antwoord_set.filter(antwoord_juist=True)
        
        for antwoord in juiste_antwoorden_per_quiz:
            max_score += antwoord.antwoord_score
    
    def get_antwoord_ids():
        list_ids = []
        for vraag in vragen_list:
            juiste_antwoorden = vraag.antwoord_set.filter(antwoord_juist=True)
            for antwoord in juiste_antwoorden:
                list_ids.append(antwoord.id)
        return list_ids

    juiste_antwoorden_ids = get_antwoord_ids()

    # Vergelijken tussen gegeven antwoorden en de juiste antwoorden.
    matches = set(user_antwoord_ids).intersection(juiste_antwoorden_ids)

    for match in matches:
        vraag = Antwoord.objects.get(id=match).vraag
        juist_antwoord = Antwoord.objects.get(id=match)

        if vraag.vraag_type == 'open':
            user_value = q.get(str(match))

            if user_value.lower() == juist_antwoord.antwoord_tekst.lower():
                score += juist_antwoord.antwoord_score
        else:
            score += juist_antwoord.antwoord_score

    return render(request, 'resultaat.html', {'user_score': score, 'max_score': max_score, 'max_score_helft': max_score / 2})
Ejemplo n.º 10
0
 def test_immutable_get_with_default(self):
     q = QueryDict(str(''))
     self.assertEqual(q.get('foo', 'default'), 'default')
Ejemplo n.º 11
0
 def post(self, request):
     webdata = QueryDict(request.body).dict()
     env = webdata.get('env')
     qs = dbconf.objects.filter(env=env)
     dbs = [obj.name for obj in qs]
     return  JsonResponse({'status': 0,'data':dbs})
Ejemplo n.º 12
0
 def test_missing_key(self):
     q = QueryDict(str(''))
     self.assertRaises(KeyError, q.__getitem__, 'foo')
Ejemplo n.º 13
0
 def test_update_from_querydict(self):
     """Regression test for #8278: QueryDict.update(QueryDict)"""
     x = QueryDict(str("a=1&a=2"), mutable=True)
     y = QueryDict(str("a=3&a=4"))
     x.update(y)
     self.assertEqual(x.getlist('a'), ['1', '2', '3', '4'])
Ejemplo n.º 14
0
 def test_mutable_delete(self):
     q = QueryDict(str('')).copy()
     q['name'] = 'john'
     del q['name']
     self.assertFalse('name' in q)
Ejemplo n.º 15
0
 def get_filters(self):
     """Parse querystring and returns a dict."""
     return QueryDict(self.querystring, mutable=True)
Ejemplo n.º 16
0
            except (urllib2.HTTPError, urllib2.URLError), e:
                logger.warn('facebook encountered a timeout or error %s',
                            unicode(e))
                attempts -= 1
                if not attempts:
                    raise
            finally:
                if response_file:
                    response_file.close()

        try:
            parsed_response = json.loads(response)
            logger.info('facebook send response %s' % parsed_response)
        except Exception, e:
            #using exception because we need to support multiple json libs :S
            parsed_response = QueryDict(response, True)
            logger.info('facebook send response %s' % parsed_response)

        if parsed_response and isinstance(parsed_response, dict):
            #of course we have two different syntaxes
            if parsed_response.get('error'):
                cls.raise_error(parsed_response['error']['type'],
                                parsed_response['error']['message'])
            elif parsed_response.get('error_code'):
                cls.raise_error(parsed_response['error_code'],
                                parsed_response['error_msg'])

        return parsed_response

    @classmethod
    def raise_error(self, type, message):
Ejemplo n.º 17
0
def execute_directly(request,
                     query,
                     query_server=None,
                     design=None,
                     on_success_url=None,
                     on_success_params=None,
                     **kwargs):
    """
  execute_directly(request, query_msg, tablename, design) -> HTTP response for execution

  This method wraps around dbms.execute_query() to take care of the HTTP response
  after the execution.

    query
      The HQL model Query object.

    query_server
      To which Query Server to submit the query.
      Dictionary with keys: ['server_name', 'server_host', 'server_port'].

    design
      The design associated with the query.

    on_success_url
      Where to go after the query is done. The URL handler may expect an option "context" GET
      param. (See ``watch_query``.) For advanced usage, on_success_url can be a function, in
      which case the on complete URL is the return of:
        on_success_url(history_obj) -> URL string
      Defaults to the view results page.

    on_success_params
      Optional params to pass to the on_success_url (in additional to "context").

  Note that this may throw a Beeswax exception.
  """
    if design is not None:
        authorized_get_design(request, design.id)

    db = dbms.get(request.user, query_server)
    database = query.query.get('database', 'default')
    db.use(database)

    query_history = db.execute_query(query, design)

    watch_url = reverse(get_app_name(request) + ':watch_query_history',
                        kwargs={'query_history_id': query_history.id})

    # Prepare the GET params for the watch_url
    get_dict = QueryDict(None, mutable=True)

    # (1) on_success_url
    if on_success_url:
        if callable(on_success_url):
            on_success_url = on_success_url(query_history)
        get_dict['on_success_url'] = on_success_url

    # (2) misc
    if on_success_params:
        get_dict.update(on_success_params)

    return format_preserving_redirect(request, watch_url, get_dict)
Ejemplo n.º 18
0
        def _test(data, expected, **kwargs):
            fs = FooFilterSet(data=QueryDict(data), queryset=[], **kwargs)

            assert set(fs.get_specs()) == set(expected)
Ejemplo n.º 19
0
    # By default List[anything] is treated for body
    return {
        "body": body,
    }


client = NinjaClient(router)


@pytest.mark.parametrize(
    # fmt: off
    "path,kwargs,expected_response",
    [
        (
            "/list1?query=1&query=2",
            dict(data=QueryDict("form=3&form=4")),
            {
                "query": [1, 2],
                "form": [3, 4]
            },
        ),
        (
            "/list2?query=1&query=2",
            dict(json=[5, 6]),
            {
                "query": [1, 2],
                "body": [5, 6]
            },
        ),
        (
            "/list3",
Ejemplo n.º 20
0
 def test_from_querydict(self):
     di = dict(a=1, b=[2, 3])
     self.assertEqual(to_querydict(di), QueryDict("a=1&b=2&b=3"))
Ejemplo n.º 21
0
def handle_successful_payment(sender, **kwargs):
    from course.models import Enrollment, Session, reset_classes_json

    # these two errors occurred because of the donate button on the front page.
    # they can be removed by checking for that
    if not sender.txn_type == "cart":
        # handled by membership.listeners
        return
    params = QueryDict(sender.query)
    _uid = str(params.get('custom', None))
    user, new_user = get_or_create_student(params)
    user.active = True
    user.save()
    if params.get('invoice', None):
        return handle_successful_store_payment(sender, user)
    if not "num_cart_items" in params:
        mail_admins("No cart items found for %s" % sender.txn_id, "")
        return
    item_count = int(params['num_cart_items'])

    enrollments = []
    error_sessions = []
    fails = []
    for i in range(1, item_count + 1):
        pp_amount = float(params['mc_gross_%d' % i])
        quantity = int(params['quantity%s' % i])

        try:
            session = Session.objects.get(id=int(params['item_number%d' %
                                                        (i, )]))
        except Session.DoesNotExist:
            fails.append(("Session not found", traceback.format_exc()))
            continue
        except ValueError:
            fails.append(
                ("Non-integer session number", traceback.format_exc()))
            continue

        enrollment, new = Enrollment.objects.get_or_create(user=user,
                                                           session=session)
        if enrollment.transaction_ids and (sender.txn_id
                                           in enrollment.transaction_ids):
            fails.append(
                ("Multiple transaction ids blocked for enrollment #%s" %
                 enrollment.id, ""))
            continue
        enrollment.transaction_ids = (enrollment.transaction_ids
                                      or "") + sender.txn_id + "|"
        NotifyCourse.objects.filter(user=user, course=session.course).delete()
        if new:
            enrollment.quantity = quantity
        else:
            enrollment.quantity += quantity
        enrollment.save()
        enrollments.append(enrollment)
        price_multiplier = (100 - user.level.discount_percentage) / 100.
        # We're ignoring people who overpay since this happens when a member doesn't login (no discount)
        if pp_amount < price_multiplier * session.course.fee * int(quantity):
            l = [
                "PP cost: %s" % pp_amount,
                "Expected Cost: %s" %
                (price_multiplier * session.course.fee * int(quantity)),
                "discount: %s" % user.level.discount_percentage,
                "Session Fee: %s" % session.course.fee,
                "Session Id: %s" % session.id,
                "Quantity: %s" % enrollment.quantity,
                "PP Email: %s" % sender.payer_email,
                "U Email: %s" % user.email,
                "u_id: %s" % _uid,  #if this is none they won't get a discount
            ]
            error_sessions.append("\n".join(l))
        if enrollment.session.total_students > enrollment.session.course.max_students:
            s = "Session #%s overfilled. Please see https://txrxlabs.org/admin/course/session/%s/"
            mail_admins("My Course over floweth",
                        s % (enrollment.session.pk, enrollment.session.pk))

    if fails:
        body = "=======\n\n".join(["%s\n%s\n\n" % (s, b) for s, b in fails])
        mail_admins("%s fails in purchasing process" % len(fails), body)
    values = {
        'enrollments': enrollments,
        'user': user,
        'new_user': new_user,
        'settings': settings
    }
    if enrollments:
        body = render_to_string("email/course_enrollment.html", values)
        subject = "Course enrollment confirmation"
        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [user.email])
    if error_sessions:
        mail_admins("Enrollment Error", "\n\n".join(error_sessions))
    reset_classes_json("classes reset during course enrollment")
Ejemplo n.º 22
0
def simple(request):

    if request.method == 'POST':
        # print(request.POST)
        query_dict = QueryDict('', mutable=True)
        query_dict.update(request.POST)

        # тут забираю код с формы и оформляю его в виде .py файла
        # print("RAW POST DATA: {}".format(request.POST['text']))
        code = request.POST['text']
        query_dict['text'] = code
        # добавляем к возвращенному run_algorithm датафрейму вызов метода сохранения его в .json
        code = code.strip() + ".to_json('perf.json')"
        # pprint(code)
        with open('temp.py', 'w', encoding='utf-8') as f:
            f.write(code)

        # выводит текущую рабочую директорию
        # print(os.path.abspath(os.getcwd()))

        # запускает python из среды zip и выполняет подготовленный скрипт
        process = subprocess.Popen(
            ["..\Zipline\env\zip\Scripts\python.exe", "-W ignore", "temp.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)
        data = process.communicate()

        # выводы print() скрипта
        output = "; ".join(str(data[0]).split(r'\r\n'))[2:-2]

        form = SnippetForm(query_dict)
        # form.save()

        df = pd.read_json('perf.json')

        # plot_div = plot([{'x': df.index, 'y': df[col], 'name': col}  for col in df.columns], output_type='div')
        plot_div = plot([{
            'x': df.index,
            'y': df['portfolio_value'],
            'name': 'portfolio'
        }],
                        output_type='div')

        with open("plot_div", 'w') as f:
            f.write(plot_div)
        # pprint(plot_div)

        # пример отрисовки графика с помощью plotly
        # x_data = [0,1,2,3]
        # y_data = [x**2 for x in x_data]
        # plot_div = plot([Scatter(x=x_data, y=y_data,
        #                 mode='lines', name='test',
        #                 opacity=0.8, marker_color='green')],
        #                 output_type='div')
        # return render(request, "/editor", context={'plot_div': plot_div})
        with open("plot_div", 'r') as f:
            plot_div = f.read()
            # pprint(plot_div)
            return render(request,
                          "snippets.html",
                          context={
                              "form": form,
                              "snippets": "",
                              "output": output,
                              "plot_div": plot_div
                          })

    else:
        form = SnippetForm()

    snippets = []

    return render(
        request,
        "snippets.html",
        {
            "form": form,
            # "snippets": Snippet.objects.all(),
            "snippets": "",
            "output": "",
            "plot_div": ""
        })
Ejemplo n.º 23
0
def check_course_access(course,
                        user,
                        action,
                        check_if_enrolled=False,
                        check_survey_complete=True):
    """
    Check that the user has the access to perform the specified action
    on the course (CourseDescriptor|CourseOverview).

    check_if_enrolled: If true, additionally verifies that the user is enrolled.
    check_survey_complete: If true, additionally verifies that the user has completed the survey.
    """
    # Allow staff full access to the course even if not enrolled
    if has_access(user, 'staff', course.id):
        return

    request = get_current_request()
    check_content_start_date_for_masquerade_user(course.id, user, request,
                                                 course.start)

    access_response = has_access(user, action, course, course.id)
    if not access_response:
        # Redirect if StartDateError
        if isinstance(access_response, StartDateError):
            start_date = strftime_localized(course.start, 'SHORT_DATE')
            params = QueryDict(mutable=True)
            params['notlive'] = start_date
            raise CourseAccessRedirect(
                '{dashboard_url}?{params}'.format(
                    dashboard_url=reverse('dashboard'),
                    params=params.urlencode()), access_response)

        # Redirect if AuditExpiredError
        if isinstance(access_response, AuditExpiredError):
            params = QueryDict(mutable=True)
            params[
                'access_response_error'] = access_response.additional_context_user_message
            raise CourseAccessRedirect(
                '{dashboard_url}?{params}'.format(
                    dashboard_url=reverse('dashboard'),
                    params=params.urlencode()), access_response)

        # Redirect if the user must answer a survey before entering the course.
        if isinstance(access_response, MilestoneAccessError):
            raise CourseAccessRedirect(
                '{dashboard_url}'.format(dashboard_url=reverse('dashboard'), ),
                access_response)

        # Deliberately return a non-specific error message to avoid
        # leaking info about access control settings
        raise CoursewareAccessException(access_response)

    if check_if_enrolled:
        # If the user is not enrolled, redirect them to the about page
        if not CourseEnrollment.is_enrolled(user, course.id):
            raise CourseAccessRedirect(
                reverse('about_course', args=[six.text_type(course.id)]))

    # Redirect if the user must answer a survey before entering the course.
    if check_survey_complete and action == 'load':
        if is_survey_required_and_unanswered(user, course):
            raise CourseAccessRedirect(
                reverse('course_survey', args=[six.text_type(course.id)]))
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.language = "en"
     self.base_valid_query = QueryDict("barcode_length=12&paper_size=a4")
Ejemplo n.º 25
0
 def _parse_response(self, response):
     """Turn the PayPal response into a dict"""
     q = QueryDict(response, encoding='UTF-8').dict()
     return {k.lower(): v for k, v in q.items()}
Ejemplo n.º 26
0
 def test_subtitle_letter(self):
     query = QueryDict("paper_size=letter")
     generator = LeftRightCardsResourceGenerator(query)
     self.assertEqual(generator.subtitle, "letter")
Ejemplo n.º 27
0
def send_bookkeeper_email(month=None, year=None, emails=None):
    today = datetime.date.today()

    # now, make sure that we send out LAST month's invoices if we did
    # not specify a month or year.
    today = get_previous_month_date_range(today)[0]

    month = month or today.month
    year = year or today.year

    from corehq.apps.accounting.interface import InvoiceInterface
    request = HttpRequest()
    params = urlencode((
        ('report_filter_statement_period_use_filter', 'on'),
        ('report_filter_statement_period_month', month),
        ('report_filter_statement_period_year', year),
    ))
    request.GET = QueryDict(params)
    request.couch_user = FakeUser(
        domain="hqadmin",
        username="******",
    )
    invoice = InvoiceInterface(request)
    invoice.is_rendered_as_email = True
    first_of_month = datetime.date(year, month, 1)
    email_context = {
        'month': first_of_month.strftime("%B"),
    }
    email_content = render_to_string('accounting/email/bookkeeper.html',
                                     email_context)
    email_content_plaintext = render_to_string(
        'accounting/email/bookkeeper.txt', email_context)

    format_dict = Format.FORMAT_DICT[Format.CSV]
    excel_attachment = {
        'title': 'Invoices_%(period)s.%(extension)s' % {
            'period': first_of_month.strftime('%B_%Y'),
            'extension': format_dict['extension'],
        },
        'mimetype': format_dict['mimetype'],
        'file_obj': invoice.excel_response,
    }

    emails = emails or settings.BOOKKEEPER_CONTACT_EMAILS
    for email in emails:
        send_HTML_email(
            "Invoices for %s" %
            datetime.date(year, month, 1).strftime(USER_MONTH_FORMAT),
            email,
            email_content,
            email_from=settings.DEFAULT_FROM_EMAIL,
            text_content=email_content_plaintext,
            file_attachments=[excel_attachment],
        )

    log_accounting_info(
        "Sent Bookkeeper Invoice Summary for %(month)s "
        "to %(emails)s." % {
            'month': first_of_month.strftime(USER_MONTH_FORMAT),
            'emails': ", ".join(emails)
        })
Ejemplo n.º 28
0
def exercises(request, **kwargs):
    """
    List of Exercises, Tagged exercises, and Exercises without problems.
    matching search query or user selection
    """
    #before = datetime.datetime.now()
    if request.method != 'GET':
        return HttpResponseNotAllowed(['GET'])

    search_state = SearchState(
                    user_logged_in=request.user.is_authenticated(),
                    **kwargs
                )
    page_size = int(askbot_settings.DEFAULT_EXERCISES_PAGE_SIZE)

    qs, meta_data = models.Thread.objects.run_advanced_search(
                        request_user=request.user, search_state=search_state
                    )
    if meta_data['non_existing_tags']:
        search_state = search_state.remove_tags(meta_data['non_existing_tags'])

    paginator = Paginator(qs, page_size)
    if paginator.num_pages < search_state.page:
        search_state.page = 1
    page = paginator.page(search_state.page)
    page.object_list = list(page.object_list) # evaluate the queryset

    # INFO: Because for the time being we need exercise posts and thread authors
    #       down the pipeline, we have to precache them in thread objects
    models.Thread.objects.precache_view_data_hack(threads=page.object_list)

    related_tags = Tag.objects.get_related_to_search(
                        threads=page.object_list,
                        ignored_tag_names=meta_data.get('ignored_tag_names',[])
                    )
    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    if tag_list_type == 'cloud': #force cloud to sort by name
        related_tags = sorted(related_tags, key = operator.attrgetter('name'))

    contributors = list(
        models.Thread.objects.get_thread_contributors(
                                        thread_list=page.object_list
                                    ).only('id', 'username', 'gravatar')
                        )

    paginator_context = {
        'is_paginated' : (paginator.count > page_size),

        'pages': paginator.num_pages,
        'page': search_state.page,
        'has_previous': page.has_previous(),
        'has_next': page.has_next(),
        'previous': page.previous_page_number(),
        'next': page.next_page_number(),

        'base_url' : search_state.query_string(),
        'page_size' : page_size,
    }

    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})
    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist("tags", search_state.tags)
    context_feed_url = '/%sfeeds/rss/?%s' % (settings.ASKBOT_URL, rss_query_dict.urlencode()) # Format the url with the QueryDict

    reset_method_count = len(filter(None, [search_state.query, search_state.tags, meta_data.get('author_name', None)]))

    if request.is_ajax():
        q_count = paginator.count

        exercise_counter = ungettext('%(q_num)s exercise', '%(q_num)s exercises', q_count)
        exercise_counter = exercise_counter % {'q_num': humanize.intcomma(q_count),}

        if q_count > page_size:
            paginator_tpl = get_template('main_page/paginator.html', request)
            paginator_html = paginator_tpl.render(Context({
                'context': functions.setup_paginator(paginator_context),
                'exercises_count': q_count,
                'page_size' : page_size,
                'search_state': search_state,
            }))
        else:
            paginator_html = ''

        exercises_tpl = get_template('main_page/exercises_loop.html', request)
        exercises_html = exercises_tpl.render(Context({
            'threads': page,
            'search_state': search_state,
            'reset_method_count': reset_method_count,
            'request': request
        }))

        ajax_data = {
            'query_data': {
                'tags': search_state.tags,
                'sort_order': search_state.sort,
                'ask_query_string': search_state.ask_query_string(),
            },
            'paginator': paginator_html,
            'exercise_counter': exercise_counter,
            'faces': [],#[extra_tags.gravatar(contributor, 48) for contributor in contributors],
            'feed_url': context_feed_url,
            'query_string': search_state.query_string(),
            'page_size' : page_size,
            'exercises': exercises_html.replace('\n',''),
            'non_existing_tags': meta_data['non_existing_tags']
        }
        ajax_data['related_tags'] = [{
            'name': escape(tag.name),
            'used_count': humanize.intcomma(tag.local_used_count)
        } for tag in related_tags]

        return HttpResponse(simplejson.dumps(ajax_data), mimetype = 'application/json')

    else: # non-AJAX branch

        template_data = {
            'active_tab': 'exercises',
            'author_name' : meta_data.get('author_name',None),
            'contributors' : contributors,
            'context' : paginator_context,
            'is_without_problem' : False,#remove this from template
            'interesting_tag_names': meta_data.get('interesting_tag_names', None),
            'ignored_tag_names': meta_data.get('ignored_tag_names', None),
            'subscribed_tag_names': meta_data.get('subscribed_tag_names', None),
            'language_code': translation.get_language(),
            'name_of_anonymous_user' : models.get_name_of_anonymous_user(),
            'page_class': 'main-page',
            'page_size': page_size,
            'query': search_state.query,
            'threads' : page,
            'exercises_count' : paginator.count,
            'reset_method_count': reset_method_count,
            'scope': search_state.scope,
            'show_sort_by_relevance': conf.should_show_sort_by_relevance(),
            'search_tags' : search_state.tags,
            'sort': search_state.sort,
            'tab_id' : search_state.sort,
            'tags' : related_tags,
            'tag_list_type' : tag_list_type,
            'font_size' : extra_tags.get_tag_font_size(related_tags),
            'display_tag_filter_strategy_choices': conf.get_tag_display_filter_strategy_choices(),
            'email_tag_filter_strategy_choices': const.TAG_EMAIL_FILTER_STRATEGY_CHOICES,
            'update_avatar_data': schedules.should_update_avatar_data(request),
            'query_string': search_state.query_string(),
            'search_state': search_state,
            'feed_url': context_feed_url,
        }

        return render_into_skin('main_page.html', template_data, request)
Ejemplo n.º 29
0
    def assertRedirects(self,
                        response,
                        expected_url,
                        status_code=302,
                        target_status_code=200,
                        host=None,
                        msg_prefix=''):
        """Asserts that a response redirected to a specific URL, and that the
        redirect URL can be loaded.

        Note that assertRedirects won't work for external links since it uses
        TestClient to do a request.
        """
        if msg_prefix:
            msg_prefix += ": "

        if hasattr(response, 'redirect_chain'):
            # The request was a followed redirect
            self.assertTrue(
                len(response.redirect_chain) > 0,
                msg_prefix + "Response didn't redirect as expected: Response"
                " code was %d (expected %d)" %
                (response.status_code, status_code))

            self.assertEqual(
                response.redirect_chain[0][1], status_code,
                msg_prefix + "Initial response didn't redirect as expected:"
                " Response code was %d (expected %d)" %
                (response.redirect_chain[0][1], status_code))

            url, status_code = response.redirect_chain[-1]

            self.assertEqual(
                response.status_code, target_status_code,
                msg_prefix + "Response didn't redirect as expected: Final"
                " Response code was %d (expected %d)" %
                (response.status_code, target_status_code))

        else:
            # Not a followed redirect
            self.assertEqual(
                response.status_code, status_code,
                msg_prefix + "Response didn't redirect as expected: Response"
                " code was %d (expected %d)" %
                (response.status_code, status_code))

            url = response['Location']
            scheme, netloc, path, query, fragment = urlsplit(url)

            redirect_response = response.client.get(path, QueryDict(query))

            # Get the redirection page, using the same client that was used
            # to obtain the original response.
            self.assertEqual(
                redirect_response.status_code, target_status_code,
                msg_prefix + "Couldn't retrieve redirection page '%s':"
                " response code was %d (expected %d)" %
                (path, redirect_response.status_code, target_status_code))

        e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(
            expected_url)
        if not (e_scheme or e_netloc):
            expected_url = urlunsplit(
                ('http', host or 'testserver', e_path, e_query, e_fragment))

        self.assertEqual(
            url, expected_url, msg_prefix +
            "Response redirected to '%s', expected '%s'" % (url, expected_url))
Ejemplo n.º 30
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     if request.method == 'PUT':
         request.PUT = QueryDict(request.body)
     else:
         request.PUT = QueryDict('')