Ejemplo n.º 1
0
 def post(self):
     data = self.request.json
     vers = self.db.query(VersionHistory).filter_by(package_id=data["package_id"]).all()
     rlss = self.db.query(Release).filter_by(package_id=data["package_id"]).all()
     
     if data["option"] == "install" or data["option"] == "siteconf" or data["option"] == "uninstall":
         src_release_id = rlss[-1].id
         dst_release_id = rlss[-1].id
     elif data["option"] == "backup" or data["option"] == "upgrade":
         src_release_id = vers[-1].id
         dst_release_id = rlss[-1].id
         if src_release_id == dst_release_id:
             src_release_id = vers[-2].id
     elif data["option"] == "rollback":
         src_release_id = rlss[-1].id
         if rlss[-1].id == vers[-1].id:
             dst_release_id = vers[-2].id
         else:
             dst_release_id = vers[-1].id
     else:
         raise
     
     data["src_release_id"] = src_release_id
     data["dst_release_id"] = dst_release_id
     ope = Operation(**data)
     self.db.add(ope)
     self.db.commit()
     
     logqueues["%s" % ope.id] = Queue.Queue()
     self.finish(ope.serialize())
Ejemplo n.º 2
0
def login():
    email = request.form.get('email')
    password = request.form.get('password')

    if email and password:  # 所有的数据不为空
        newAdmin = Admin.query.filter(Admin.email == email).first()
        if newAdmin and newAdmin.checkPassword(password=password):  #用户存在且密码正确
            session.permanent = True  # 设置session
            session['adminId'] = newAdmin.id

            operate = Operation(time=datetime.now(),
                                ip=request.remote_addr,
                                operate='登录')
            operate.adminId = newAdmin.id
            db.session.add(operate)
            db.session.commit()  # 将管理员的操作记录下来

            msg = {
                'code': 1,
                'id': newAdmin.id,
                'email': newAdmin.email,
                'createTime': str(newAdmin.createTime)
            }
            return jsonify(msg)
        else:
            return jsonify({'code': 2})  #用户名或密码错误
    else:
        return jsonify({'code': 0})  #参数错误
Ejemplo n.º 3
0
def balance(request):
    """ View card  balans and store this operation in db"""
    card = request.user
    date = datetime.utcnow()
    operation = Operation(card=card, date=date, operation='0')
    operation.save()
    content = {'date': date.date, 'balance': card.balance,
               'card': split_number(card.card_number)}
    return render(request, 'balance.html', content)
Ejemplo n.º 4
0
    def POST(self, id):
        user = get_object_or_404(User, id=id)
        form = CreditForm()

        if not form.validates():
            return render.credit(user, form)

        Operation.new(user_id=id, amount=form.d.amount, date=datetime.datetime.now()).save()
        user.balance += float(form.d.amount)
        user.save()

        raise web.seeother('/')
Ejemplo n.º 5
0
    def POST(self, id):
        user = get_object_or_404(User, id=id)
        form = CreditForm()

        if not form.validates():
            return render.credit(user, form)
        #problem here
        amount = str(form.d.amount).replace(',', '.', 1)

        Operation.new(user_id=id, amount=amount,
                      date=datetime.datetime.now()).save()
        user.balance += float(amount)
        user.save()

        raise web.seeother('/')
Ejemplo n.º 6
0
def do_update(request):
    if request.method == "POST":
        ips = request.POST["ips"]
        op = Operation(o_ips=ips)
        op.save()
        op_id = op
        ip_list = ips.split(";")
        for ip in ip_list:
            ip = ip.strip()
            if ip:
                per_ip(ip, op_id)
        resp = "success"
    else:
        resp = "GET not allowed"
    return HttpResponse(resp)
Ejemplo n.º 7
0
    def POST(self, id):
        user = get_object_or_404(User, id=id)
        form = ConsumeForm()

        if not form.validates():
            raise web.seeother('/users/{}'.format(user.id))

        amount = settings.CONSUMPTION_UNIT*int(form.d.units)
        Operation.new(user_id=id, amount=-amount, date=datetime.datetime.now()).save()
        user.balance -= float(amount)
        user.save()

        if b'userside' in web.data():
            return render_no_layout.consume(None, user)
        else:
            raise web.seeother('/')
