示例#1
0
 def post(self, *args, **kwargs):
     recipient_form = RequisitesForm(self.request.arguments)
     bill_content_form = BillContentForm(self.request.arguments)
     if not (recipient_form.validate() and bill_content_form.validate()):
         if not recipient_form.validate():
             logging.debug(u'Форма получателя не валидна.')
         if not bill_content_form.validate():
             logging.debug(u'Форма содержимого не валидна.')
         self.context.update({'title': u'Создание счёта',
                              'module_name': url_base,
                              'sender': RequisitesDB.get_one({'inn': '772160030650'}),
                              'recipient': recipient_form,
                              'bill_content': bill_content_form,
                              'bill_num': Counter.next_key('bill'),
                              'date': datetime.now(),
                              })
         self.render(tmpl('create'))
     else:
         req = RequisitesDB.create_from_data(recipient_form.data)
         contr = ContactorDB.create(self.user_id, req['_id'])['_id']
         items_from_form = bill_content_form.data['items']
         items = []
         for i in items_from_form:
             if i['count'] > 0.0 and i['name']:
                 items.append(i)
         cont = ContentDB.create(items)['_id']
         bill_num = Counter.next_key('bill')
         date = datetime.now()
         sender_user = UserDB.get_one({'id': 1})
         bill = BillDB.create_simple(sender_user['_id'], contr, cont, bill_num, date)
         logging.debug(u'Счёт сохранен.')
         self.redirect('/%s/full/%s' % (url_base, bill['_id']))
示例#2
0
 def get(self):
     try:
         # パスの解析
         name =  self.request.path.split('/')[2]
         (key, type) = name.split('.')
         key = db.Key(key)
         output_encoding = [images.PNG, images.JPEG][['png', 'jpg'].index(type)]
         # カウンターの取得
         counter = Counter.get(key)
         if not counter:
             responses.display_error(self, 404)
             return
         # アクセス履歴情報の取得
         record = {
             'referer'     : self.request.headers.get('Referer'),
             'user_agent'  : self.request.headers.get('User-Agent'),
             'remote_addr' : self.request.remote_addr,
             }
         # カウントのインクリメント
         result = db.run_in_transaction(self.increment_count, counter.key(), record)
         count = Counter.get(result).count
         logging.debug(count)
         # 新しいカウントを桁毎に区切る
         digits = []
         while count / 10 != 0:
             digits.append(count % 10)
             count /= 10
         digits.append(count)
         # 使用する画像データの読み込み
         image_data = {}
         for number_image in NumberImage.all().ancestor(key).filter('number in', digits):
             image_data[number_image.number] = number_image.data
         # 合成するデータの決定
         image_list = []
         offset = 0
         for i in reversed(digits):
             image_list.append((image_data[i], offset, 0, 1.0, images.TOP_LEFT))
             offset += 64
         # 合成して出力
         image = images.composite(image_list, offset, 128, output_encoding=output_encoding)
         if output_encoding == images.PNG:
             self.response.headers['Content-Type'] = 'image/png'
         elif output_encoding == images.JPEG:
             self.response.headers['Content-Type'] = 'image/jpeg'
         self.response.out.write(image)
     except ValueError, error:
         logging.error('invalid path')
         responses.display_error(self, 404)
示例#3
0
def counters(counter_id=None):
    if request.method == 'POST':
        body = request.get_json()
        counter = Counter.save(
            id=counter_id,
            establishment=body.get('establishment')
        )
        return jsonify(counter.to_dict())
    if request.method == 'PUT':
        if counter_id:
            body = request.get_json()
            counter = Counter.get_by_id(counter_id)
            if counter.auth_key == body.get('auth_key'):
                counter.step_up()
            return jsonify(counter.to_dict())
    counter = Counter.get_by_id(counter_id)
    return jsonify(counter.to_dict())
示例#4
0
 def get(self):
     
     self.context.update({'title': u'Создание счёта',
                          'module_name': url_base,
                          'sender': RequisitesDB.get_one({'inn': '772160030650'}),
                          'recipient': RequisitesForm(),
                          'bill_content': BillContentForm(),
                          'bill_num': Counter.next_key('bill'),
                          'date': datetime.now(),
                          })
     self.render(tmpl('create'))
示例#5
0
    def post(self, _to):
        data = self.parser.parse_args()
        counter = Counter.find_counter(_to=_to)
        count = data["increase_by"]
        print("coutner", counter)
        print("count", count)

        if counter is not None:
            print("eyo")
            count += counter.count
            counter.delete_from_db()
        thought = Counter(_to, count)
        try:
            thought.save_to_db()
        except:
            return {
                "message":
                "An error occurred while saving the item (count) to the database."
            }, 500
        return {"message": "Count increased"}, 200
