Пример #1
0
    def get(self):
        auth_level = self.is_user_authorized()
        if auth_level == models.AUTH_LEVEL_REGISTERED_USER:
            self.redirect("/account/activate/reminder/")
        elif auth_level == models.AUTH_LEVEL_ACTIVATED_USER:
            today = datetime.utcnow()

            year = self.request.get("year")
            month = self.request.get("month")

            if not year or not month:
                year = today.year
                month = today.month
            else:
                year = dec(year)
                month = dec(month)
            articles = Article.get_all_published_for_month(year, month)
            books = Book.get_latest(count=10)
            response = render_template(
                "blog.html",
                year_list=models.BLOG_YEAR_LIST,
                month_list=models.MONTH_LIST,
                today=today,
                requested_year=year,
                requested_month=month,
                articles=articles,
                books=books,
            )
            self.response.out.write(response)
        else:
            response = render_template("index.html")
            self.response.out.write(response)
Пример #2
0
    def get(self):
        auth_level = self.is_user_authorized()
        if auth_level == models.AUTH_LEVEL_REGISTERED_USER:
            self.redirect('/account/activate/reminder/')
        elif auth_level == models.AUTH_LEVEL_ACTIVATED_USER:
            today = datetime.utcnow()

            request_year = self.request.get('year')
            request_month = self.request.get('month')

            if not request_year or not request_month:
                year = today.year
                month = today.month
                articles = Article.get_latest_published_student()
            else:
                year = dec(request_year)
                month = dec(request_month)
                articles = Article.get_all_published_student_articles_for_month(year, month)
            books = Book.get_latest(count=10)
            response = render_template('blog_students.html',
                year_list=models.BLOG_YEAR_LIST,
                month_list=models.MONTH_LIST,
                today=today,
                requested_year=year,
                requested_month=month,
                articles=articles,
                books=books)
            self.response.out.write(response)
        else:
            response = render_template('index.html')
            self.response.out.write(response)
def solve3(view):
    action_name = dec(b'ImVtYWlsIg==')
    allow_method = dec(b'WyJnZXQiLCAiZGVsZXRlIl0=')

    router = SimpleRouter()
    router.register('users', view)

    group_by_methods, group_by_actions = get_actions_from_router(router)

    assert group_by_actions.get(action_name,
                                None), 'email action 이 구현되지 않았습니다.'
    assert allow_method == group_by_actions.get(
        action_name, []
    ), f'email action 은 GET, DELETE Method 를 허용해야합니다. 현재 email action 은 {", ".join(group_by_actions.get(action_name, []))} 을 허용중입니다.'

    factory = APIRequestFactory()

    view = view.as_view(actions={'get': action_name})
    user = baker.make(User, email='*****@*****.**')
    response = view(factory.get(''), pk=user.pk)

    assert response.status_code == 200, f'get API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'
    assert response.data == '*****@*****.**', f'get API 호출 결과는 {"*****@*****.**"} 이 되어야 합니다: 현재: {response.data}'

    view = view.as_view(actions={'delete': action_name})
    response = view(factory.delete(''), pk=user.pk)

    user.refresh_from_db()
    assert response.status_code == 204, f'delete API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'
    assert not user.email, 'delete API 호출 결과 유저의 email 속성이 지워지지 않았습니다.'
Пример #4
0
def save_training_program(key='', title='', venue='', faculty='', 
        when_from='',
        when_to='',
        when_registration_ends='',
        participation_counts=[], 
        participation_fees=[]):
    if key:
        training_program = db.get(db.Key(key))
    else:
        training_program = models.TrainingProgram
    training_program.title = title
    training_program.venue = venue
    training_program.faculty = faculty
    training_program.when_from = parse_iso_datetime_string(when_from)
    training_program.when_to = parse_iso_datetime_string(when_to)
    training_program.when_registration_ends = parse_iso_datetime_string(when_registration_ends)
    training_program.put()
    
    fees = []
    for count, fee in izip(participation_counts, participation_fees):
        tpfee = models.TrainingProgramFee()
        tpfee.for_participation_count = count
        if '.' in fee:
            fee_integer, fee_fraction = fee.split('.')
        else:
            fee_integer, fee_fraction = fee, '0'
        tpfee.fee_integer = dec(fee_integer)
        tpfee.fee_fraction = dec(fee_fraction)
        tpfee.training_program = training_program
        fees.append(tpfee)
    db.put(fees)