Ejemplo n.º 8
0
    def POST(self, id):
        user = get_object_or_404(User, id=id)
        form = ConsumeForm()

        if not form.validates():
            raise web.seeother('/users/{}'.format(user.id))

        amount = settings.CONSUMPTION_UNIT * int(form.d.units)
        Operation.new(user_id=id, amount=-amount,
                      date=datetime.datetime.now()).save()
        user.balance -= float(amount)
        user.save()

        if b'userside' in web.data():
            return render_no_layout.consume(None, user)
        else:
            raise web.seeother('/')
Ejemplo n.º 9
0
def withdrawal(request):
    """ View withdrawal process, """
    if request.POST:
        date = datetime.utcnow()
        card = request.user
        amount = int(request.POST.get('amount'))
        if card.balance < amount:
            return render(request, 'error_page.html', {})
        operation = Operation(card=card, date=date, operation='1',
                              amount=amount)
        operation.save()
        card.balance -= amount
        card.save()
        content = {'date': date.date, 'balance': card.balance,
                   'card': split_number(card.card_number), 'amount': amount}
        return render(request, 'report.html', content)


    return render(request, 'withdrawal.html', {})
Ejemplo n.º 10
0
    def GET(self, id):
        try:
            user = User.get(rfid=id)
            amount = settings.CONSUMPTION_UNIT
            Operation.new(user_id=user.id, amount=-amount, date=datetime.datetime.now()).save()
            user.balance -= float(amount)
            user.save()

            return "OK"
        except Entry.DoesNotExist:
            body = settings.MAIL_TPL_UNKNOWN_CARD.format(
                    new_user_url = urlize('/users/add/?rfid={}'.format(id)),
                    existing_user_url = urlize('/users/rfid/{}'.format(id)),
                    hour=datetime.datetime.now().strftime('%H:%M'))

            web.sendmail(settings.MAIL_ADDRESS,
                settings.SECRETARY_MAIL_ADDRESS,
                '[INGIfet] Carte inconnue {}'.format(id),
                body)

            raise web.notfound()
Ejemplo n.º 11
0
def confirmations(product_url,user_mail,user_firstName,user_lastName,tweet_id,tweet_message,product_id,size,date_tweet,user):

    print "confirmation function"
    #Confirmation tweet
    if product_url:
        if size:
            print ' size '
            #api.update_status('Votre achat a ete enregistre, taille %s'%(size),tweet_id)
        else:
            print 'no size'
            #api.update_status('Votre achat a ete enregistre',tweet_id)
    if not size:
        size='none'

    #Confirmation mail
    message = mail.EmailMessage(sender="Admin <%s>"%( os.environ['admin_mail'] ),
    subject="%s new command"%( os.environ['hashtag'] ))
    message.to = "%s <%s>" %( user_firstName,user_mail )
    message.body = """ Hi %s
    Your tweet has been taken in consideration and added tou your %s Cart
     """ %( user_firstName, os.environ['website_name'] )
    message.send()
    mail_sent = True

    #Obtain today's date
    today = datetime.datetime.today()

    #Add the operation to the datastore
    operation = Operation(
        tweet_id=int(tweet_id),
        tweet_message = tweet_message,
        iceberg_product_id = int(product_id),
        iceberg_offer_id = 0,
        iceber_variation = size,
        mail_sent=mail_sent,
        time_stamp=today,
        date=date_tweet,
        user=user
    )
    operation.put()