示例#6
0
 def post(self, *args, **kwargs):
     recipient_form = RequisitesForm(self.request.arguments)
     bill_content_form = BillContentForm(self.request.arguments)
     if not (recipient_form.validate() and bill_content_form.validate()):
         if not recipient_form.validate():
             logging.debug(u'Форма получателя не валидна.')
         if not bill_content_form.validate():
             logging.debug(u'Форма содержимого не валидна.')
         self.context.update({
             'title':
             u'Создание счёта',
             'module_name':
             url_base,
             'sender':
             RequisitesDB.get_one({'inn': '772160030650'}),
             'recipient':
             recipient_form,
             'bill_content':
             bill_content_form,
             'bill_num':
             Counter.next_key('bill'),
             'date':
             datetime.now(),
         })
         self.render(tmpl('create'))
     else:
         req = RequisitesDB.create_from_data(recipient_form.data)
         contr = ContactorDB.create(self.user_id, req['_id'])['_id']
         items_from_form = bill_content_form.data['items']
         items = []
         for i in items_from_form:
             if i['count'] > 0.0 and i['name']:
                 items.append(i)
         cont = ContentDB.create(items)['_id']
         bill_num = Counter.next_key('bill')
         date = datetime.now()
         sender_user = UserDB.get_one({'id': 1})
         bill = BillDB.create_simple(sender_user['_id'], contr, cont,
                                     bill_num, date)
         logging.debug(u'Счёт сохранен.')
         self.redirect('/%s/full/%s' % (url_base, bill['_id']))
示例#7
0
    def get(self, _to):
        messages = MessageModel.find_all(_to)
        counter = Counter.find_counter(_to)
        count = 0
        if counter is not None:
            count = counter.count
        all = []
        if messages:
            # TODO: FIX THIS TO SEND DATE TIME
            all = [m.json() for m in messages]

        return {'messages': all, 'count': count}, 200
示例#8
0
 def delete(self, _to):
     counter = Counter.find_counter(_to=_to)
     print("delete: counter:", counter)
     if counter is None:
         return {'message': "The counter doesn't exist"}, 404
     try:
         counter.delete_from_db()
     except:
         return {
             "message":
             "An error occurred while deleting the item (count) in the database."
         }, 500
     return {"message": "Count Deleted"}, 200
示例#9
0
 def increment_count(self, key, record):
     """
     transactionでアクセスカウントを増やす
     """
     counter = Counter.get(key)
     counter.count += 1
     access_record = AccessRecord(
         parent      = counter,
         count       = counter.count,
         referer     = record['referer'],
         user_agent  = record['user_agent'],
         remote_addr = record['remote_addr'],
         )
     access_record.put()
     return counter.put()
 def post():
     """
     Insert a new record
     :return: insert time
     """
     json = request.get_json()
     current_datetime = datetime.datetime.now()
     try:
         visit = Counter(date_time=current_datetime,
                         agency_id=json["agency_id"])
     except KeyError:
         return {"error": "Lack necessary argument"}, 406
     db.session.add(visit)
     db.session.commit()
     count = len(Counter.query.filter_by(agency_id=json["agency_id"]).all())
     return {"count": count}, 201
示例#11
0
def load_anki_data(kanji_list):
    kanji_list = set(kanji_list)

    # Find out which kanji we actually have cards for
    expected = set()
    for kanji in Kanji.all():
        if kanji.suspended:
            continue
        expected.add(kanji.kanji)

    # Kanji words also get to add to the whitelist
    actual = set()
    for word in Counter.all() + KanjiWord.all():
        if word.suspended:
            continue

        # Add all the kanji in the word
        for kanji in word.kanji:
            # Make sure we only add kanji
            if kana.is_kana(kanji):
                continue

            actual.add(kanji)

    extra = load_extra(settings.EXTRA_DICT_KANJI)

    # Find which kanji we have no cards for
    missing = actual - expected
    if len(missing):
        message("Missing Kanji Found", ' '.join(missing))

    # Notify the user of any kanji that don't have examples (no kanji-words)
    no_example = expected - actual
    if len(no_example):
        message("Kanji with no Examples", ' '.join(no_example))

    # Notify the user of any kanji that aren't in our dictionary
    unknown = (expected | actual) - (kanji_list | extra)
    if len(unknown):
        message("Unknown Kanji, not in Dict:", ' '.join(unknown))

    # Now we finally make our known kanji list
    known = (expected | actual)

    return known
