Пример #1
0
def load_accounts(data='troll-tweets/users.csv'):
    """Load user accounts from users.csv into database."""

    df = pd.read_csv(data)

    df['id'].replace(np.nan, 0, regex=True, inplace=True)
    df.replace(np.nan, '', regex=True, inplace=True)

    for index, row in df.iterrows():
        user_id, location, name, followers_count, statuses_count, time_zone,\
        verified, lang, screen_name, description, created_at, favorites_count,\
        friends_count, listed_count = row.values.tolist()

        if user_id == '':
            account = Account(screen_name=screen_name)
        else:
            account = Account(user_id=user_id,
                              location=location,
                              name=name,
                              followers_count=followers_count,
                              statuses_count=statuses_count,
                              time_zone=time_zone,
                              verified=verified,
                              lang=lang,
                              screen_name=screen_name.lower(),
                              description=description,
                              created_at=created_at,
                              favorites_count=favorites_count,
                              friends_count=friends_count,
                              listed_count=listed_count)

        db.session.add(account)

    db.session.commit()
 def get_account(self,values,userid,name):
   balance=None
   if userid:
     account=Account.gql("where userid=:1 limit 1",userid).get()
     if not account:
       if name:
         account=Account()
         account.userid=userid
         account.name=name
         account.balance=0
         account.put()
       else:
         account=None
     else:
       balance=account.balance
       name=account.name
   else:
     account=None
   values["userid"]=userid
   if balance:
     values["balance"]=balance/100.0
   else:
     values["balance"]=0.0
   values["name"]=name
   return account
Пример #3
0
def user_signup():
    """ Displays a signup form for new users. """

    if request.method == "GET":
        return render_template("signup_form.html")

    # post request logic starts here
    email = request.form.get("email")
    password = request.form.get("password")

    if email_is_valid(email):

        flash(
            "It looks like you are already signed up for Readerboard!  Try signing in instead."
        )
        return redirect("/signin")

    else:

        new_user = User()
        db.session.add(new_user)
        db.session.commit()
        new_acct = Account(user_id=new_user.user_id,
                           email=email,
                           password=password)
        db.session.add(new_acct)

        db.session.commit()
        session['acct'] = new_acct.acct_id

        return redirect("/auth/goodreads")
Пример #4
0
def otp_send():
    print "inside sendotp"
    if not request.json.get('mobile'):
        abort(400)
    else:
        user_id = request.json.get('mobile')
        otp = pyotp.TOTP('base32secret3232').now()
        try:
            act_rec = Account.query.filter_by(user_id=user_id).first()
            if act_rec:
                act_rec.otp = otp
                act_rec.last_updated_on = ctime()
                session_commit()
                res = jsonify({'result': 'modified'})
            else:
                act = Account(user_id, otp)
                account_added = add_row(act)
                if account_added:
                    res = jsonify({'result': 'created'})
                else:
                    return make_response(jsonify({'result': 'failed'}), 501)
            email_otp(user_id, otp)
            return make_response(res, 200)
        except Exception, e:
            logging.error(str(e))
            abort(400)
Пример #5
0
    def __add_account_2_mem(self, data):
        # add id_to_service_dic
        account = Account(db_update_fun=DBAccountInst.update_ls, **data)
        self.__id_to_dic[str(data['id'])] = account
        self.__phone_ls.append(data['phone'])

        TeamMgr().add_leader(data['id'], data['leader_id'])
Пример #6
0
def login():
    username = request.form['username']
    password = request.form['password']

    sha512 = hashlib.sha512()
    sha512.update(password.encode())
    hashed_password = sha512.hexdigest()
    response = {}

    user = db.session.query(Account).filter_by(name=username).first()
    current_time = datetime.now().strftime('%m/%d/%Y, %H:%M:%S')
    cookie = generate_cookie(username, hashed_password, current_time)

    if user:
        if user.password == hashed_password:
            response['status'] = 'login successfully'
        else:
            response['status'] = 'failed'
    else:
        response['status'] = 'register successfully'
        new_user = Account(username, hashed_password)
        db.session.add(new_user)
        db.session.commit()

    response['cookie'] = '' if response['status'] == 'failed' else cookie
    if response['status'] != 'failed':
        new_cookie = Cookie(username, cookie)
        db.session.add(new_cookie)
        db.session.commit()

    return json.dumps(response)