Ejemplo n.º 12
0
 def run(self):
     """
     This function doing something depending on users' choice.
     """
     i = 0
     while i != 8:
         i = self.view.user_input(self.view.menu_function)
         if i == 1:
             for operation in self.session.query(Operation).all():
                 print(operation)
         elif i == 2:
             new_operation = self.view.get_new_operation_data()
             new_operation['date'] = self.session.query(Date).filter_by(date=new_operation['date']).first() or \
                                     Date(date=new_operation['date'])
             self.session.add(Operation(**new_operation))
             self.session.commit()
         elif i == 3:
             for operation in self.session.query(Operation).filter_by(
                     money=float(
                         self.view.user_input(
                             self.view.get_money_function))).all():
                 print(operation)
         elif i == 4:
             for operation in self.session.query(Operation).filter_by(
                     description=self.view.get_description_function()).all(
                     ):
                 print(operation)
         elif i == 5:
             for operation in self.session.query(Operation).filter_by(
                     date=self.session.query(Date).filter_by(
                         date=self.view.get_datetime()).first()).all():
                 print(operation)
         elif i == 6:
             print("Balance = %.2f" % Operation.get_balance(self.session))
         elif i == 7:
             for operation in self.session.query(Operation).all():
                 self.session.delete(operation)
             self.session.commit()
         elif i != 8:
             print("Wrong choice, try again")
Ejemplo n.º 13
0
    def GET(self, id):
        try:
            user = User.get(rfid=id)
            amount = settings.CONSUMPTION_UNIT
            Operation.new(user_id=user.id,
                          amount=-amount,
                          date=datetime.datetime.now()).save()
            user.balance -= float(amount)
            user.save()

            return "OK"
        except Entry.DoesNotExist:
            body = settings.MAIL_TPL_UNKNOWN_CARD.format(
                new_user_url=urlize('/users/add/?rfid={}'.format(id)),
                existing_user_url=urlize('/users/rfid/{}'.format(id)),
                hour=datetime.datetime.now().strftime('%H:%M'))

            web.sendmail(settings.MAIL_ADDRESS,
                         settings.SECRETARY_MAIL_ADDRESS,
                         '[INGIfet] Carte inconnue {}'.format(id), body)

            raise web.notfound()
Ejemplo n.º 14
0
def routing(message):
    session = DBSession()
    try:
        user = session.query(User).filter_by(
            telegramid=message.from_user.id).first()
        if not user:
            user = User(telegramid=message.from_user.id)
            session.add(user)
            user.operation = Operation()
            session.commit()
        if user.operation is None:
            user.operation = Operation()
            session.commit()
        db_connector.save_to_log(
            from_who='user',
            message=message)  # Сохранение входящего сообщения в БД.
        text = utils.text_lower_wo_command(message)
        if not user.active:
            bot.send_message(message.chat.id, 'Вы заблокированы.')
        elif text in ('start', 'help'):
            handle_start_help(message, session, user)
        elif not user.registrationDone or user.operation.current_operation == opRegister:
            register_flow(bot, message, session)
        elif text in admin_functions.admin_commands:
            #Для правильной работы необходим заполненный admin_id в config
            admin_functions.admin_flow(bot, message, session)
        elif text in standard.create_group or user.operation.current_operation == create_group.opGroup:
            create_group.route_flow(bot, message, session)
        elif text in standard.find_group or user.operation.current_operation == join_group.opGroup:
            join_group.route_flow(bot, message, session)
        else:
            not_found(message)
        session.commit()
    except Exception as e:
        session.rollback()
        raise e
    finally:
        session.close()