Пример #5
0
def parse_esex(fil, enc='WINDOWS-1253'):
    # Create list with lines to exclude
    EXC = (
        ' ' * 164 + 'Σελίδα',
        '   Κινήσεις ανά Ημέρα',
        '     A/A Τύπος Εγγραφής',
        '-------- ------------------------- ',
        '   Σύνολα ημέρας',
        ' ' * 92 + '-------------------- -------------------- ',
        ' ' * 53 + 'Σύνολα Εξόδων',
        ' ' * 53 + 'Σύνολα Εξόδων',
        '  Γενικά Σύνολα',
        ' ' * 53 + 'Εξόδων',
    )
    SDAT = slice(32, 42)  # Ημερομηνία
    SAA = slice(0, 8)  # Αριθμός άρθρου
    STYP = slice(9, 34)  # Τύπος
    SPAR = slice(35, 66)  # Παραστατικό
    SAFM = slice(67, 76)  # ΑΦΜ
    SLMO = slice(67, 91)  # όλο το πεδίο άν δεν υπάρχει ΑΦΜ
    SLMP = slice(77, 91)  # μόνο μετά το ΑΦΜ
    SVAL = slice(93, 112)  # Καθαρή αξία
    SFPA = slice(114, 133)  # ΦΠΑ
    STOT = slice(156, 175)  # Σύνολο
    dat = typ = par = per = afm = ''
    aar = val = fpa = tot = 0
    # lines = []
    # lind = defaultdict(list)
    lind = defaultdict(dict)
    with open(fil, encoding=enc) as ofil:
        for lin in ofil:
            llin = len(lin)
            if llin < 40:
                continue
            elif lin.startswith(EXC):  # Exclude lines
                continue
            elif lin.startswith('  Κινήσεις της '):
                # print(lin)
                dat = iso_dat(lin[SDAT])
            elif lin[109] == ',' and lin[130] == ',' and lin[151]:
                aar = int(lin[SAA].strip())
                typ = lin[STYP].strip()
                par = lin[SPAR].strip()
                afm = lin[SAFM].strip()
                if is_afm(afm):
                    per = lin[SLMP].strip()
                else:
                    afm = ''
                    per = lin[SLMO].strip()
                val = dec(lin[SVAL].strip().replace('.', '').replace(',', '.'))
                fpa = dec(lin[SFPA].strip().replace('.', '').replace(',', '.'))
                tot = dec(lin[STOT].strip().replace('.', '').replace(',', '.'))
                "id dat typ par per afm val fpa tot"
                kin = Kin(aar, dat, typ, par, per, afm, val, fpa, tot)
                if afm != '':
                    # lines.append(kin)
                    lind[dat][kin.par] = kin.afm
    return lind
Пример #6
0
 def __str__(self):
     if self.ttype == enums.Decr.DEBIT:
         debit = self.value
         credit = utl.dec(0)
     elif self.ttype == enums.Decr.CREDIT:
         debit = utl.dec(0)
         credit = self.value
     else:
         debit = credit = self.value
     return self.stt % (self.account.code, self.comment, debit, credit)
Пример #7
0
    def get(self):
        count = dec(self.request.get('count', '0'))
        minimum = dec(self.request.get('min', '0'))

        if not count:
            self.redirect('/register/pricing/')

        if config.LOCAL:
            country_code = 'IND'
        else:
            country_code = ip_address_to_country_code(self.request.remote_addr, 'IND')
        response = render_template('register/participants.html', count=count, minimum=minimum, country_code=country_code, countries=COUNTRIES_SELECTION_LIST)
        self.response.out.write(response)
Пример #8
0
 def value_delta(self):
     if self.ttype == enums.Decr.DEBIT:
         return self.value
     elif self.ttype == enums.Decr.CREDIT:
         return -self.value
     else:
         return utl.dec(0)
Пример #9
0
 def update_video_interval(self, interval: int, aid, bvid):
     now = datetime.utcnow() + timedelta(hours=8)
     if aid == None:
         aid = enc(bvid)
     if bvid == None:
         bvid = dec(aid)
     return {'next': now, 'interval': interval, 'aid': aid, 'bvid': bvid}
Пример #10
0
    def post(self, key):
        training_program = db.get(db.Key(key))

        title = self.request.get('title')
        venue = self.request.get('venue')
        when_from = self.request.get('when_from')
        when_to = self.request.get('when_to')
        faculty = self.request.get('faculty')
        when_registration_ends = self.request.get('when_registration_ends')
        when_payment_is_calculated = self.request.get('when_payment_is_calculated')
        max_participants = self.request.get('max_participants')
        brochure_url = self.request.get('brochure_url')
        description = self.request.get("description")

        training_program.title = title
        training_program.venue = venue
        training_program.when_from = parse_iso_datetime_string(when_from)
        training_program.when_to = parse_iso_datetime_string(when_to)
        training_program.faculty = faculty
        training_program.when_registration_ends = parse_iso_datetime_string(when_registration_ends)
        training_program.when_payment_is_calculated = parse_iso_datetime_string(when_payment_is_calculated)
        training_program.max_participants = dec(max_participants)
        training_program.brochure_url = brochure_url
        training_program.description = description

        fees1 = Decimal(self.request.get('fees_1'))
        fees2 = Decimal(self.request.get('fees_2'))
        fees3 = Decimal(self.request.get('fees_3'))
        participants1 = dec(self.request.get('participants_1'))
        participants2 = dec(self.request.get('participants_2'))
        participants3 = dec(self.request.get('participants_3'))

        fees = training_program.fees
        fees_1 = fees[0]
        fees_2 = fees[1]
        fees_3 = fees[2]

        fees_1.fee = fees1
        fees_1.for_participant_count = participants1
        fees_2.fee = fees2
        fees_2.for_participant_count = participants2
        fees_3.fee = fees3
        fees_3.for_participant_count = participants3

        db.put([training_program, fees_1, fees_2, fees_3])

        self.response.out.write(training_program.to_json('title', 'is_deleted', 'is_active', 'is_starred', 'when_created'))