示例#12
0
def load_anki_data(kanji_list):
    kanji_list = set(kanji_list)

    # Find out which kanji we actually have cards for
    expected = set()
    for kanji in Kanji.all():
        if kanji.suspended:
            continue
        expected.add(kanji.kanji)

    # Kanji words also get to add to the whitelist
    actual = set()
    for word in Counter.all() + KanjiWord.all():
        if word.suspended:
            continue

        # Add all the kanji in the word
        for kanji in word.kanji:
            # Make sure we only add kanji
            if kana.is_kana(kanji):
                continue

            actual.add(kanji)

    extra = load_extra(settings.EXTRA_DICT_KANJI)

    # Find which kanji we have no cards for
    missing = actual - expected
    if len(missing):
        message("Missing Kanji Found", ' '.join(missing))

    # Notify the user of any kanji that don't have examples (no kanji-words)
    no_example = expected - actual
    if len(no_example):
        message("Kanji with no Examples", ' '.join(no_example))

    # Notify the user of any kanji that aren't in our dictionary
    unknown = (expected | actual) - (kanji_list | extra)
    if len(unknown):
        message("Unknown Kanji, not in Dict:", ' '.join(unknown))

    # Now we finally make our known kanji list
    known = (expected | actual)

    return known
示例#13
0
    def get(self):

        self.context.update({
            'title':
            u'Создание счёта',
            'module_name':
            url_base,
            'sender':
            RequisitesDB.get_one({'inn': '772160030650'}),
            'recipient':
            RequisitesForm(),
            'bill_content':
            BillContentForm(),
            'bill_num':
            Counter.next_key('bill'),
            'date':
            datetime.now(),
        })
        self.render(tmpl('create'))
示例#14
0
 def get(self):
     try:
         user = users.get_current_user()
         # requestのkeyに対応するCounterを取得
         counter = Counter.get(db.Key(encoded = self.request.get('key')))
         # 現在のユーザーと関連づけられていなければ403エラー
         if counter == None or user != counter.user:
             responses.display_error(self, 403)
             return
         template_values = {
             'user'     : user,
             'user_url' : users.create_logout_url('/'),
             'counter'  : counter,
             'loop'     : range(10),
             }
         path = os.path.join(os.path.dirname(__file__), os.pardir, 'templates', 'config.html')
         self.response.out.write(template.render(path, template_values))
     # requestのkeyが正しくない場合
     except BadKeyError, error:
         logging.error(str(error))
         responses.display_error(self, 400)
示例#15
0
 def get(self):
     try:
         user = users.get_current_user()
         # requestのkeyに対応するCounterを取得
         counter = Counter.get(db.Key(encoded=self.request.get("key")))
         # 現在のユーザーと関連づけられていなければ403エラー
         if counter == None or user != counter.user:
             responses.display_error(self, 403)
             return
         template_values = {
             "user": user,
             "user_url": users.create_logout_url("/"),
             "counter": counter,
             "records": AccessRecord.all().ancestor(counter).order("-count"),
         }
         path = os.path.join(os.path.dirname(__file__), os.pardir, "templates", "record.html")
         self.response.out.write(template.render(path, template_values))
     # requestのkeyが正しくない場合
     except BadKeyError, error:
         logging.error(str(error))
         responses.display_error(self, 400)
示例#16
0
 def post(self):
     """
     requestからkeyを受け取り、対応するCounterのentityを削除する
     """
     try:
         # 削除する対象を取得
         counter = Counter.get(db.Key(encoded = self.request.get('key')))
         # 現在のユーザーと関連づけられていなければ403エラー
         if counter == None or counter.user != users.get_current_user():
             responses.display_error(self, 403)
             return
         # 関連画像、アクセス履歴ともに一括削除
         for image in counter.image:
             NumberImage.get(image).delete()
         for record in AccessRecord.all().ancestor(counter):
             record.delete()
         counter.delete()
         self.redirect('/')
     # requestのkeyが正しくない場合
     except BadKeyError, error:
         logging.error(str(error))
         responses.display_error(self, 400)
示例#17
0
 def get(self):
     """
     ログインしていればユーザーの管理画面へ、
     ログインしていなければトップ画面へ
     """
     user = users.get_current_user()
     if user:
         user_url = users.create_logout_url(self.request.uri)
         counters = Counter.all().filter('user = '******'counters': counters,
             'can_create': True if counters.count() < 3 else False,
             }
     else:
         user_url = users.create_login_url(self.request.uri)
         counter  = None
     template_values = {
         'counter'  : counter,
         'user'     : user,
         'user_url' : user_url,
         }
     path = os.path.join(os.path.dirname(__file__), 'templates', 'index.html')
     self.response.out.write(template.render(path, template_values))
示例#18
0
 def get(self, _to):
     count = Counter.find_count(_to).count
     return {'count': count}, 200