Ejemplo n.º 15
0
def save_to_log(from_who='user',
                message_type=None,
                message=None,
                comment_text='',
                msg_text=''):
    """Сохранить в лог. Внимательно передавать from_who

    from_who - 'bot', 'user', 'system'. От кого сообщение
    message - тип message. Сообщение от пользователя.
    comment_text - дополнительный текст.
    msg_text - текст сообщения. Использовать для сохранения ответа бота на message пользователя

    Примеры.
    save_to_log('user', message) - сохранить сообщение от пользователя.
    save_to_log('system', comment_text=err_text) - сохранить сообщение от системы. Например, об ошибке.
    save_to_log('bot', message=message_from_user, msg_text=bot_msg_text) - сохранить сообщение от бота пользоателю.
    """
    if from_who not in ('bot', 'user', 'system'):
        comment_text += ' ' + from_who
        from_who = 'need_help'
    operation = None
    tid = None
    session = DBSession()
    if message:
        tid = message.from_user.id
        if from_who == 'user':
            if message.content_type == 'text':
                msg_text = message.text
            if message.content_type == 'contact':
                msg_text = str(message.contact)

        operation = session.query(Operation).filter_by(telegramid=tid).first()

    if operation is None: operation = Operation()
    log = Log(datetime=datetime.datetime.now(),
              from_who=from_who,
              user_id=tid,
              msg_text=msg_text,
              msg_type=message_type,
              operation=operation.current_operation,
              status=operation.operation_status,
              additional_info=operation.additional_info_db,
              function=inspect.stack()[1][3],
              comment=comment_text)
    session.add(log)
    session.commit()
    session.close()
Ejemplo n.º 16
0
def transfer(userSource, userTarget, title, amount, admin):
    try:
        userSource_acc = Account.objects.filter(owner=userSource)
        if not userSource_acc:
            raise Exception(u"Nieznany użytkownik")
        userSource_acc = userSource_acc[0]
        
        
        
        
        userTarget_acc = Account.objects.filter(owner=userTarget)
        if not userTarget_acc:
            raise Exception(u"Nieznany użytkownik")
        userTarget_acc = userTarget_acc[0]
            
            
        if userSource == userTarget and admin != 1:
            raise Exception(u"Nie można przelewać na swoje konto!")
        
        if amount < 0 and admin != 1:
            raise Exception(u"Ujemna kwota przelewu!")
        
        if amount == 0:
            raise Exception("Kwota musi być różna od 0")
        
        if userSource_acc.balance < amount and admin != 1:
            raise Exception(u"Brak środków!")
            
        
        transfer_obj = Operation()
        transfer_obj.SourceAccount = userSource_acc
        transfer_obj.TargetAccount = userTarget_acc
        transfer_obj.title = title
        transfer_obj.amount = amount
        transfer_obj.save()
        userTarget_acc.balance += amount
        userTarget_acc.save()
        if admin != 1:
            userSource_acc = Account.objects.filter(owner=userSource)[0]
            userSource_acc.balance -= amount
            userSource_acc.save()
        return 'Ok'
    except Exception,e:
        return e
Ejemplo n.º 17
0
def transfer(userSource, userTarget, title, amount, admin):
    try:
        userSource_acc = Account.objects.filter(owner=userSource)
        if not userSource_acc:
            raise Exception(u"Nieznany użytkownik")
        userSource_acc = userSource_acc[0]

        userTarget_acc = Account.objects.filter(owner=userTarget)
        if not userTarget_acc:
            raise Exception(u"Nieznany użytkownik")
        userTarget_acc = userTarget_acc[0]

        if userSource == userTarget and admin != 1:
            raise Exception(u"Nie można przelewać na swoje konto!")

        if amount < 0 and admin != 1:
            raise Exception(u"Ujemna kwota przelewu!")

        if amount == 0:
            raise Exception("Kwota musi być różna od 0")

        if userSource_acc.balance < amount and admin != 1:
            raise Exception(u"Brak środków!")

        transfer_obj = Operation()
        transfer_obj.SourceAccount = userSource_acc
        transfer_obj.TargetAccount = userTarget_acc
        transfer_obj.title = title
        transfer_obj.amount = amount
        transfer_obj.save()
        userTarget_acc.balance += amount
        userTarget_acc.save()
        if admin != 1:
            userSource_acc = Account.objects.filter(owner=userSource)[0]
            userSource_acc.balance -= amount
            userSource_acc.save()
        return 'Ok'
    except Exception, e:
        return e