Пример #7
0
def account_from_api_object(obj, instance):
    return Account(
        mastodon_instance=instance,
        mastodon_id=obj['id'],
        screen_name='{}@{}'.format(obj['username'], instance),
        display_name=obj['display_name'],
        avatar_url=obj['avatar'],
        reported_post_count=obj['statuses_count'],
    )
Пример #8
0
def create_account(email, password, login_id):
    """Create Account."""

    account = Account(email=email, password=password, login_id=login_id)

    db.session.add(account)
    db.session.commit()

    return account
Пример #9
0
def create_account(user_id, account_type, account_nickname):
    """Create and return an account."""

    account = Account(user_id=user_id,
                      account_type=account_type,
                      account_nickname=account_nickname)
    db.session.add(account)
    db.session.commit()

    return account
Пример #10
0
def start():
    while True:
        selection = v.get_initial_menu_choice()
        print(f'this was the selection: {selection}')
        #is it better to test for quit first or go in same order as menu?
        if int(selection) == 1:  #create account
            first_name, last_name, pin = v.create_account_prompt()
            account = Account()
            account_num = account.create_account(first_name, last_name, pin)
            account.save_account()
            account.save_file()
            v.confirm_account_creation(account.account_num)
        elif int(selection) == 2:  #login
            account = Account()
            account_num, pin = v.login_prompt()
            authenticated_user = account.login(account_num, pin)

            #if the login is successful -- validated by model show next menu
            while authenticated_user:
                selection = v.get_main_menu_choice(
                    authenticated_user.first_name,
                    authenticated_user.last_name,
                    authenticated_user.account_num)
                if int(selection) == 1:  #check balance
                    v.show_balance(authenticated_user.get_balance())
                elif int(selection) == 2:  #withdraw
                    amount = v.withdrawal_prompt()
                    authenticated_user.withdraw(amount)
                    authenticated_user.save_account()
                    authenticated_user.save_file()
                elif int(selection) == 3:  #deposit
                    amount = v.deposit_prompt()
                    authenticated_user.deposit(amount)
                    authenticated_user.save_account()
                    authenticated_user.save_file()
                elif int(selection) == 4:  #quit
                    v.confirm_quit()
                    break

        elif int(selection) == 3:
            v.confirm_quit()
            break
Пример #11
0
def create_account():
    db.session.add(
        Account(
            first_name=request.form['first_name'],
            last_name=request.form['last_name'],
            email=request.form['email'],
            password=request.form['password'],
            picture='some picture url ?',
        ), )
    db.session.commit()
    return render_template('index.html')
Пример #12
0
def add_account(first_name,last_name,username,password,gender,acc_type):
    if check_user_exists(username)==False:
        add_account = Account(
            first_name= first_name,
            last_name = last_name,
            username = username,         
            password = password,            
            gender = gender,
            acc_type = acc_type)
        session.add(add_account)
        session.commit()
    else:
        raise Exception("User already exists")
Пример #13
0
def create_entity_using_keyword_arguments(user_dict, userid, entries=1):
    user = Account()
    # logging.info("USer obj looks like {}".format(dict(user_dict)))

    # user_dict = {unicode(k).encode("utf-8"): unicode(v).encode("utf-8") for k,v in dict(user_dict).iteritems()}
    if user_dict["last_name"]:
        user.username = user_dict["first_name"] + " " + user_dict["last_name"]
    else:
        user.username = user_dict["first_name"]
    user.userid = userid
    user.entries = entries
    # user.phone_no = user_dict["phone_number"]
    return user
Пример #14
0
def account_login(user, access_token):
    """Add account to db."""
    this_account = Account.query.filter_by(user_id=user.id).first()
    if this_account:
        this_account.last_login = datetime.datetime.now()
        this_account.access_token = access_token
        db.session.add(this_account)
        db.session.commit()
        return

    this_account = Account(user_id=user.id,
                           access_token=access_token,
                           last_login=datetime.datetime.now())
    db.session.add(this_account)
    db.session.commit()
    return
