Example #1
0
    def modify_account_balance(self, account_id, amount):
        a = AccountsTable.query.filter(AccountsTable.id == account_id).first()
        if a:
            a.balance += float(amount)

            db_session.add(a)
            db_session.commit()
Example #2
0
def ran_script(script_id):
    if request.args.get('secret') != API_SECRET:
        abort(401)

    event = Event.query.order_by(Event.id.desc()).first()

    defending_team = AttendingTeam.query.filter_by(
        id=request.args.get('team_id'), event=event).first()
    error = int(request.args.get('error'))
    error_msg = request.args.get('error_msg', None)

    script = Script.query.filter_by(id=script_id).first()

    if str(script.type).split(".")[-1] == "exploit":
        abort(500)
        return

    script_run = ScriptRun()
    script_run.script = script
    script_run.attending_team = defending_team
    script_run.error = error
    if len(error_msg) > 2040:
        script_run.error_msg = error_msg[:2040] + "<cut>"  # XXX
    else:
        script_run.error_msg = error_msg
    db_session.add(script_run)
    db_session.commit()

    return jsonify({"result": "great success"})
Example #3
0
def create_post():
    user_id = session['user_id']
    user = db_session.query(User).filter(User.user_id == user_id).first()
    title = request.form['post_title']
    content = request.form['post_content']
    location_description = request.form['location_description']
    longitude = request.form['longitude']
    latitude = request.form['latitude']
    style = request.form['post_style']
    has_cipher = request.form['has_cipher']
    cipher = request.form['post_cipher']
    has_picture = request.form['has_picture']
    new_post = Post(title=title,
                    content=content,
                    location_description=location_description,
                    longitude=longitude,
                    latitude=latitude,
                    style=style,
                    has_cipher=has_cipher,
                    has_picture=has_picture,
                    cipher=cipher,
                    create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    db_session.add(new_post)
    user.posts.append(new_post)
    db_session.commit()

    if has_picture == '1':
        post_picture = request.files['post_picture']
        post_picture.save(sys.path[0] + "/post_picture/" +
                          str(new_post.post_id) + ".png")
    app.logger.info("User %s created post successfully.", user_id)
    return gen_json_success(None)
Example #4
0
def create_script(challenge, type, payload):
    """
    only gets called if is_working is 1
    :param challenge:
    :param type:
    :param script:
    :return:
    """

    # get newest event
    event = Event.query.order_by(Event.id.desc()).first()

    s = Script()
    s.name = type + ".py"
    s.is_working = 1
    s.challenge = challenge
    s.type = type
    s.event = event

    db_session.add(s)
    db_session.commit()
    sp = ScriptPayload()
    sp.script = s
    sp.payload = payload.encode('utf8')
    db_session.add(sp)
    db_session.commit()
Example #5
0
    def edit_expense(self,
                     date,
                     amount,
                     account_id,
                     expense_id,
                     description=None,
                     category_id=None,
                     pass_thru=False):
        e = self.get_simple_expense(expense_id)
        if e:
            # update the totals
            self.totals.update_expense(-float(e.amount), e.date)

            # category and description not provided?
            if not description: description = e.description
            if not category_id: category_id = e.category

            e.date, e.category, e.description, e.deduct_from, e.amount, e.pass_thru\
            = date, category_id, description, account_id, amount, pass_thru
            db_session.add(e)
            db_session.commit()

            # update the totals
            self.totals.update_expense(amount, date)

            return e  # return so we see the updated values
Example #6
0
def dislikes():
    if request.method == "PUT":
        user_id = session['user_id']
        post_id = request.form['post_id']
        user = db_session.query(User).filter(User.user_id == user_id).first()
        post = db_session.query(Post).filter(Post.post_id == post_id).first()
        dislike_found = db_session.query(Dislike).filter(
            Dislike.post_id == post_id and Dislike.user_id == user_id).first()

        if dislike_found is None:
            new_dislike = Dislike()
            user.user_dislikes.append(new_dislike)
            post.post_dislikes.append(new_dislike)
            post.dislike_number += 1
            db_session.add(new_dislike)
            # remove old like
            old_like = db_session.query(Like).filter(
                Like.post_id == post_id and Like.user_id == user_id).first()
            if old_like is not None:
                db_session.delete(old_like)
                post.like_number -= 1
            db_session.commit()
            data = {"dislike_post": True}
        else:
            dislike = db_session.query(Dislike).filter(
                Dislike.post_id == post_id
                and Dislike.user_id == user_id).first()
            post.dislike_number -= 1
            db_session.delete(dislike)
            db_session.commit()
            data = {"dislike_post": False}
        return gen_json_success(data)
Example #7
0
def registercheck():
    if request.method == 'POST':
        if request.form['username'] != "":
            if request.form['password1'] != "":
                if request.form['password1'] == request.form['password2']:
                    if (User.query.filter(User.username == request.
                                          form['username']).first() == None):
                        NewUser = User(request.form['username'],
                                       request.form['password1'])
                        new_posi = posi_ram()
                        NewCity = City(request.form['username'], new_posi[0],
                                       new_posi[1])
                        db_session.add(NewUser)
                        db_session.add(NewCity)
                        db_session.commit()
                        return redirect(url_for('index'))
                    else:
                        error = 'the user already exists!'
                else:
                    error = 'the password1 doesnot equal to password2!'
            else:
                error = 'the password has to be filled!'
        else:
            error = 'the username has to be filled!'
    return render_template('register.html', error=error)
def user_similarity_db():
    """

    :return: calculate all users similarity and insert this information in dabase
    """

    deleted_rows = db_session.query(UserSimilarity).delete()
    db_session.commit()
    print("Deleted %i rows" % deleted_rows)

    local_ = utils.pre_get_movies_by_user()

    all_users = utils.get_all_users()

    for i in all_users:
        print("Calculating similarity of user %i" % i)

        for j in all_users:

            if i < j:
                value = similarity_value(i, j, local_)
                similarity_instance = UserSimilarity(i, j, value)
                db_session.add(similarity_instance)

    db_session.commit()
Example #9
0
    def add_expense(self,
                    date,
                    description,
                    amount,
                    category_id=None,
                    account_id=None,
                    pass_thru=False):
        # add into uncategorized expenses if category not provided
        if not category_id:
            category_id = self.is_category(name="Uncategorized")
            if not category_id:
                # crete a new one
                c = ExpenseCategoriesTable(self.user_id, u'Uncategorized')
                db_session.add(c)
                db_session.commit()
                category_id = c.id

        # find default account if not provided
        if not account_id:
            acc = Accounts(self.user_id)
            account_id = acc.get_default_account()
            if not account_id:
                account_id = acc.add_default_account()

        # add the actual expense
        e = ExpensesTable(self.user_id, date, category_id, description,
                          account_id, amount, pass_thru)
        db_session.add(e)
        db_session.commit()

        # update the totals
        self.totals.update_expense(amount, date)

        return e.id
Example #10
0
def insert_task_to_db(openid, task, task_day, task_month, task_year, task_hour,
                      task_min):
    import hashlib

    hashstr = task + openid + task_day + task_month + task_year + task_hour + task_min
    sha1obj = hashlib.sha1()
    sha1obj.update(hashstr.encode('utf-8'))
    task_ID = sha1obj.hexdigest()

    t_id = Task.query.filter(Task.task_ID == task_ID).first()
    if t_id is not None:
        print(t_id + "已经在数据库!")
    else:
        t = Task(task_ID=task_ID,
                 task=task,
                 thour=task_hour,
                 tmin=task_min,
                 tyear=task_year,
                 tmonth=task_month,
                 tday=task_day)
        try:
            db_session.add(t)
            db_session.commit()
            return 1  # 成功返回 1
        except Exception as e:
            print('插入task到数据库错误: ' + str(e))
            return -1  # 失败返回 -1
Example #11
0
    def add_income(self, account_id, category_id, date, description, amount):
        i = IncomeTable(self.user_id, date, category_id, description, account_id, amount)
        db_session.add(i)
        db_session.commit()

        # update totals
        self.totals.update_income(amount, date)
Example #12
0
def add_user_work_experiences(user,
                              company_name,
                              position,
                              department,
                              entry_at,
                              is_resign=False,
                              dimission_at=None,
                              company_id=0):
    """
    添加用户工作经历
    """

    employer = UserEmployer()
    employer.user_id = user.id
    employer.nickname = user.nickname or user.email
    employer.company_name = company_name
    employer.company_id = company_id
    employer.position = position
    employer.department = department
    employer.entry_at = entry_at
    employer.is_resign = is_resign
    if is_resign:
        employer.dimission_at = dimission_at
    else:
        #解决sqlite不能插入默认字符串时间
        employer.dimission_at = entry_at
    db_session.add(employer)
    db_session.commit()
    return employer
Example #13
0
 def modify_loan_link(self, loan_id, percentage, original_amount):
     le = ExpensesToLoansTable.query.filter(ExpensesToLoansTable.loan == loan_id)
     if le:
         for i in le:
             i.percentage, i.original_amount = percentage, original_amount
             db_session.add(i)
         db_session.commit()
Example #14
0
    def add_expense(self, date, description, amount, category_id=None, account_id=None, pass_thru=False):
        # add into uncategorized expenses if category not provided
        if not category_id:
            category_id = self.is_category(name="Uncategorized")
            if not category_id:
                # crete a new one
                c = ExpenseCategoriesTable(self.user_id, u'Uncategorized')
                db_session.add(c)
                db_session.commit()
                category_id = c.id

        # find default account if not provided
        if not account_id:
            acc = Accounts(self.user_id)
            account_id = acc.get_default_account()
            if not account_id:
                account_id = acc.add_default_account()

        # add the actual expense
        e = ExpensesTable(self.user_id, date, category_id, description, account_id, amount, pass_thru)
        db_session.add(e)
        db_session.commit()

        # update the totals
        self.totals.update_expense(amount, date)

        return e.id
Example #15
0
def level_up_barracks(name,x,y): #升级兵营
    #city = City.query.filter(and_(City.posX==x , City.posY==y)).first()
    city = City.query.filter((City.posX==x) & (City.posY==y)).first()
    if city is None:
        return 'Error: city not exist!'
    if city.barracks >= city.minicipal:
        return 'Fail: Minicipal Level Too Low.'
    cost = (city.barracks*City.BasicPrice['barracks'][0],city.barracks*City.BasicPrice['barracks'][1],city.barracks*City.BasicPrice['barracks'][2],city.barracks*City.BasicPrice['barracks'][3])
    if city.wood <= cost[0]:
        return 'Fail: Wood Not Enough'
    if city.stone <= cost[1]:
        return 'Fail: Stone Not Enough'
    if city.grass <= cost[2]:
        return 'Fail: Grass Not Enough'
    
    #if Message.query.filter(and_(Message.username == name, Message.event =='Level up' , Message.status==0)).first() is not None:
    if Message.query.filter((Message.username == name) & (Message.event =='Level up') & (Message.status==0)).first() is not None:
        return 'Fail: Another Construction Exist' 
    
    print 'OK'
    
    city.wood-=cost[0]
    city.stone-=cost[1]
    city.grass-=cost[2]
    
    mesId = len(Message.query.all())+1
    db_session.add(Message(mesId,name,'system',cost[3],'Level up','Level up: Barracks'))
    db_session.commit()
    #level_up_barracks_done.delay(mesId,x,y,cost[3])
    level_up_barracks_done.apply_async(args=[mesId,x,y], countdown=cost[3])
    return 'Success!'
Example #16
0
def attack(attackerPosX,attackerPosY,defenserPosX,defenserPosY,infantryNum,cavalryNum,archerNum):#进攻事件,接收参数:攻防双方坐标,士兵数目
    #attacker = City.query.filter(and_(City.posX == attackerPosX, City.posY == attackerPosY)).first()
    attacker = City.query.filter((City.posX == attackerPosX) & (City.posY == attackerPosY)).first()
    #defenser = City.query.filter(and_(City.posX == defenserPosX, City.posY == defenserPosY)).first()
    defenser = City.query.filter((City.posX == defenserPosX) & (City.posY == defenserPosY)).first()
    
    if attacker is None or defenser is None:
        return 'Error: city not exist!'
    
    if attacker.infantry < infantryNum or attacker.cavalry < cavalryNum or attacker.archer<archerNum:
        return 'Fail: Army not enough'
    
    mesId1 = len(Message.query.all())+1
    mesId2 = mesId1 + 1
    #time_delta = timedelta(minutes = int(sqrt(attackerPosX*attackerPosX+attackerPosY*attackerPosY)*5))
    countdown_ =  int(sqrt(attackerPosX*attackerPosX+attackerPosY*attackerPosY)*300) #由距离算出到达秒数,用于延时调用
    time_delta = timedelta(seconds = countdown_) #由秒数算出时间间隔,用于写入message
    
    
    db_session.add(Message(mesId1,attacker.name,'system',time_delta,'Attack','Attack: from '+attacker.name+' to ' + defenser.name))
    db_session.add(Message(mesId2,defenser.name,'system',time_delta,'Attack','Attack: from '+attacker.name+' to ' + defenser.name))
    db_session.commit()
    
    #attack_battle.delay(mesId1,mesId2,attackerPosX,attackerPosY,defenserPosX,defenserPosY,infantryNum,cavalryNum,archerNum,time_delta)
    attack_battle.apply_async(args=[mesId1,mesId2,attackerPosX,attackerPosY,defenserPosX,defenserPosY,infantryNum,cavalryNum,archerNum], countdown=countdown_)
    
    return 'Success!'
Example #17
0
def recruit_archer(name,x,y,num=1):#招募弓箭手
    #city = City.query.filter(and_(City.posX==x , City.posY==y)).first()
    city = City.query.filter((City.posX==x) & (City.posY==y)).first()
    if city is None:
        return 'Error: city not exist!'
    if city.archer+city.cavalry+city.archer+num > city.barracks*10:
        return 'Fail: Barracks Level Too Low.'
        
    cost = (City.BasicPrice['archer'][0]*num,City.BasicPrice['archer'][1]*num,City.BasicPrice['archer'][2]*num,City.BasicPrice['archer'][3]*num)
    
    if city.wood <= cost[0]:
        return 'Fail: Wood Not Enough'
    if city.stone <= cost[1]:
        return 'Fail: Stone Not Enough'
    if city.grass <= cost[2]:
        return 'Fail: Grass Not Enough'
    
    #if Message.query.filter(and_(Message.username == name, Message.event =='Recruit' , Message.status==0)).first() is not None:
    if Message.query.filter((Message.username == name) & (Message.event =='Recruit') & (Message.status==0)).first() is not None:
        return 'Fail: Another Recruit Exist' 
    
    print 'OK'
    
    city.wood-=cost[0]
    city.stone-=cost[1]
    city.grass-=cost[2]
    
    mesId = len(Message.query.all())+1
    db_session.add(Message(mesId,name,'system',cost[3],'Recruit','Recruit: Archer'))
    db_session.commit()
    #recruit_archer_done.delay(mesId,x,y,num,cost[3])
    recruit_archer_done.apply_async(args=[mesId,x,y,num], countdown=cost[3])
    return 'Success!'
Example #18
0
    def modify_account_balance(self, account_id, amount):
        a = AccountsTable.query.filter(AccountsTable.id == account_id).first()
        if a:
            a.balance += float(amount)

            db_session.add(a)
            db_session.commit()
Example #19
0
def set_state(team_id, service_id):
    if request.args.get('secret') != API_SECRET:
        abort(401)

    event = Event.query.order_by(Event.id.desc()).first()
    status = int(request.args.get('status'))
    team_id = int(team_id)
    service_id = int(service_id)

    reason = request.args.get('reason')

    if not status in [0, 1, 2]:
        abort(400)

    tss = TeamServiceState()
    tss.attending_team = AttendingTeam.query.filter_by(id=team_id,
                                                       event=event).first()
    tss.challenge = Challenge.query.filter_by(id=service_id,
                                              type="ad",
                                              event=event).first()
    tss.state = status
    if len(reason) > 248:
        tss.reason = reason[:248] + "<cut>"
    else:
        tss.reason = reason
    db_session.add(tss)
    db_session.commit()

    return jsonify({"result": "great success"})
Example #20
0
 def post(self):
     """A post request to this endpoint takes the base_image and
     user_image submitted via json and checks the database to ensure
     a match before issuing a token"""
     current_user = get_jwt_identity()
     if current_user is None:
         response = jsonify({"msg": "unauthenticated"})
         return (response.json), 401
     if not request.is_json:
         response = jsonify({"msg": "Missing JSON in request"})
         return (response.json), 400
     docker_image = request.json.get('image', None)
     docker_tag = request.json.get('tag', None)
     image_format = request.json.get('format', None)
     if not (docker_image and docker_tag and image_format):
         response = jsonify({"msg": "Missing parameter"})
         return (response.json), 400
     if not (image_format == 'qemu' or image_format == 'raw'):
         response = jsonify(
             {"msg":
              "Only qemu and raw image formats are supported"})  # noqa
         return (response.json), 400
     query = User.query.filter_by(username=current_user).first()
     user_id = query.uuid
     status = 'building'
     container_id = Container(user_id, docker_image, docker_tag, status,
                              image_format)
     db.add(container_id)
     db.commit()
     tasks.build_image.apply_async(
         args=[container_id.uuid, docker_image, docker_tag, image_format])
     response = jsonify(status=status, id=container_id.uuid)
     return (response.json), 200
Example #21
0
def newInboundMessage():
    """ This page will be for all inbound messages, check if customer exists if so, check content of message if == "UNSUBSCRIBE", change user status.
    If customer does not exist add to database.
    """
    try:
        print ('requestform', request.form)
        tel = str(request.form['To'])
        user = db_session.query(User).filter_by(
            phone=tel).one()

        if user:
            customer = db_session.query(
                User_Customer).filter_by(phone=request.form['From']).first()
            if customer:
                if request.form['Text'] == "UNSUBSCRIBE":
                    customer.status = "UNSUBSCRIBED"
            else:
                customer = User_Customer(
                    name='UNKNOWN', phone=request.form['From'], user_id=user.id, status="SUBSCRIBED")
                db_session.add(customer)
                db_session.commit()

            newMessage = Message(
                user_id=user.id, user_customer_id=customer.id, message_uuid=request.form['MessageUUID'], message=request.form['Text'], direction="inbound", status="RECEIVED",
                units=request.form["Units"],
                total_rate=request.form["TotalRate"],
                total_amount=request.form["TotalAmount"], error_code="200", message_time=datetime.datetime.now())

            db_session.add(newMessage)
            db_session.commit()
            return jsonify(newMessage.serialize)
    except:
        print('Something went wrong, rolling back transaction!')
        db_session.rollback()
        db_session.commit()
Example #22
0
    def add_income(self, account_id, category_id, date, description, amount):
        i = IncomeTable(self.user_id, date, category_id, description,
                        account_id, amount)
        db_session.add(i)
        db_session.commit()

        # update totals
        self.totals.update_income(amount, date)
Example #23
0
def apiStreamAdd():
    if request.headers['Content-Type'] == 'application/json':
        stream = Stream(name=request.json['name'])
        db_session.add(stream)
        db_session.commit()
    else:
        abort(400)
    return jsonify(stream.serialize())
Example #24
0
def apiDeviceAdd():
    if request.headers['Content-Type'] == 'application/json':
        device = Device(name=request.json['name'])
        db_session.add(device)
        db_session.commit()
    else:
        abort(400)
    return jsonify(device.serialize())
Example #25
0
 def modify_loan_link(self, loan_id, percentage, original_amount):
     le = ExpensesToLoansTable.query.filter(
         ExpensesToLoansTable.loan == loan_id)
     if le:
         for i in le:
             i.percentage, i.original_amount = percentage, original_amount
             db_session.add(i)
         db_session.commit()
Example #26
0
def apiRoomAdd():
    if request.headers['Content-Type'] == 'application/json':
        room = Room(name=request.json['name'], )
        db_session.add(room)
        db_session.commit()
    else:
        abort(400)
    return jsonify(room.serialize())
Example #27
0
    def edit_account_transfer(self, date, deduct_from_account, credit_to_account, amount, transfer_id):
        t = self.get_transfer(transfer_id)
        if t:
            t.date, t.from_account, t.to_account, t.amount = date, deduct_from_account, credit_to_account, amount
            db_session.add(t)
            db_session.commit()

            return t # return so we see the updated values
Example #28
0
 def link_to_loan(self, expense_id, loan_id, shared_with, percentage,
                  original_amount):
     l = ExpensesToLoansTable(expense=expense_id,
                              loan=loan_id,
                              shared_with=shared_with,
                              percentage=percentage,
                              original_amount=original_amount)
     db_session.add(l)
     db_session.commit()
Example #29
0
    def edit_account_transfer(self, date, deduct_from_account,
                              credit_to_account, amount, transfer_id):
        t = self.get_transfer(transfer_id)
        if t:
            t.date, t.from_account, t.to_account, t.amount = date, deduct_from_account, credit_to_account, amount
            db_session.add(t)
            db_session.commit()

            return t  # return so we see the updated values
Example #30
0
 def get_key(self):
     k = UsersKeysTable.query\
     .filter(UsersKeysTable.user == self.user_id)\
     .filter(UsersKeysTable.expires > today_timestamp()).first()
     # generate key
     if not k:
         k = UsersKeysTable(self.user_id)
         db_session.add(k)
         db_session.commit()
     return k
Example #31
0
 def get_key(self):
     k = UsersKeysTable.query\
     .filter(UsersKeysTable.user == self.user_id)\
     .filter(UsersKeysTable.expires > today_timestamp()).first()
     # generate key
     if not k:
         k = UsersKeysTable(self.user_id)
         db_session.add(k)
         db_session.commit()
     return k
Example #32
0
def get_home():
    """
    GET method

    :return:
    """
    m1 = Model1(name="bp1", email="bp1@")
    db_session.add(m1)
    db_session.commit()
    return "GET Inside blueprint1"
Example #33
0
def create_user(name):
    '''A test module for creating users in the system'''

    name = name.lower()
    slug = slugify(name)
    u = UsersTable(name.capitalize(), False, slug, slug)
    db_session.add(u)
    db_session.commit()

    return make_response("User created", 200)
Example #34
0
def get_home():
    """
    GET method

    :return: String
    """
    m1 = Model2(name="bp2", email="bp2@")
    db_session.add(m1)
    db_session.commit()
    return "GET Inside blueprint2"
Example #35
0
    def add_slug(self, type, object_id, description=None, slug=None):
        s = SlugsTable(type=type,
                       object_id=object_id,
                       user_id=self.user_id,
                       description=description,
                       slug=slug)
        db_session.add(s)
        db_session.commit()

        return s.slug
Example #36
0
def create_user(name):
    '''A test module for creating users in the system'''

    name = name.lower()
    slug = slugify(name)
    u = UsersTable(name.capitalize(), False, slug, slug)
    db_session.add(u)
    db_session.commit()

    return make_response("User created", 200)
Example #37
0
def add_asso_group():
    if request.method == 'POST':
        try:
            request_key = request.form.keys()[0]
            get_user_id = int(request_key.split('-')[1])
            get_group_id = int(request.form.get(request_key, ''))
            assouser = db_session.query(GitUser).filter_by(
                id=get_user_id).first()
            assogroup = db_session.query(GitGroup).filter_by(
                id=get_group_id).first()
            if assogroup not in assouser.git_group:
                assouser.git_group.append(assogroup)

            assos = db_session.query(asso_group_user).all()
            if (get_group_id, get_user_id) not in assos:
                try:
                    db_session.add(assouser)
                    db_session.commit()
                    print '====>  Store (%s) to DB successfully.' % assouser.name

                    assogroup_file = BASE_DIR + '/conf/groups/' \
                        + assogroup.name + '.conf'
                    gconf_dict = {}
                    with open(assogroup_file, 'rb') as f:
                        lines = f.readlines()
                        for line in lines:
                            gconf_group = line.split('=')[0].lstrip(
                                '@').strip()
                            gconf_user = line.split('=')[1].split()
                            gconf_dict[gconf_group] = gconf_user
                    allowed_ext_user = []
                    for _ in allowed_ext:
                        allowed_ext_user.append('.'.join(
                            assouser.name.split('.')[:-1]))
                    for _ in set(allowed_ext_user):
                        if gconf_dict.has_key(
                                assogroup.name) and _ not in gconf_dict[
                                    assogroup.name]:
                            gconf_dict[assogroup.name].append(str(_))
                            f = open(assogroup_file, 'wb')
                            f.truncate()
                            for _ in gconf_dict:
                                f.write('@' + _ + ' = ' +
                                        ' '.join(gconf_dict[_]))
                            f.close()
                except TypeError:
                    db_session.rollback()
                    print '====>  TypeError Need string or buffer, list found.'
                finally:
                    db_session.close()
            else:
                print '====>  The record(%s) already exists.' % assouser.name
        except IndexError:
            print '====>  IndexError because of out of range.'
        return redirect(url_for('user'))
Example #38
0
def add_user(email, password):
    """
    添加用户
    """
    user = User()
    user.email = email
    user.salt = random_str(6)
    user.password = password_encrypt(password, user.salt)
    db_session.add(user)
    db_session.commit()
    return user
Example #39
0
    def modify_loan_balance(self, amount, with_user_id):
        a = AccountsTable.query.filter(AccountsTable.user == self.user_id)\
        .filter(AccountsTable.type == "loan")\
        .filter(AccountsTable.name == with_user_id).first()
        if not a:
            a = AccountsTable(self.user_id, with_user_id, 'loan', float(amount)) # create new
        else:
            a.balance += float(amount) # update

        db_session.add(a)
        db_session.commit()
Example #40
0
    def edit_income(self, income_id, account_id, category_id, date, description, amount):
        i = self.get_income(income_id)
        if i:
            # update totals
            self.totals.update_income(-float(i.amount), i.date)

            i.credit_to, i.category, i.date, i.description, i.amount = account_id, category_id, date, description, amount
            db_session.add(i)
            db_session.commit()

            # update totals
            self.totals.update_income(amount, date)
Example #41
0
def init_project():
    project = Project()
    project.name = u'我的第一个项目'
    db_session.add(project)
    db_session.commit()

    project_database = ProjectDatabase()
    project_database.project_id = project.id
    project_database.db_name = 'first.db'
    project_database.db_type = DatabaseType.SQLITE
    db_session.add(project_database)
    db_session.commit()
Example #42
0
def create_user(data):
	user = None
	data = data.get('data')
	if data:
		user_id = data.get('id')
		if user_id:
			user = db_session.query(User).get(user_id)
		else:
			user = User(data.get('login'),data.get('name'),data.get('password'),data.get('email'))
			db_session.add(user)
		db_session.commit()	
	return jsonify({u'user': orm_to_dict(user) if user else None})
Example #43
0
    def add_loan(self, other_user_id, date, description, amount, account_id=None):
        # if an account id is not provided, get a 'default' account
        if not account_id:
            accounts = Accounts(self.user_id)
            account_id = accounts.get_default_account()
            # create a default account if no joy getting a default account
            if not account_id:
                account_id = accounts.add_default_account()
        l = LoansTable(self.user_id, other_user_id, date, account_id, description, amount)
        db_session.add(l)
        db_session.commit()

        return l.id
Example #44
0
    def modify_user_balance(self, amount, account_id=None):
        if not account_id:
            a = AccountsTable.query.filter(AccountsTable.user == self.user_id).filter(AccountsTable.type != "loan")\
            .order_by(asc(AccountsTable.id)).first()
        else:
            a = AccountsTable.query.filter(AccountsTable.user == self.user_id)\
            .filter(AccountsTable.id == account_id).first()

        if a:
            a.balance += float(amount)

            db_session.add(a)
            db_session.commit()
Example #45
0
def dashboard():
    '''Test budget dashboard'''

    u = UsersTable(u"Admin", False, u"admin", u"admin")
    db_session.add(u)
    db_session.commit()

    current_user_id = u.id

    # get uncategorized expenses
    exp = Expenses(current_user_id)
    uncategorized_expenses = exp.get_entries(category_name="Uncategorized")

    # get latest expenses
    exp = Expenses(current_user_id)
    latest_expenses = exp.get_entries(limit=5)

    # get accounts
    acc = Accounts(current_user_id)
    accounts = acc.get_accounts_and_loans()

    # split, get totals
    assets, liabilities, loans, assets_total, liabilities_total = [], [], [], 0, 0
    for a in accounts:
        if a[0].type == 'asset':
            assets.append(a)
            assets_total += float(a[0].balance)
        elif a[0].type == 'liability':
            liabilities.append(a)
            liabilities_total += float(a[0].balance)
        elif a[0].type == 'loan':
            # if we owe someone, it is our liability
            if float(a[0].balance) < 0:
                liabilities.append(a)
                liabilities_total += float(a[0].balance)
            else:
                assets.append(a)

    # get the monthly totals
    t = Totals(current_user_id)
    totals = t.get_totals()

    return render_template('admin_dashboard.html', **locals())

#class SQLiteSequenceTable(Base):
#    """SQLite sequence table"""
#
#    __tablename__ = 'sqlite_master'
#    rowid = Column(Integer, primary_key=True)
#    name = Column(String(200))
#    seq = Column(Integer)
Example #46
0
    def update_income(self, amount, date):
        # generate a month/year string
        m = MonthYear(date)

        # get the corresponding entry
        t = TotalsTable.query\
        .filter(and_(TotalsTable.user == self.user, TotalsTable.month == str(m))).first()

        if not t:
            # brand spanking new
            t = TotalsTable(self.user, str(m), 0, amount)
        else:
            # update the total
            t.income += float(amount)

        # save
        db_session.add(t)
        db_session.commit()
Example #47
0
    def edit_expense(self, date, amount, account_id, expense_id, description=None, category_id=None, pass_thru=False):
        e = self.get_simple_expense(expense_id)
        if e:
            # update the totals
            self.totals.update_expense(-float(e.amount), e.date)

            # category and description not provided?
            if not description: description = e.description
            if not category_id: category_id = e.category

            e.date, e.category, e.description, e.deduct_from, e.amount, e.pass_thru\
            = date, category_id, description, account_id, amount, pass_thru
            db_session.add(e)
            db_session.commit()

            # update the totals
            self.totals.update_expense(amount, date)

            return e # return so we see the updated values
Example #48
0
def add_user_work_experiences(user, company_name, position, department, entry_at, is_resign=False, dimission_at=None, company_id=0):
    """
    添加用户工作经历
    """

    employer = UserEmployer()
    employer.user_id = user.id
    employer.nickname = user.nickname or user.email
    employer.company_name = company_name
    employer.company_id = company_id
    employer.position = position
    employer.department = department
    employer.entry_at = entry_at
    employer.is_resign = is_resign
    if is_resign:
        employer.dimission_at = dimission_at
    else:
        #解决sqlite不能插入默认字符串时间
        employer.dimission_at = entry_at
    db_session.add(employer)
    db_session.commit()
    return employer
Example #49
0
def registercheck():
    if request.method == 'POST':
        if request.form['username'] != "" :
            if request.form['password1'] != "":
                if request.form['password1'] == request.form['password2']:
                    if (User.query.filter(User.username== request.form['username'] ).first() == None):
                        NewUser=User(request.form['username'],request.form['password1'])
                        new_posi=posi_ram();
                        NewCity=City(request.form['username'],new_posi[0],new_posi[1])
                        db_session.add(NewUser)
                        db_session.add(NewCity)
                        db_session.commit()
                        return redirect(url_for('index'))
                    else:        
                        error = 'the user already exists!'
                else :
                    error = 'the password1 doesnot equal to password2!'
            else :
                error = 'the password has to be filled!'
        else :
            error = 'the username has to be filled!'
    return render_template('register.html', error=error)
Example #50
0
    def edit_loan(self, other_user_id, date, amount, description=None, loan_id=None, slug=None, account_id=None):
        if slug:
            # find object id first
            s = SlugsTable.query\
            .filter(and_(SlugsTable.slug == slug, SlugsTable.type == 'loan', SlugsTable.user == self.user_id))\
            .first()

            loan_id = s.object_id

        l = self.get_loan(loan_id=loan_id)
        if l:
            # description not provided
            if not description: description = l.description

            # save new values
            l.other_user, l.date, l.description, l.amount = other_user_id, date, description, amount
            # changing the account?
            if account_id: l.account = account_id

            db_session.add(l)
            db_session.commit()

            return l # return so we see the updated values
Example #51
0
 def add_connection(self, user_id):
     c = UsersConnectionsTable(self.user_id, user_id)
     db_session.add(c)
     c = UsersConnectionsTable(user_id, self.user_id)
     db_session.add(c)
     db_session.commit()
Example #52
0
 def add_private_user(self, name):
     u = UsersTable(name, True)
     db_session.add(u)
     db_session.commit()
     return u.id
Example #53
0
    def add_default_account(self):
        a = AccountsTable(self.user_id, "Default", 'default', 0)
        db_session.add(a)
        db_session.commit()

        return a.id
Example #54
0
 def add_account(self, name, type, balance):
     a = AccountsTable(self.user_id, name, type, balance)
     db_session.add(a)
     db_session.commit()
Example #55
0
 def add_account_transfer(self, date, deduct_from_account, credit_to_account, amount):
     t = AccountTransfersTable(self.user_id, date, deduct_from_account, credit_to_account, amount)
     db_session.add(t)
     db_session.commit()
Example #56
0
def attack_battle(
    mesId1, mesId2, attackerPosX, attackerPosY, defenserPosX, defenserPosY, infantryNum, cavalryNum, archerNum
):  # 战斗事件,决定胜负,损失士兵数和战利品数
    countdown_ = int(sqrt(attackerPosX * attackerPosX + attackerPosY * attackerPosY) * 300)
    timedelta_ = timedelta(seconds=countdown_)
    # time.sleep(timedelta)
    # attacker = City.query.filter(and_(City.posX == attackerPosX, City.posY == attackerPosY)).first()
    # defenser = City.query.filter(and_(City.posX == defenserPosX, City.posY == defenserPosY)).first()
    attacker = City.query.filter((City.posX == attackerPosX) & (City.posY == attackerPosY)).first()
    defenser = City.query.filter((City.posX == defenserPosX) & (City.posY == defenserPosY)).first()

    mes1 = Message.query.filter(Message.messageId == mesId1).first()
    mes2 = Message.query.filter(Message.messageId == mesId2).first()

    mes1.status = 1
    mes2.status = 1

    wood = 0
    stone = 0
    grass = 0

    attack_point = (
        City.BasicAbility["infantry"][0] * infantryNum
        + City.BasicAbility["cavalry"][0] * cavalryNum
        + City.BasicAbility["archer"][0] * archerNum
    )
    defense_point = (
        City.BasicAbility["infantry"][1] * defenser.infantry
        + City.BasicAbility["cavalry"][1] * defenser.cavalry
        + City.BasicPrice["archer"][1] * defenser.archer
    )
    if attack_point > defense_point:
        defenser.infantry /= 4
        defenser.cavalry /= 4
        defenser.archer /= 4
        db_session.flush()
        infantryNum = max(infantryNum / 4, infantryNum - defenser.infantry)
        cavalryNum = max(cavalryNum / 4, cavalryNum - defenser.cavalry)
        archerNum = max(archerNum / 4, archerNum - defenser.archer)
        mes1.detail = (
            "Victory!\nYour Survivors: Infantry %d, Cavalry %d, Archer %d\nEnermy Survivors: Infantry %d, Cavalry %d, Archer %d"
            % (infantryNum, cavalryNum, archerNum, defenser.infantry, defenser.cavalry, defenser.archer)
        )
        mes2.detail = (
            "Defeat!\nYour Survivors: Infantry %d, Cavalry %d, Archer %d\nEnermy Survivors: Infantry %d, Cavalry %d, Archer %d"
            % (defenser.infantry, defenser.cavalry, defenser.archer, infantryNum, cavalryNum, archerNum)
        )

        wood = defenser.wood / 2
        stone = defenser.stone / 2
        grass = defenser.grass / 2
        defenser.wood -= wood
        defenser.stone -= stone
        defenser.grass -= grass

    else:
        infantryNum /= 4
        cavalryNum /= 4
        archerNum /= 4
        defenser.infantry = max(defenser.infantry / 4, defenser.infantry - infantryNum)
        defenser.cavalry = max(defenser.cavalry / 4, defenser.cavalry - cavalryNum)
        defenser.archer = max(defenser.archer / 4, defenser.archer - archerNum)
        mes1.detail = (
            "Defeat!\nYour Survivors: Infantry %d, Cavalry %d, Archer %d\nEnermy Survivors: Infantry %d, Cavalry %d, Archer %d"
            % (infantryNum, cavalryNum, archerNum, defenser.infantry, defenser.cavalry, defenser.archer)
        )
        mes2.detail = (
            "Victory!\nYour Survivors: Infantry %d, Cavalry %d, Archer %d\nEnermy Survivors: Infantry %d, Cavalry %d, Archer %d"
            % (defenser.infantry, defenser.cavalry, defenser.archer, infantryNum, cavalryNum, archerNum)
        )

    mesId = len(Message.query.all()) + 1
    mes = Message(
        mesId,
        attacker.username,
        "system",
        timedelta_,
        "Come Back",
        "Come Back: Infantry %d, Cavalry %d, Archer %d" % (infantryNum, cavalryNum, archerNum),
    )
    mes.detail = "Spoils: Wood %d , Stone %d, Grass  %d" % (wood, stone, grass)
    db_session.add(mes)
    db_session.commit()
    # attack_return.delay(mesId,attackerPosX,attackerPosY,infantryNum,cavalryNum,archerNum,wood,stone,grass,timedelta)
    attack_return.apply_async(
        args=[mesId, attackerPosX, attackerPosY, infantryNum, cavalryNum, archerNum, wood, stone, grass],
        countdown=countdown_,
    )
Example #57
0
 def add_category(self, name):
     c = IncomeCategoriesTable(self.user_id, name)
     db_session.add(c)
     db_session.commit()