Ejemplo n.º 18
0
def init_db():
    # --- Inserting a user ---
    test = User(username='******', email='*****@*****.**', password='******')
    test.save()

    # --- Inserting some operation-types ---
    tokenization = OperationType(nameOp='Tokenization')
    tokenization.save()

    stopWords = OperationType(nameOp='Stop words')
    stopWords.save()

    lemmatization = OperationType(nameOp='Lemmatization')
    lemmatization.save()

    stemming = OperationType(nameOp='Stemming')
    stemming.save()

    posTagging = OperationType(nameOp='Pos Tagging')
    posTagging.save()

    bagOfWords = OperationType(nameOp='Bag of words')
    bagOfWords.save()

    TfIdf = OperationType(nameOp='TF-IDF')
    TfIdf.save()

    word2Vec = OperationType(nameOp='Word2Vec')
    word2Vec.save()

    # --- Inserting an operation ---
    stopWordOp1 = Operation(
        text=
        "منذ انعقاد المجلس الوطني الأخير لحزب العدالة والتنمية لا حديث بين الأعضاء إلا عن أساليب التهديد والوعيد التي بات يرفعها بعض أعضاء الأمانة العامة في وجه المخالفين للقيادة الحالية.",
        textType="input",
        result=
        "['انعقاد', 'المجلس', 'الوطني', 'الأخير', 'لحزب', 'العدالة', 'والتنمية', 'حديث', 'الأعضاء', 'أساليب', 'التهديد', 'والوعيد', 'بات', 'يرفعها', 'أعضاء', 'الأمانة', 'العامة', 'وجه', 'المخالفين', 'للقيادة', 'الحالية', '.']",
        dateCr="2012-10-15T21:26:17Z",
        user=test,
        operation_type=stopWords)
    stopWordOp1.save()

    tokenOp1 = Operation(
        text="منذ انعقاد المجلس الوطني الأخير لحزب العدالة والتنمية",
        textType="input",
        result=
        "[ 'منذ', 'انعقاد', 'المجلس', 'الوطني', 'الأخير', 'لحزب', 'العدالة', 'والتنمية' ]",
        dateCr="2012-10-15T21:26:17Z",
        user=test,
        operation_type=tokenization)
    tokenOp1.save()

    # --- Inserting some datas ---
    data1 = Data(url="lakom",
                 title="tttttttttt",
                 content="test",
                 language="arabic",
                 datePost="now",
                 score=4,
                 classe=1)
    data1.save()

    data2 = Data(url="lakom",
                 title="tttttttttt",
                 content="test",
                 language="arabic",
                 datePost="now",
                 score=4,
                 classe=1)
    data2.save()