Пример #11
0
    def get(self, year, month, day, slug_title):
        year = dec(year)
        month = dec(month)
        day = dec(day)
        today = datetime.utcnow()
        articles = [Article.get_article_for_day_with_slug(year, month, day, slug_title)]
        logging.info(articles)
        response = render_template('blog.html',
            year_list=models.BLOG_YEAR_LIST,
            month_list=models.MONTH_LIST,
            current_year=today.year,
            current_month=today.month,
            articles=articles,
            show_comments=True)
        self.response.out.write(response)

        """auth_level = self.is_user_authorized()
Пример #12
0
    def post(self):
        count = dec(self.request.get('count'))
        pricing = Decimal(str(get_pricing_per_individual(count)))

        total_price = Decimal('0')
        participants = []

        host_info = get_host_info(self.request)
        host_info.put()

        group = ParticipantGroup()
        group.title = self.request.get('organization_1') + '/' + self.request.get('email_1')
        group.host_info = host_info
        group.put()

        primary_participant = None
        for x in range(count):
            i = str(x + 1)

            full_name = self.request.get('full_name_' + i)
            if full_name:
                participant = Participant()
                participant.full_name = full_name
                participant.email = self.request.get('email_' + i)
                participant.mobile_number = self.request.get('mobile_number_' + i)
                participant.address = self.request.get('address_' + i)
                participant.phone_number = self.request.get('phone_number_' + i)
                participant.designation = self.request.get('designation_' + i)
                participant.organization = self.request.get('organization_' + i)
                participant.department = self.request.get('department_' + i)
                participant.country_code = self.request.get('country_code_' + i)
                participant.state_province = self.request.get('state_province_' + i)
                participant.city = self.request.get('city_' + i)
                participant.zip_code = self.request.get('zip_code_' + i)
                participant.pricing = pricing
                if x == 0:
                    participant.is_primary = True
                    primary_participant = participant
                participant.group = group
                total_price += pricing
                participants.append(participant)

        tax_amount = (total_price * PRICING_TAX)
        tax_amount = tax_amount.quantize(Decimal('.01'), rounding=ROUND_DOWN)
        calculated_price = total_price
        total_price = total_price + tax_amount

        self.session['calculated_price'] = calculated_price
        self.session['tax_amount'] = tax_amount
        self.session['total_price'] = total_price
        self.session['participant_count'] = count
        self.session['participants'] = participants
        self.session['participant_group'] = group
        self.session['primary_participant'] = primary_participant



        self.redirect('/register/payment/')
Пример #13
0
 def get(self):
     year = self.request.get('year')
     month = self.request.get('month')
     #auth_level = self.is_user_authorized()
     #if auth_level == models.AUTH_LEVEL_ACTIVATED_USER:
         #self.redirect(configuration.PICASA_WEB_ALBUMS_PUBLIC_URL)
     articles = models.Article.get_all_published_for_month(dec(year), dec(month))
     articles_list = [
         dict(title=a.title,
         author_nickname=a.author.nickname(),
         author_email=a.author.email(),
         when_published=get_iso_datetime_string(a.when_published),
         content=a.html_content
         )
         for a in articles
     ]
     retval = json.dumps(articles_list)
     self.response.out.write(retval)
Пример #14
0
def auth_request(data, k):

    req = pickle.loads(data)

    userid = utils.dec(req.userid, k)
    password = utils.dec(req.password, k)
    qa = utils.dec(req.qa, k)

    print 'User ID: ', userid
    print 'Password: '******'QA: ', qa

    status = 'SUCCESSFUL'

    if not checkCreds(userid, password):
        status = 'UNSUCCESSFUL'

    return status
Пример #15
0
 def myf(self):
     cval = defaultdict(dict)
     cfpa = defaultdict(dict)
     myfl = []
     for tran in self.transactions:
         myf = tran.myf
         if myf:
             cval[myf.category][myf.decr] = cval[myf.category].get(
                 myf.decr, 0) + myf.amount
             cfpa[myf.category][myf.decr] = cfpa[myf.category].get(
                 myf.decr, 0) + myf.tax
             if myf.category == MyfCat.PROVAT:
                 cat = MyfCat.PRO
                 if myf.tax == 0:
                     amn = dec(myf.amount / dec(1.24))
                     tax = myf.amount - amn
                     # print(tran.date, tran.parastatiko, tran.perigrafi, tran.afm, amn, tax)
                 else:
                     amn = myf.amount
                     tax = myf.tax
                 myfl.append(
                     MyfLine(myf.date, myf.afm, cat, myf.decr, amn, tax))
             elif myf.category == MyfCat.PELLIA:
                 myfl.append(
                     MyfLine(myf.date, '', myf.category, myf.decr,
                             myf.amount, myf.tax))
             elif myf.category == MyfCat.PRO and myf.afm in MYFEX:
                 # print(tran)
                 myfl.append(
                     MyfLine(myf.date, '', MyfCat.PROCUB, myf.decr,
                             myf.amount, myf.tax))
             else:
                 myfl.append(myf)
     for key, val in cval.items():
         print(key.name)
         for k2, val2 in val.items():
             print(k2, val2)
     for key, val in cfpa.items():
         print(key.name)
         for k2, val2 in val.items():
             print(k2, val2)
     return myfl
Пример #16
0
    def post(self):
        title = self.request.get('title')
        venue = self.request.get('venue')
        when_from = self.request.get('when_from')
        when_to = self.request.get('when_to')
        faculty = self.request.get('faculty')
        when_registration_ends = self.request.get('when_registration_ends')
        when_payment_is_calculated = self.request.get('when_payment_is_calculated')
        max_participants = self.request.get('max_participants')
        brochure_url = self.request.get('brochure_url')
        description = self.request.get("description")

        training_program = TrainingProgram()
        training_program.title = title
        training_program.venue = venue
        training_program.when_from = parse_iso_datetime_string(when_from)
        training_program.when_to = parse_iso_datetime_string(when_to)
        training_program.faculty = faculty
        training_program.when_registration_ends = parse_iso_datetime_string(when_registration_ends)
        training_program.when_payment_is_calculated = parse_iso_datetime_string(when_payment_is_calculated)
        training_program.max_participants = dec(max_participants)
        training_program.brochure_url = brochure_url
        training_program.description = description
        training_program.put()

        fees1 = Decimal(self.request.get('fees_1'))
        fees2 = Decimal(self.request.get('fees_2'))
        fees3 = Decimal(self.request.get('fees_3'))
        participants1 = dec(self.request.get('participants_1'))
        participants2 = dec(self.request.get('participants_2'))
        participants3 = dec(self.request.get('participants_3'))

        fees_1 = TrainingProgramFee(fee=fees1, for_participant_count=participants1)
        fees_1.training_program = training_program
        fees_2 = TrainingProgramFee(fee=fees2, for_participant_count=participants2)
        fees_2.training_program = training_program
        fees_3 = TrainingProgramFee(fee=fees3, for_participant_count=participants3)
        fees_3.training_program = training_program

        db.put([fees_1, fees_2, fees_3])

        self.response.out.write(training_program.to_json('title', 'is_deleted', 'is_active', 'is_starred', 'when_created'))
Пример #17
0
def login_create(data, k):

    req = pickle.loads(data)

    userid = utils.dec(req.userid, k)
    password = utils.dec(req.password, k)
    qa = utils.dec(req.qa, k)

    print 'User ID: ', userid
    print 'Password: '******'QA: ', qa

    status = 'SUCCESSFUL'

    if isUser(userid):
        status = 'UNSUCCESSFUL'
    else:
        writeUser(userid, password, qa)

    return status
Пример #18
0
 def update_video_interval(self, interval: int, aid, bvid):
   if aid == None:
     aid = enc(bvid)
   if bvid == None:
     bvid = dec(aid)
   return {
       'next': datetime.utcfromtimestamp(0),
       'interval': interval,
       'aid': aid,
       'bvid': bvid
   }
Пример #19
0
    def post(self, key):
        user = db.get(db.Key(key))
        person = user.people_singleton[0]

        person.first_name = self.request.get('first_name')
        person.last_name = self.request.get('last_name')
        user.nickname = ' '.join([person.first_name, person.last_name])
        user.email = self.request.get('email')

        corporate_email = self.request.get('corporate_email').strip()
        if corporate_email:
            user.corporate_email = corporate_email
        person.company = self.request.get('company')
        person.designation = self.request.get('designation')
        person.graduation_year = dec(self.request.get('graduation_year'))
        person.t_shirt_size = self.request.get('t_shirt_size')
        person.gender = self.request.get('gender')

        birthdate_day = dec(self.request.get('birthdate_day'))
        birthdate_month = dec(self.request.get('birthdate_month'))
        birthdate_year = dec(self.request.get('birthdate_year'))
        person.birthdate = datetime(birthdate_year, birthdate_month, birthdate_day).date()

        phone_count = dec(self.request.get('phone_count'))
        if phone_count:
            phones = []
            for i in xrange(phone_count):
                phone_key = self.request.get('phone_' + str(i + 1) + '_key')
                phone = db.get(db.Key(phone_key))
                phone.number = self.request.get('phone_' + str(i + 1))
                phones.append(phone)
            db.put(phones)

        is_student = self.request.get('is_student')
        if is_student == 'yes':
            person.is_student = True

        user.put()
        person.put()
        self.response.out.write(user.to_json('nickname', 'email', 'is_starred', 'is_deleted', 'is_active', 'is_premium'))
Пример #20
0
 def parse(self, res):
     bvid = str(
         res.url.lstrip('https://www.bilibili.com/video/BV').rsplit('?')[0])
     tagName = res.xpath("//li[@class='tag']/a/text()")
     item = {}
     item['bvid'] = bvid
     item['tag_list'] = []
     item['aid'] = dec('BV' + bvid)
     if tagName != []:
         ITEM_NUMBER = len(tagName)
         for i in range(0, ITEM_NUMBER):
             item['tag_list'].append(tagName[i])
     return item
def solve2(view):
    action_name = dec(b'InNldF9zdGFmZiI=')
    allow_method = dec(b'InBvc3Qi')

    router = SimpleRouter()
    router.register('users', view)

    _, group_by_actions = get_actions_from_router(router)

    assert group_by_actions.get(action_name,
                                None), 'set_staff action 이 구현되지 않았습니다.'
    assert allow_method in group_by_actions.get(
        action_name, []
    ), f'set_staff action 는 POST Method 를 허용해야합니다. 현재 set_staff action 은 {", ".join(group_by_actions.get(action_name, []))} 을 허용중입니다.'

    factory = APIRequestFactory()
    view = view.as_view(actions={allow_method: action_name})
    user = baker.make(User, is_staff=False)
    response = view(factory.post(''), pk=user.pk)

    assert response.status_code == 200, f'{allow_method} API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'
    user.refresh_from_db()
    assert user.is_staff, f'{allow_method} API 호출 결과 유저의 is_staff 속성이 True 로 설정되지 않았습니다.'
Пример #22
0
 def __init__(self, account_code, ttype, value, comment='', acc_name=None):
     """Create a new TransactionLine
     :param account: The account code
     :param ttype: DEBIT(1), or CREDIT(2)
     :param value: Decimal nonzero number
     :param comment: Small comment about the line
     """
     # assert ttype in (cfg.DEBIT, cfg.CREDIT)  # Only DEBIT or CREDIT
     # assert value != 0  # Must have a nonzero value
     self.account = acc.Account(account_code)
     self.ttype = enums.Decr(ttype)
     self.value = utl.dec(value)
     self.comment = comment
     self.normalize()
Пример #23
0
 def get(self, year, month, day, slug_title):
     auth_level = self.is_user_authorized()
     if auth_level == models.AUTH_LEVEL_REGISTERED_USER:
         self.redirect("/account/activate/reminder/")
     elif auth_level == models.AUTH_LEVEL_ACTIVATED_USER:
         year = dec(year)
         month = dec(month)
         day = dec(day)
         today = datetime.utcnow()
         articles = [Article.get_article_for_day_with_slug(year, month, day, slug_title)]
         logging.info(articles)
         response = render_template(
             "blog.html",
             year_list=models.BLOG_YEAR_LIST,
             month_list=models.MONTH_LIST,
             current_year=today.year,
             current_month=today.month,
             articles=articles,
         )
         self.response.out.write(response)
     else:
         response = render_template("index.html")
         self.response.out.write(response)
def solve1(view):
    allow_methods = dec(
        b'eyJwb3N0IjogWyJjcmVhdGUiXSwgInBhdGNoIjogWyJwYXJ0aWFsX3VwZGF0ZSJdLCAiZGVsZXRlIjogWyJkZXN0cm95Il19'
    )
    router = SimpleRouter()
    router.register('users', view)

    group_by_methods, _ = get_actions_from_router(router)
    result_methods = allow_methods.copy()

    for method in group_by_methods:
        if method in result_methods:
            del result_methods[method]

    assert not result_methods, f'{", ".join([value for key, values in result_methods.items() for value in values])} 이(가) 구현되지 않았습니다.'
Пример #25
0
    def post(self, training_key):
        training_program = db.get(db.Key(training_key))
        nominations = dec(self.request.get("nominations_count"))

        # training_program.increment_participant_count(incr=nominations)
        training_program.increment_total_participant_count(incr=nominations)

        registrants = []
        for x in range(nominations):
            i = str(x + 1)
            full_name = self.request.get("full_name_" + i)
            phone_number = self.request.get("phone_number_" + i)
            email = self.request.get("email_" + i)
            company = self.request.get("company_" + i)
            designation = self.request.get("designation_" + i)
            registrant = TrainingProgramRegistrant()
            registrant.full_name = full_name
            registrant.phone_number = phone_number
            registrant.email = email
            # Let the admin determine who to activate.
            # registrant.is_active = True
            registrant.company = company
            registrant.designation = designation
            registrant.training_program = training_program
            registrants.append(registrant)
        db.put(registrants)

        if training_program.is_canceled:
            for registrant in registrants:
                registrant_key = str(registrant.key())
                queue_mail_task(
                    url="/worker/mail/training_announcement_canceled_notification/",
                    params=dict(registrant_key=registrant_key, training_program_key=training_key),
                    method="POST",
                )
            response = render_template("training_announcement_canceled.html", training_announcement=training_program)
            self.response.out.write(response)
        else:
            for registrant in registrants:
                registrant_key = str(registrant.key())
                queue_mail_task(
                    url="/worker/mail/training_announcement_registration_notification/",
                    params=dict(registrant_key=registrant_key, training_program_key=training_key),
                    method="POST",
                )
            self.redirect("/training_announcements/")
Пример #26
0
    async def parse(self, res):
        try:
            json_data = res.json_data

            item = {}
            bvid = res.url.query['bvid']

            item['bvid'] = bvid
            item['aid'] = dec('BV' + bvid)
            if res == None or res.json_data['data'] == None:
                return None
            m = map(lambda x: x['tag_name'], res.json_data['data'])
            if m == None:
                return None
            item['tag_list'] = list(m)
            return item
        except Exception as e:
            self.logger.exception(e)
            return None
Пример #27
0
    async def video_gen_without_lock(self):
        last_data = set()
        batch = 2000
        while True:
            try:
                d = []
                data = self.async_db.video_interval.find({
                    'next': {
                        '$lte': datetime.datetime.utcnow()
                    }
                }).sort([('next', 1)]).hint("idx_next").limit(batch)
                async for each in data:
                    if 'aid' not in each and 'bvid' in each and 'bvid' != '':
                        each['aid'] = dec('BV' + each['bvid'].lstrip('BV'))
                    elif 'bvid' not in each and 'aid' in each or 'bvid' == '':
                        each['bvid'] = enc(each['aid']).lstrip('BV')
                    elif 'aid' in each and 'bvid' in each and each[
                            'aid'] != None and type(
                                each['aid']) != str and each['aid'] > 0:
                        pass
                    else:
                        await self.async_db.video_interval.delete_one(
                            {'_id': each['_id']})
                    d.append(each)
                for data in d:
                    if 'aid' not in data:
                        continue
                    if data['aid'] not in last_data:
                        last_data.add(data['aid'])
                        yield data
                last_data = set()

                if len(d) < batch / 2:
                    await asyncio.sleep(10)
            except Exception as e:
                self.logger.exception(e)
Пример #28
0
    def post(self):
        session_user = self.get_session_user()

        first_name = self.request.get('first_name')
        last_name = self.request.get('last_name')
        birthdate_day = dec(self.request.get('birthdate_day'))
        birthdate_month = dec(self.request.get('birthdate_month'))
        birthdate_year = dec(self.request.get('birthdate_year'))
        company = self.request.get('company')
        designation = self.request.get('designation')
        gender = self.request.get('gender')
        t_shirt_size = self.request.get('t_shirt_size')
        email_address = self.request.get('email_address')
        corporate_email_address = self.request.get('corporate_email_address')
        railway_line = self.request.get('railway_line')
        graduation_year = dec(self.request.get('graduation_year'))

        if not session_user.email:
            session_user.email = email_address

        apartment = self.request.get('apartment')
        street_name = self.request.get('street_name')
        landmark = self.request.get('landmark')
        city = self.request.get('city')
        state_province = self.request.get('state_province')
        zip_code = self.request.get('zip_code')
        country = self.request.get('country')

        phone_number_count = int(self.request.get('phone_number_count'), 10)
        phone_numbers = []
        for i in range(1, phone_number_count+1):
            phone_number = self.request.get('phone_number_' + str(i))
            phone_type = self.request.get('phone_type_' + str(i))
            phone_numbers.append((phone_number, phone_type))

        #enable_notifications = True if self.request.get('enable_notifications') else False
        #enable_public_profile = True if self.request.get('enable_public_profile') else False
        #enable_administrator_contact = True if self.request.get('enable_administrator_contact') else False
        enable_notifications = True
        enable_public_profile = True
        enable_administrator_contact = True

        # Create database entries.
        to_store = []
        user = models.User(username=session_user.username,
            email=email_address,
            signin_email=session_user.email,
            identifier=session_user.identifier)
        if corporate_email_address:
            user.corporate_email = corporate_email_address
        user.nickname = first_name + ' ' + last_name
        user.enable_notifications = enable_notifications
        user.enable_public_profile = enable_public_profile
        user.enable_administrator_contact = enable_administrator_contact
        user.wants_activation = True
        user.has_updated_profile = True
        user.auth_provider = session_user.auth_provider
        user.is_active = False
        if session_user.photo:
            user.photo = session_user.photo
            user.gravatar = get_gravatar_url(email_address)
        user.put()

        person = models.Person()
        person.user = user
        person.first_name = first_name
        person.last_name = last_name
        person.company = company
        person.designation = designation
        person.birthdate = datetime(birthdate_year, birthdate_month, birthdate_day).date()
        person.gender = gender
        person.graduation_year = graduation_year
        person.t_shirt_size = t_shirt_size
        person.put()

        host_info = models.UserHostInformation()
        host_info.user = user
        host_info.ip_address = self.request.remote_addr
        host_info.http_user_agent = self.request.headers.get('User-Agent', '')
        host_info.http_accept_language = self.request.headers.get('Accept-Language', '')
        host_info.http_accept_encoding = self.request.headers.get('Accept-Encoding', '')
        host_info.http_accept_charset = self.request.headers.get('Accept-Charset', '')
        host_info.http_accept = self.request.headers.get('Accept', '')
        host_info.http_referer = self.request.headers.get('Referer', '')
        to_store.append(host_info)

        openid = models.OpenID(username=session_user.username)
        openid.nickname = session_user.nickname
        openid.email = session_user.email
        openid.auth_provider = session_user.auth_provider
        openid.identifier = session_user.identifier
        openid.profile_url = session_user.profile_url
        openid.user = user
        openid.is_primary_id = True
        to_store.append(openid)

        address_line = ', '.join([
            apartment,
            street_name,
            landmark,
            '' if railway_line == 'other' else models.RAILWAY_LINES.get(railway_line, '') + ' Railway Line',
            city,
            state_province + ' ' + zip_code,
            COUNTRY_NAME_ISO_ALPHA_3_TABLE.get(country, ''),
            ])
        address = models.PersonAddress(person=person,
            address_line=address_line,
            street_name=street_name,
            zip_code=zip_code,
            state_province=state_province,
            country=country,
            landmark=landmark,
            apartment=apartment,
            city=city,
            nearest_railway_line=railway_line,
            address_type='home')
        to_store.append(address)

        for (number, phone_type) in phone_numbers:
            if number.strip():
                phone = models.PersonPhone(person=person,
                    number=number,
                    phone_type=phone_type)
                to_store.append(phone)

        # Batch write all non-dependent entities.
        db.put(to_store)
        models.User.increment_user_count()
        queue_mail_task(url='/worker/mail/signup_notification/' + str(user.key()), method='GET')
        
        rendered_template = render_template('activation_reminder.html')
        self.response.out.write(rendered_template)
Пример #29
0
 def credit(self):
     if self.ttype == enums.Decr.CREDIT:
         return self.value
     else:
         return utl.dec(0)
Пример #30
0
 def debit(self):
     if self.ttype == enums.Decr.DEBIT:
         return self.value
     else:
         return utl.dec(0)
Пример #31
0
    async def video_gen(self):
        while True:
            # 如果存在锁
            if await self.async_db.lock.count_documents(
                {"name": "video_interval"}):
                sleep(0.1)
                continue
            # 挂锁
            await self.async_db.lock.insert_one({
                "name":
                "video_interval",
                "date":
                datetime.datetime.utcnow()
            })
            try:
                d = []
                data = await self.async_db.video_interval.find({
                    'order': {
                        '$exists': True,
                        '$ne': []
                    }
                }).hint("idx_order").limit(100)
                for each in data:
                    d.append(each)
                data = await self.async_db.video_interval.find({
                    'next': {
                        '$lt': datetime.datetime.utcnow()
                    }
                }).limit(100)
                for each in data:
                    d.append(each)
                for data in d:
                    # 如果存在手动操作,则刷新数据
                    if 'order' in data:
                        for order_id in data['order']:
                            await self.async_db.user_record.update_one(
                                {'_id': order_id},
                                {'$set': {
                                    'isExecuted': True
                                }})
                    data['next'] = data['next'] + \
                                   datetime.timedelta(seconds=data['interval'])
                    data['order'] = []
                    try:
                        if 'aid' not in data:
                            data['aid'] = dec('BV' + data['bvid'])
                            filt = {'bvid': data['bvid']}
                        elif 'bvid' not in data:
                            data['bvid'] = enc(data['aid']).lstrip("BV")
                            filt = {'aid': data['aid']}
                        else:
                            filt = {'bvid': data['bvid']}
                    except Exception:
                        if 'aid' in data:
                            await self.async_db.video_interval.delete_many(
                                {'aid': data['aid']})
                        else:
                            await self.async_db.video_interval.delete_many(
                                {'bvid': data['bvid']})
                        continue
                    if await self.async_db.video_interval.count(filt) > 1:
                        await self.async_db.video_interval.delete_many(filt)

                    await self.async_db.video_interval.update_one(
                        filt, {'$set': data})

                # 解锁
                await self.async_db.lock.delete_one({"name": "video_interval"})
                for data in d:
                    yield data
            except Exception as e:
                self.logger.exception(e)
def solve4(answer1, answer2):
    result1 = dec(b'InVzZXJzLzxpbnQ6cGs+L3NldF9hZG1pbiI=')
    result2 = dec(b'InVzZXItc2V0LWFkbWluIg==')
    assert answer1 == result1, 'answer1 번이 틀렸습니다.'
    assert answer2 == result2, 'answer2 번이 틀렸습니다.'
def solve6(view, serializer):
    allow_methods = dec(
        b'eyJnZXQiOiBbImxpc3QiLCAicmV0cmlldmUiXSwgInBvc3QiOiBbImNyZWF0ZSJdLCAicHV0IjogWyJ1cGRhdGUiXSwgInBhdGNoIjogWyJwYXJ0aWFsX3VwZGF0ZSJdLCAiZGVsZXRlIjogWyJkZXN0cm95Il19'
    )

    router = SimpleRouter()
    router.register('users', view)

    group_by_methods, _ = get_actions_from_router(router)
    result_methods = allow_methods.copy()

    for method in group_by_methods:
        if method in result_methods:
            del result_methods[method]

    assert not result_methods, f'{", ".join([value for key, values in result_methods.items() for value in values])} 이(가) 구현되지 않았습니다.'

    # Method 체크

    factory = APIRequestFactory()
    user = baker.make(User, email='*****@*****.**')

    # List
    view = view.as_view(actions={'get': 'list'})
    response = view(factory.get(''))

    assert response.status_code == 200, f'list API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'
    assert type(
        response.data
    ) == ReturnList, f'list API 의 호출결과가 list 타입이 아닙니다: 현재 {type(response.data)}'
    assert {data.get('email'): data
            for data in response.data
            }.get('*****@*****.**'), f'list API 의 호출 결과에서 테스트 데이터를 찾을 수 없습니다.'

    # Retrieve
    view = view.as_view(actions={'get': 'retrieve'})
    response = view(factory.get(''), pk=user.pk)

    assert response.status_code == 200, f'retrieve API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'

    # Create
    view = view.as_view(actions={'post': 'create'})
    request_data = serializer(baker.prepare(User, email='*****@*****.**')).data
    response = view(factory.post('', request_data, format='json'))

    assert response.status_code == 201, f'create API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'
    assert User.objects.filter(
        email='*****@*****.**').first(), 'create API 호출 결과로 User 가 생성되지 않았습니다.'

    # Update
    view = view.as_view(actions={'put': 'update'})
    user.refresh_from_db()
    request_data = serializer(user).data
    request_data['email'] = '*****@*****.**'
    response = view(factory.put('', request_data, format='json'), pk=user.pk)

    assert response.status_code == 200, f'update API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'
    user.refresh_from_db()
    assert user.email == '*****@*****.**', 'update API 호출 결과로 email 이 업데이트 되지 않았습니다.'

    # Partial-Update
    view = view.as_view(actions={'patch': 'partial_update'})
    user.refresh_from_db()
    request_data = serializer(user).data
    request_data['email'] = '*****@*****.**'
    response = view(factory.patch('', request_data, format='json'), pk=user.pk)

    assert response.status_code == 200, f'partial_update API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'
    user.refresh_from_db()
    assert user.email == '*****@*****.**', 'partial_update API 호출 결과로 email 이 업데이트 되지 않았습니다.'

    # Delete
    view = view.as_view(actions={'delete': 'destroy'})
    response = view(factory.delete(''), pk=user.pk)

    assert response.status_code == 204, f'destroy API 호출 결과의 status_code 가 일치하지 않습니다: 현재: {response.status_code}'
    assert not User.objects.filter(
        pk=user.pk).first(), f'destroy API 호출 결과로 User 가 삭제되지 않았습니다.'
Пример #34
0
def parse_imerologio(fil, enc='WINDOWS-1253'):
    # Create list with lines to exclude
    EXC = (' ' * 150 + 'Σελίδα', ' ' * 33 + 'ΓΕΝΙΚΟ ΗΜΕΡΟΛΟΓΙΟ',
           '  Ημ/νία      Α/Α ΚΒΣ Στοιχεία Αρθρου',
           '  Ημ/νία     Α/Α ΚΒΣ  Στοιχεία Αρθρου',
           '                      Σχετ. Παραστατ.',
           '  -----------------------------------', ' ' * 38 + 'Από μεταφορά',
           ' ' * 123 + '-------------- --------------',
           ' ' * 70 + 'Σύνολα Σελίδας', ' ' * 70 + 'Σε Μεταφορά',
           ' ' * 70 + 'Σύνολα Περιόδου', ' ' * 152)
    dat = par = lmo = lmp = xre = pis = pe2 = per = ''
    tno = lno = 0
    SDAT = slice(2, 12)  # Ημερομηνία
    SPAR = slice(22, 48)  # Παραστατικό
    SLMO = slice(48, 60)  # Κωδικός λογαριασμού
    SLMP = slice(77, 122)  # Ονομασία λογαριασμού
    SXRE = slice(124, 137)  # Χρέωση
    SPIS = slice(139, 152)  # Πίστωση
    SPE2 = slice(22, 48)  # Έξτρα περιγραφή
    SPER = slice(48, -1)  # Περιγραφή
    dper = {}
    dlmo = {}
    trah = {}
    trad = {}
    arthro = {}
    unparsed_lines = {}
    with open(fil, encoding=enc) as ofil:
        for i, lin in enumerate(ofil):
            llin = len(lin)  # Το υπολογίζω εδώ μία φορά
            if llin < 48:  # Δεν έχουν νόημα γραμμές μικρότερες του 48
                continue
            elif lin.startswith(EXC):  # Exclude lines
                continue
            elif lin[50] == '.' and lin[53] == '.' and lin[134] == ',':
                if lin[4] == '/' and lin[7] == '/':
                    tno += 1
                    dat = iso_dat(lin[SDAT])
                    par = lin[SPAR].strip()
                    trah[tno] = TransHeader(dat, par)
                lno += 1
                lmo = lin[SLMO].strip()
                lmp = lin[SLMP].strip()
                xre = dec(lin[SXRE].strip().replace('.', '').replace(',', '.'))
                pis = dec(lin[SPIS].strip().replace('.', '').replace(',', '.'))
                if lmo in dlmo:
                    if dlmo[lmo] != lmp:
                        logger.error('Διαφορά στο όνομα %s:  %s -> %s' %
                                     (lmo, dlmo[lmo], lmp))
                else:
                    dlmo[lmo] = lmp
                trad[lno] = TransDetail(tno, lmo, xre, pis)
                arthro[tno] = arthro.get(tno, [])
                arthro[tno].append(lno)
            elif llin < 132:  # Πρόκειται για γραμμή περιγραφής
                pe2 = lin[SPE2].strip()
                per = lin[SPER].strip()
                dper[tno] = DetailPerigraphi(per, pe2)
            else:
                unparsed_lines[i] = lin
    if len(unparsed_lines) > 0:
        logger.error('parse_imerologio unparsed lines : %s' % unparsed_lines)
    else:
        logger.info('parse_imerologio parsed everynthing ok !!!')
    return {
        'tr_header': trah,
        'tr_lines': trad,
        'tr_per': dper,
        'lmoi': dlmo,
        'arthra': arthro,
        'errors': unparsed_lines
    }