Пример #15
0
def create_account(account_id, available_balance, type, name, user):
    """Create and return a new account."""
    account = Account.query.filter_by(account_id=account_id).first()

    #check if it exists in database to avoid repeating PK, if not add it
    if not account:
        account = Account(account_id=account_id,
                          available_balance=available_balance,
                          type=type,
                          name=name,
                          user=user)

        db.session.add(account)
        db.session.commit()

        return account
Пример #16
0
def create(event, context):
    body = {
        "message": "Go Serverless v1.0! Your function executed successfully!",
        "input": event
    }
    # body = {
    #     role : value
    # }
    # from event find pathParameters and extract id from there
    # if 'event' in event:
    #     id = event['id']
    # else:
    #     body = {"Error" : "Manditory field ID not provided"}
    #     return response = {
    #     "statusCode": 500,
    #     "body": json.dumps(body)
    # }
    # user = User.get(User.id == 1)
    # # user = User.get(id=id)
    payload = json.loads(event['body'])

    name = payload['name'] if 'name' in payload else None
    address1 = payload['address1'] if 'address1' in payload else None
    address2 = payload['address2'] if 'address2' in payload else None
    state = payload['state'] if 'state' in payload else None
    city = payload['city'] if 'city' in payload else None
    zip = payload['zip'] if 'zip' in payload else None
    phone = payload['phone'] if 'phone' in payload else None
    web = payload['web'] if 'web' in payload else None
    contact_name = payload[
        'contact_name'] if 'contact_name' in payload else None
    contact_email = payload[
        'contact_email'] if 'contact_email' in payload else None

    account = Account(name = name , address1 = address1, address2 = address2, state = state, \
    city = city, zip = zip, phone = phone, web = web, contact_name = contact_name, contact_email = contact_email)
    account.save()
    # user = User(role = 'Admin', user_name = 'Sumanth', first_name = 'Sumanth', last_name = 'Reddy', phone_number = '+914567890987', email_id = '*****@*****.**')
    # user.save()

    response = {"statusCode": 200, "body": json.dumps(account.id)}

    return response

    # Use this code if you don't use the http event with the LAMBDA-PROXY
    # integration
    """
Пример #17
0
def to_account_mysql():
    all_account = request.args.get('account')
    if ',' in all_account:
        account_list = all_account.split(',')
        log(account_list)
    else:
        account_list = [all_account]
        log(account_list)
    for account_name in account_list:
        account.name = account_name
        info = account.run_uploads()
        if info:
            # 上传数据库
            from model import Account
            _account = Account(info)
            _account.to_mysql_weixin()
            return '上传成功'
        return '上传失败'
Пример #18
0
    def post(self):
        # try:
        data = parser.parse_args()
        print(hashlib.md5(data['password'].encode()).hexdigest())
        if User.query.filter(User.username == data['username']).first():
            return {"error": "User already exists"}

        u = User(username=data['username'],
                 password=hashlib.md5(data['password'].encode()).hexdigest())
        u.save()
        s = Account(username=(data['username']))
        s.save()
        access_token = create_access_token(identity=data['username'])
        refresh_token = create_refresh_token(identity=data['username'])
        return {
            'username': data['username'],
            'access_token': access_token,
            'refresh_token': refresh_token
        }
Пример #19
0
def create_cred(uuid):

    content = request.json

    sys_username = content['username']
    sys_password = content['password']
    service_id = content['service_id']
    encrypted_pass = encrypt_string(sys_password)

    acc = Account(datetime.datetime.now(), sys_username, str(encrypted_pass),
                  service_id)
    db.session.add(acc)
    db.session.commit()

    print(content['username'])
    print(content['password'])
    print(encrypted_pass)
    print(content['service_id'])
    return jsonify({"username": content['username']})
Пример #20
0
async def init_data():
    await db.init_db(user_dsn)
    await db.begin()
    print('-   初始化表:account')
    password = '******'
    passwd_md5 = hashlib.md5(password.encode('utf-8')).hexdigest()
    account = Account()
    account.uid = 'admin'
    account.name = '管理员'
    account.password = passwd_md5
    account.usergroup = 'admin'
    await account.save()
    print('-   初始化表:usergroup')
    usergroup = Usergroup()
    usergroup.gid = 'admin'
    usergroup.role = 'admin'
    usergroup.name = '管理员'
    await usergroup.save()
    usergroup.gid = 'core'
    usergroup.role = 'user'
    usergroup.name = '核心组'
    await usergroup.save()
    usergroup.gid = 'front'
    usergroup.role = 'user'
    usergroup.name = '前置组'
    await usergroup.save()
    usergroup.gid = 'manger'
    usergroup.role = 'user'
    usergroup.name = '管理组'
    await usergroup.save()
    usergroup.gid = 'chanle'
    usergroup.role = 'user'
    usergroup.name = '渠道组'
    await usergroup.save()
    usergroup.gid = 'public'
    usergroup.role = 'user'
    usergroup.name = '公共'
    await usergroup.save()
    await db.commit()
    rows = await Usergroup.read(where='gid=%s', args=['public'])
    print(rows)
    await db.close_db(user_dsn)
Пример #21
0
    def signIn(self, *args):
        username = self.txtUsername.get()
        password = self.txtPassword.get()
        account = Account(username, password)

        if self.isValidated() == False:
            messagebox.showwarning("Warning", "Please fill the text boxes!")
            return

        if self.isCorrectAccount(account) == False:
            messagebox.showerror("Error", "Account not found!")
            return

        if ShareHelper.currentAccount.getRole() == "Student":
            messagebox.showinfo("Information", "Student signed in")
        elif ShareHelper.currentAccount.getRole() == "Teacher":
            messagebox.showinfo("Information", "Teacher signed in")

        self.frame.destroy()
        ProfileFrame()
Пример #22
0
 def decorated_function(*args, **kwargs):
     user = users.get_current_user()
     if user:
         account = Account.query(Account.userid == user.user_id()).fetch(1)
         if account:
             g.user = account[0]
             logging.info('Existed account, key:' + str(account[0].key))
         else:
             logging.info("New account, google user id:" +
                          str(user.user_id()))
             new_account = Account(userid=user.user_id(),
                                   username=user.nickname(),
                                   email=user.email())
             new_account_key = new_account.put()
             logging.info('New account, key:' + str(new_account_key))
             g.user = new_account
     else:
         url = users.create_login_url('/')
         return redirect(url)
     return f(*args, **kwargs)
Пример #23
0
    def register(self):
        global account
        username = input('Choose your username: '******'Choose your password: '******'accounts']  # returns accounts array
        for acc in accounts:
            """ check if the user already exists. 
            if yes, tell the user, 
            else ask about initial deposit """

            if acc['username'] == username:
                try:
                    raise LoginError()
                except LoginError:
                    print('An account with this username already exists.')
                    return
                finally:
                    logger.error(
                        f'{self.getCurrentTime()}:ERROR:user: has attempted to register with an existing username.'
                    )
        newAccDeposit = input(
            'Would you like to make a deposit in your new account Y/N. ')
        if newAccDeposit.upper() == 'Y':
            amount = float(input('How much do you want to deposit: '))

        account = Account.Account(username, password, amount)
        # accounts += [{"username": username, "password": password, 'amount': amount}]
        accounts += [{
            "username": account.getUsername(),
            "password": account.getPassword(),
            "amount": account.getAmount()
        }]
        logger.info(
            f'{self.getCurrentTime()}:INFO:{username}: has registered with our bank.'
        )
        self.saveAccounts(data)
Пример #24
0
    def login(self, username, password) -> bool:
        print('logging in...')

        data = dao.getAccountData()
        for acc in data['accounts']:
            if acc['username'] == username and acc['password'] == password:
                print('successfully logged in')
                global account
                account = Account.Account(str(username), str(password),
                                          float(acc['amount']))
                logger.info(
                    f'{self.getCurrentTime()}:INFO:{username}: has successfully logged in.'
                )
                return True
        try:
            raise LoginError
        except LoginError:
            print('Cannot login with this username/password pair.')
            logger.error(
                f'{self.getCurrentTime()}:ERROR:Failed login using username:password pair.{username}:{password}'
            )
        finally:
            return False
Пример #25
0
    def get(self):
        self.response.write(open('header.html').read())
        an = self.request.get('tfAcNo')
        ahn = self.request.get('tfAcHName')
        amn = self.request.get('tfHMNo')
        ab = self.request.get('tfAcBalance')
        city = self.request.get('ddCity')
        # getting branch
        bc = self.request.get('tfBC')
        bn = self.request.get('tfBN')
        bm = self.request.get('tfBM')
        bp = self.request.get('tfBP')

        self.response.write(an + "<br/>")
        self.response.write(ahn + "<br/>")
        self.response.write(amn + "<br/>")
        self.response.write(ab + "<br/>")
        self.response.write(city + "<br/>")
        # creating a model Account
        act = Account()
        act.AcNo = int(an)
        act.AcHName = ahn
        act.AcMobNo = amn
        act.AcBalance = float(ab)
        act.City = city
        # creating an instance of Branch
        br = Branch()
        br.BCode = int(bc)
        br.BName = bn
        br.BManager = bm
        br.BPINCode = int(bp)
        # setting to account instance
        act.BranchInfo = br
        # storing into database
        key = act.put()
        self.response.write(key.urlsafe())
Пример #26
0
def account_from_api_user_object(obj):
    return Account(twitter_id=obj['id_str'],
                   display_name=obj['name'],
                   screen_name=obj['screen_name'],
                   avatar_url=obj['profile_image_url_https'],
                   reported_post_count=obj['statuses_count'])
Пример #27
0
def example_data():
    """Create example data for the test database."""
    Dislike.query.delete()
    Stargazer.query.delete()
    Watcher.query.delete()
    Follower.query.delete()
    Contributor.query.delete()
    RepoLanguage.query.delete()
    Language.query.delete()
    Repo.query.delete()
    Account.query.delete()
    User.query.delete()

    jane = User(user_id="1",
                login="******",
                name="Jane",
                last_crawled=datetime.datetime.now(),
                last_crawled_depth=2)
    alex = User(user_id="2",
                login="******",
                name="Alex",
                last_crawled=(datetime.datetime.now() -
                              datetime.timedelta(weeks=6)),
                last_crawled_depth=2)
    kelly = User(user_id="3", login="******", name="Kelly")
    db.session.add_all([jane, alex, kelly])
    db.session.commit()

    jane_account = Account(user_id="1", access_token="abc123")
    db.session.add(jane_account)
    db.session.commit()

    py_repo = Repo(repo_id="1",
                   name="python-repo",
                   description="A Python repository",
                   owner_id="1",
                   last_crawled=datetime.datetime.now(),
                   last_crawled_depth=2,
                   url="https://github.com/jhacks/python-repo",
                   stargazers_count=2)
    js_repo = Repo(repo_id="2",
                   name="js-repo",
                   description="A Javascript repository",
                   owner_id="1",
                   last_crawled=(datetime.datetime.now() -
                                 datetime.timedelta(weeks=6)),
                   last_crawled_depth=1,
                   url="https://github.com/jhacks/js-repo",
                   stargazers_count=1)
    db.session.add_all([py_repo, js_repo])
    db.session.commit()

    astar = Stargazer(repo_id="1", user_id="2")
    kstar = Stargazer(repo_id="1", user_id="3")
    kstar_js = Stargazer(repo_id="2", user_id="3")
    a_dislike_js = Dislike(repo_id="2", user_id="2")
    # k_dislike_js = Dislike(repo_id="2", user_id="3")
    db.session.add_all([astar, kstar, kstar_js, a_dislike_js])
    db.session.commit()

    kwatch = Watcher(repo_id="1", user_id="3")
    a_j_follow = Follower(user_id="1", follower_id="2")
    k_j_follow = Follower(user_id="1", follower_id="3")
    j_a_follow = Follower(user_id="2", follower_id="1")
    db.session.add_all([kwatch, a_j_follow, k_j_follow, j_a_follow])
    db.session.commit()

    jcon = Contributor(repo_id="1", user_id="1")
    kcon = Contributor(repo_id="1", user_id="3")
    db.session.add_all([jcon, kcon])
    db.session.commit()

    # python = Topic(topic_id="1", topic_name="python")
    # api = Topic(topic_id="2", topic_name="api")
    # db.session.add_all([python, api])
    # db.session.commit()

    # py_rep1 = RepoTopic(topic_id="1", repo_id="1")
    # api_rep1 = RepoTopic(topic_id="2", repo_id="1")
    # db.session.add_all([py_rep1, api_rep1])
    # db.session.commit()

    py_lang = Language(language_id="1", language_name="python")
    c_lang = Language(language_id="2", language_name="c")
    db.session.add_all([py_lang, c_lang])
    db.session.commit()

    py_lang_rep1 = RepoLanguage(language_id="1",
                                repo_id="1",
                                language_bytes=5000)
    c_lang_rep1 = RepoLanguage(language_id="2",
                               repo_id="1",
                               language_bytes=100)
    db.session.add_all([py_lang_rep1, c_lang_rep1])
    db.session.commit()
Пример #28
0
def socket_handler(action):

    if action['type'] == 'server/login':
        account = Account.query.filter(
            Account.email == action['data']['email']).first()
        if account and checkpw(action['data']['password'].encode('utf-8'),
                               account.password.encode('utf-8')):
            game = Game.query.filter(Game.account == account,
                                     Game.finished_at == None).first()
            login(account, game)
        else:
            error_message(action['type'], 'Invalid login')

    elif action['type'] == 'server/logout':
        logout()

    elif action['type'] == 'server/register':
        email = action['data']['email']
        password = action['data']['password']
        account = Account.query.filter(Account.email == email).first()
        if not account:
            password = hashpw(password.encode('utf-8'), gensalt())
            try:
                account = Account(email=email,
                                  password=password.decode('utf-8'))
            except AssertionError:
                error_message(action['type'], 'Invalid email address')
            else:
                commit_to_db(account)
                login(account)

    elif action['type'] == 'server/join_game':
        room_id = action['data']['room_id'].upper()
        name = action['data']['name']
        game = Game.query.filter(Game.room_id == room_id,
                                 Game.finished_at == None).first()
        if game and not game.in_progress:
            player = Player.query.filter(Player.game_id == game.game_id,
                                         Player.name == name).first()
            if not player and len(game.players) < 8:
                player = Player(game=game, name=name)
                commit_to_db(player)
                join_game(game, player)
            elif not player and len(game.players) >= 8:
                error_message(action['type'], 'Game is full')
            else:
                error_message(action['type'], 'Duplicate name')
        elif game and game.in_progress:
            error_message(action['type'], 'Game already in progress')
        else:
            error_message(action['type'], 'Invalid room')

    elif action['type'] == 'server/leave_game':
        player_id = action['data']['player_id']
        game_id = action['data']['game_id']
        player = Player.query.filter(Player.player_id == player_id).one()
        game = Game.query.filter(Game.game_id == game_id).one()
        commit_to_db(player, delete=True)
        leave_game(game)

    elif action['type'] == 'server/create_game':
        account_id = action['data']
        account = Account.query.filter(Account.account_id == account_id).one()
        active_game = Game.query.filter(Game.account == account,
                                        Game.finished_at == None).first()
        if not active_game:
            game = Game(account=account, room_id=generate_room_id())
            commit_to_db(game)
            login(account, game)
        else:
            error_message(action['type'],
                          'Game {} is active'.format(active_game.room_id))

    elif action['type'] == 'server/delete_game':
        account_id = action['data']['account_id']
        game_id = action['data']['game_id']
        account = Account.query.filter(Account.account_id == account_id).one()
        game = Game.query.filter(Game.game_id == game_id).one()
        close_game(game)
        delete_game(game)
        login(account)

    elif action['type'] == 'server/start_game':
        game_id = action['data']['game_id']
        game = Game.query.filter(Game.game_id == game_id).one()
        if len(game.players) >= 3 and not game.in_progress:
            assign_prompts(game.players)
            begin_game(game)
            start_game(game)
        elif game.in_progress:
            error_message(action['type'], 'Game already in progress')
        else:
            error_message(
                action['type'],
                'There must be at least 3 players in game in order to play')

    elif action['type'] == 'server/ready':
        player_id = action['data']['player_id']
        node = PlayerPrompt.query.filter(
            PlayerPrompt.player_id == player_id).first()
        prompt = node.prompt
        answer_phase(prompt)

    elif action['type'] == 'server/answer':
        player_id = action['data']['player_id']
        prompt_id = action['data']['prompt_id']
        answer_text = action['data']['answer']
        if answer_text == '':
            answer_text = 'No Answer'
        player = Player.query.filter(Player.player_id == player_id).one()
        players = [p.player_id for p in player.game.players]
        node = PlayerPrompt.query.filter(
            PlayerPrompt.prompt_id == prompt_id,
            PlayerPrompt.player_id.in_(players)).one()
        answer = Answer(player=player, node=node, text=answer_text)
        commit_to_db(answer)
        if player_id == node.player_id:
            next_node = PlayerPrompt.query.filter(
                PlayerPrompt.node_id == node.next_id).one()
            next_prompt = next_node.prompt
            answer_phase(next_prompt)
        elif sum([len(p.answers) - 2 for p in player.game.players]) == 0:
            vote_phase(player.game, node)
        else:
            answer_wait()

    elif action['type'] == 'server/vote':
        player_id = action['data']['player_id']
        answer_id = action['data']['answer_id']
        player = Player.query.filter(Player.player_id == player_id).one()
        answer = Answer.query.filter(Answer.answer_id == answer_id).one()
        node = answer.node
        game = player.game
        players = [p.player_id for p in game.players]
        nodes = PlayerPrompt.query.filter(
            PlayerPrompt.player_id.in_(players)).all()
        vote = Vote(player=player, answer=answer)
        commit_to_db(vote)
        if sum([len(n.answers[0].votes) + len(n.answers[1].votes) - \
            len(players) + 2 for n in nodes]) == 0:
            vote_display(game, node, last=True)
        elif (len(node.answers[0].votes) + len(node.answers[1].votes) - \
            len(players) + 2) == 0:
            vote_display(game, node)
        else:
            vote_wait(node)
Пример #29
0
		return 1
	else:
		return 0
session=connection.init_db()
query=session.query(Account)
for account in query:
	web_se=vote.vote_login(account.account,account.passwd)
	if web_se:
		vote.auto_vote(web_se,account)
	elif is_full_name(account.account.strip()):
		session.delete(account)
		session.commit()
		logging.warning('delete '+account.account)
	elif vote.vote_login(account.account.strip()+'@qq.com',account.passwd.strip()):
		vote.auto_vote(vote.vote_login(account.account.strip()+'@qq.com',account.passwd.strip()),account)
		ac=Account(account=account.account.strip()+'@qq.com',passwd=account.passwd.strip())
		session.add(ac)
		session.delete(account)
		session.commit()
		logging.warning('add '+ac.account)
	elif vote.vote_login(account.account.strip()+'@163.com',account.passwd.strip()):
		vote.auto_vote(vote.vote_login(account.account.strip()+'@163.com',account.passwd.strip()),account)
		ac=Account(account=account.account.strip()+'@163.com',passwd=account.passwd.strip())
		session.add(ac)
		session.delete(account)
		session.commit()
		logging.warning('add '+ac.account)
	else:
		session.delete(account)
		session.commit()
		logging.warning('delete '+account.account)		
Пример #30
0
# -*- coding: utf-8 -*-

import time
import os
from configobj import ConfigObj
from model import Account

basedir = os.path.abspath(os.path.dirname(__file__))

if __name__ == '__main__':
    conf = ConfigObj(
        os.environ.get('APP_SETTINGS', os.path.join(basedir, 'conf.cfg')))
    account = Account(conf)

    def on_transaction(t, c):
        print('Transaction received, tag: {0}, confirmed: {1}'.format(
            t.tag, c))
        print('{0}'.format(t))

    account.on_new_transaction_received = on_transaction

    account.call_history(print_history=True)

    while True:
        account.call_history()
        time.sleep(int(conf['SLEEP']))