# --- Main function ---
# if(__name__=='__main__'):
#     init_db()
Ejemplo n.º 19
0
	def get(self):

		self.response.headers['Content-Type'] = 'application/json'

		new = False
		custom = False
		if len(self.request.get('parent')) > 0:
			custom = True

		if len(self.request.get('operation')) > 0:
			if custom:
				operation = CustomOperation.get_by_key(self.request.get('operation'))
			else:
				operation = Operation.get_by_key(self.request.get('operation'))
			operation.updated = datetime.now()
		else:
			if custom:
				operation = CustomOperation()
				operation.target = ndb.Key(urlsafe = self.request.get('target'))
				operation.parent = ndb.Key(urlsafe = self.request.get('parent'))
				parent = Operation.get_by_key(operation.parent.urlsafe())
				operation.name = parent.name
				operation.target = parent.target
				operation.direction = parent.direction
				operation.amount = parent.amount
				operation.frequency = parent.frequency
				operation.cutoff_date = parent.cutoff_date
			else:
				operation = Operation()
			new = True

		if custom and len(self.request.get('notes')) > 0:
			operation.notes = self.request.get('notes')

		if not custom and new or len(self.request.get('direction')) > 0:
			operation.direction = self.request.get('direction')
		if not custom and new or len(self.request.get('name')) > 0:
			operation.name = self.request.get('name')
		if not custom and new or len(self.request.get('target')) > 0:
			operation.target = ndb.Key(urlsafe = self.request.get('target'))
		if not custom and new or len(self.request.get('amount')) > 0:
			operation.amount = float(self.request.get('amount'))
		if len(self.request.get('frequency')) > 0:
			operation.frequency = self.request.get('frequency')
		if len(self.request.get('delay_raise')) > 0:
			operation.frequency = float(self.request.get('delay_raise'))
		if not custom and new or len(self.request.get('cutoff_date')) > 0:
			daymonth_freq = ['bimonthly', 'yearly']
			cutoff_date = self.request.get('cutoff_date').split(',')
			cutofflist = []
			if operation.frequency in daymonth_freq:
				count  = 0
				cutoffdict = {}
				for cutoff in cutoff_date:
					count += 1
					logging.warning('DEBUG OperationSet - count modulo 2: %i' % (count % 2))
					if count % 2 != 0:
						cutoffdict['day'] = int(cutoff)
						logging.warning('DEBUG OperationSet - cutoffdict: %s' % str(cutoffdict))
					else:
						cutoffdict['month'] = int(cutoff)
						logging.warning('DEBUG OperationSet - cutoffdict: %s' % str(cutoffdict))
						cutofflist.append(cutoffdict)
						cutoffdict = {}
			else:
				for cutoff in cutoff_date:
					cutofflist.append({'day': int(cutoff)})
						
			operation.cutoff_date = json.dumps(cutofflist)

		operation.put()

		if custom:
			operationtype = 'custom'
		else:
			operationtype = 'standard'

		output = {'status': 0, 'message': 'Pago agregado.', 'operation': {'key': operation.key.urlsafe(), 'type': operationtype, 'name': operation.name, 'target': operation.target.urlsafe(), 'amount': operation.amount, 'frequency': operation.frequency, 'cutoff_date': operation.cutoff_date, 'created': tools.datetime_to_str(operation.created), 'updated': tools.datetime_to_str(operation.updated)}}

		logging.warning('DEBUG OperationSet - output: %s' % str(output))
		self.response.write(json.dumps(output))
Ejemplo n.º 20
0
	def get(self):
		self.response.headers['Content-Type'] = 'application/json'
		target = self.request.get('target')

		url = '%s%s/api/organization/tree?entity=%s' % (config.PROTOCOL, config.APP_HOSTNAME, target)
		result = urlfetch.fetch(url)
		if result.status_code == 200:
			orgtree = json.loads(result.content)
		else:
			orgtree = None

		logging.warning('DEBUG OperationList - orgtree: %s' % str(orgtree))

		key = ndb.Key(urlsafe = target)
		operationlist = []
		replaced = []
		has_parent = True
		if orgtree is not None:
			while has_parent:
				if key.kind() == 'CN':
					entity = CN.get_by_key(key.urlsafe())
					operations = CustomOperation.fetch_by_target(entity.key.urlsafe())
				if key.kind() == 'OU':
					entity = OU.get_by_key(key.urlsafe())
					operations = Operation.fetch_by_target(entity.key.urlsafe())
				if key.kind() == 'Organization':
					entity = Organization.get_by_key(key.urlsafe())
					operations = Operation.fetch_by_target(entity.key.urlsafe())
					has_parent = False
				
				for operation in operations:
					operationdict = {'key': operation.key.urlsafe(), 'name': operation.name, 'target': operation.target.urlsafe(), 'target_kind': key.kind(), 'direction': operation.direction, 'amount': operation.amount, 'frequency': operation.frequency, 'cutoff_date': json.loads(operation.cutoff_date), 'delay_raise': operation.delay_raise, 'created': tools.datetime_to_str(operation.created), 'updated': tools.datetime_to_str(operation.updated)}

					if key.kind() == 'CN':
						operationdict['parent'] = operation.parent.urlsafe()
						replaced.append(operation.parent.urlsafe())

					operationlist.append(operationdict)

				if has_parent:
					key = entity.parent

		index = 0
		operationlist_clone = operationlist[:]
		for operation in operationlist_clone:
			logging.warning('DEBUG OperationList multidirectional - replaced: %s - operation[key]: %s- in: %s' % (str(replaced), operation['key'], str(operation['key'] in replaced)))
			if operation['key'] in replaced:
				operationlist.pop(index)
			else:
				index += 1
			logging.warning('operationlist(%i) - operationlist_clone(%i)' % (len(operationlist), len(operationlist_clone)))

		if self.request.get('direction') in ['in', 'out']:
			index = 0
			oplist_clone = operationlist[:]
			logging.warning('DEBUG OperationList unidirectional - operationlist(%i): %s' % (len(oplist_clone), str(operationlist)))
			for op in oplist_clone:
				if op['direction'] != self.request.get('direction'):
					operationlist.pop(index)
				else:
					index += 1
				logging.warning('operationlist(%i) - operationlist_clone(%i)' % (len(operationlist), len(oplist_clone)))

		self.response.write(json.dumps(operationlist))
Ejemplo n.º 21
0
    def GET(self, id):
        user = get_object_or_404(User, id=id)
        operations = Operation.filter(user_id=id, order_by='date DESC')

        return render.user(user, operations)
Ejemplo n.º 22
0
def analyseTweet(tweet):

    #env variables
    admin_mail = os.environ['admin_mail']
    hashtag = os.environ['hashtag']
    website_name = os.environ['website_name'] 
    application_name = os.environ['application_name'] 

    # Tweet variables   
    date_tweet = tweet.created_at
    twitter_username = tweet._json['user']['screen_name']
    tweet_id = tweet.id
    tweet_message =  tweet.text
    mail_sent = False         

    print twitter_username

    user = None
    user_mail = False

    # determine if user exists
    users = db.GqlQuery("SELECT * FROM User WHERE twitterUsername ='******'" %(twitter_username) )

    for res in users:

        user_exists = True
        user = res
        user_mail = res.mail
        user_firstName = res.firstName

    if not user:
        print "user doesn't exists"
        return

    if not user.active:
        print 'account desactivated'
        return


    print "The user exists, great "

    #determine if operation has already been treated
    operations = db.GqlQuery("SELECT * FROM Operation WHERE tweet_id =%s" %(tweet_id) )
    for operation in operations:
        print 'tweet has already been taken into consideration'
        return

    #Obtain url from parent tweet
    product_url = False
    parent_id = tweet.in_reply_to_status_id
    parent_status = api.get_status(str(parent_id))
    for url in parent_status.entities['urls']:
        link = url['expanded_url']
        if application_name in link:
            product_url = link
    product_id = product_url.split('/')[-2]

    #Obtain size id there is one
    size = False
    for hashtag in tweet.entities['hashtags']:
        if hashtag['text'][0] == 'T' or hashtag['text'][0] == 't':
            size =  hashtag['text'].split('_')
            size = size[1]

    #Confirmation tweet
    if product_url:
        if size:
            print ' size '
            #api.update_status('Votre achat a ete enregistre, taille %s'%(size),tweet_id)
        else:
            print 'no size'
            #api.update_status('Votre achat a ete enregistre',tweet_id)
    if not size:
        size='none'

    #obtain today's date
    today = datetime.datetime.today()
    print today

    #Confirmation mail
    message = mail.EmailMessage(sender="Admin <%s>"%(admin_mail),
    subject="%s new command"%(hashtag))
    message.to = "%s <%s>" %(user_firstName,user_mail)
    message.body = """ Hi %s
    Your tweet has been taken in consideration and added tou your %s Cart
     """ %(user_firstName, application_name)
    message.send()
    mail_sent = True

    AddFunction=addToCart()
    AddFunction.add(52,"*****@*****.**", "Florian", "Poullin") 


    #add the operation to the datastore
    operation = Operation(
        tweet_id=int(tweet_id),
        tweet_message = tweet_message,
        iceberg_product_id = int(product_id),
        iceberg_offer_id = 0,
        iceber_variation = size,
        mail_sent=mail_sent,
        time_stamp=today,
        date=date_tweet,
        user=user
    )
    operation.put()
Ejemplo n.º 23
0
    def GET(self, id):
        user = get_object_or_404(User, id=id)
        operations = Operation.filter(user_id=id, order_by='date DESC')

        return render.user(user, operations)