Ejemplo n.º 1
0
def start(bot, update):

    ordinal = lambda n: "%d%s" % (n, "tsnrhtdd"[(n / 10 % 10 != 1) *
                                                (n % 10 < 4) * n % 10::4])
    chat_id = update.message.chat_id
    user_id = update.message.from_user.id
    user_obj = bot.getChat(chat_id)
    ancestor_key = ndb.Key('Account', user_id or '*notitle*')
    curr_user = Account.query_users(ancestor_key).fetch()

    if not curr_user:
        account = create_entity_using_keyword_arguments(user_obj, user_id)
        account.key = ndb.Key('Account', user_id)
        account.put()
        # ancestor_key = ndb.Key('Account',user_id or '*notitle*')
        curr_user = Account.query_users(account.key).fetch()
        bot.sendMessage(
            chat_id=chat_id,
            text="Welcome to the Booking Bot, {}.\n How many people?".format(
                user_obj["first_name"]))
    else:
        user = ancestor_key.get()
        user.entries += 1
        user.put()
        bot.sendMessage(
            chat_id=chat_id,
            text=
            """Welcome again to the Booking Bot {}.\nThis is your {} time here.
			\nHow many people?""".format(user_obj["first_name"], ordinal(user.entries)))
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
    def post(self):
        author = users.get_current_user()
        acct = self.request.get('acct')
        psw = self.request.get('psw')
        acctType = self.request.get('acctType')
        account = Account(author=author, acct=acct, psw=psw, acctType=acctType)
        account.put()

        self.redirect('/Accounts')
Ejemplo n.º 4
0
def test_create():
    """
    """
    account = {
        'account_name': 'flask sv',
        'start_on': '2021-05-05 00:00:00',
        'end_on': '2030-12-31 00:00:00',
    }

    Account.create(account, 999)
Ejemplo n.º 5
0
def _get_default_account():
    default = Account.query(Account.username==DEFAULT_NAME,
                            Account.password==DEFAULT_PW,
                            Account.service==DEFAULT_SERVICE).get()
    if default:
        return default
    else:
        default_key = Account(username=DEFAULT_NAME,
                              password=DEFAULT_PW,
                              service=DEFAULT_SERVICE).put()
        return default_key.get()
Ejemplo n.º 6
0
    def add(self):
        Account.create(name=self._view.name, address=self._view.address,
                       password=self._view.password,
                       imap_host=self._view.imap_host,
                       imap_port=self._view.imap_port,
                       imap_ssl=self._view.imap_ssl,
                       smtp_host=self._view.smtp_host,
                       smtp_port=self._view.smtp_port,
                       smtp_ssl=self._view.smtp_ssl)
        
        self._view.accept()

        if self._main_controller:
            self._main_controller.update_accounts()
 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
Ejemplo n.º 8
0
def create_beta_account():
    error = False
    errors = []
    flash = errors.append

    if len(request.form.get('application')) < 4 or \
       not service.valid_subdomain(request.form.get('application')):
        flash(
            'Account name must be at least 4 characters with alpha '
            'numeric and hyphen characters. It cannot start or end '
            'with a hyphen or have two or more consecutive hyphens.'
        )
        error = True
    if len(request.form.get('username')) < 6 or \
       len(request.form.get('password')) < 6:
        flash('Username and password both must be at least 6 characters')
        error = True
    if not service.valid_email(request.form.get('email')):
        flash('E-mail address is not valid')
        error = True
    if not error:
        plan = db.session.query(Plan).\
            filter(Plan.code_name=='beta open').one()
        user = AccountUser(
            username=request.form.get('username'),
            password=service.make_hash(request.form.get('password')),
            email=request.form.get('email')
        )
        account = Account(
            name=request.form.get('application'),
            users=[user]
        )
        account.inherit_plan(plan)
        db.session.add(account)
        db.session.commit()
        manager_uri = 'http://%s.%s/login/?first_registration=true' % (
            request.form.get('application'), 
            config.DOMAIN_SUFFIX_MANAGER
        )
        mailer.beta_registration(
            request.form.get('application'),
            request.form.get('username'),
            request.form.get('email')
        )
        reply = {'redirect': manager_uri}
    else:
        raise APIError(errors)
    return reply
Ejemplo n.º 9
0
def get(event, context):
    logging.info("received event %s", event)
    body = {
        #"message": "Go Serverless v1.0! Your function executed successfully!",
        # "role" : User.get(User.id == 1).role,
        # "user_name" : User.get(User.id == 1).user_name,
        # "first_name" : User.get(User.id == 1).first_name,
        # "last_name" : User.get(User.id == 1).last_name,
        # "phone_number" : User.get(User.id == 1).phone_number,
        # "email_id" : User.get(User.id == 1).email_id
    }
    if 'pathParameters' in event and 'id' in event['pathParameters']:
        _id = event['pathParameters']['id']
        try:
            account = Account.get(id=_id)
            response = {
                "statusCode": 200,
                "body": json.dumps(model_to_dict(account))
            }
        except pw.DoesNotExist:
            logger.exception(
                "Account detail does not exist for id {}".format(_id))

            body = {
                "message":
                "Account detail does not exist for id {}".format(_id),
            }
            response = {"statusCode": 404, "body": json.dumps(body)}

    return response
Ejemplo n.º 10
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)
Ejemplo n.º 11
0
 def get(self):
     accounts_to_clear = Account.query(
         ndb.AND(Account.valid_until < datetime.now(),
                 Account.cleared == False)
     ).fetch()
     for account in accounts_to_clear:
         account.clear()
Ejemplo n.º 12
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'])
Ejemplo n.º 13
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")
Ejemplo n.º 14
0
def listAccounts(filter):
    if filter == "active":
        accounts = Account.list("active")
    elif filter == "deleted":
        accounts = Account.list("deleted")
    elif filter == "debts":
        accounts = Account.list("debts")
    elif filter == "staff":
        accounts = Account.list("staff")
    else:
        raise ApiError("Wrong filter, must be one of these: active, deleted, debts, staff")

    for account in accounts:
        account.balance = str(account.balance)

    return [acc.serialize() for acc in accounts]
Ejemplo n.º 15
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)
Ejemplo n.º 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
    """
Ejemplo n.º 17
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
Ejemplo n.º 18
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 '上传失败'
Ejemplo n.º 19
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'],
    )
Ejemplo n.º 20
0
    def get(self):
        user = users.get_current_user()
        accounts_query = Account.query(Account.author == user)
        accounts = accounts_query.fetch(10)
        template_values = {
            'accounts': accounts
        }

        template = JINJA_ENVIRONMENT.get_template('templates/accounts.html')
        self.response.write(template.render(template_values))
Ejemplo n.º 21
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
        }
Ejemplo n.º 22
0
 def get(self):
     user = users.get_current_user()
     accounts_query = Account.query(Account.author == user)
     accounts = accounts_query.fetch()
     resp_list = []
     for account in accounts:
         smzdm_handler = Smzdm(account)
         attend_dict = smzdm_handler.attendance()
         resp_list.append(attend_dict)
     self.response.write(resp_list)
Ejemplo n.º 23
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
Ejemplo n.º 24
0
 def get(self):
     self.response.write(open('header.html').read())
     urlsafe = self.request.get('urlsafe')
     result = Account.query()
     for item in result:
         if item.key.urlsafe() == urlsafe:
             self.response.write(str(item.key.id()) + "<br/>")
             self.response.write(str(item.key.kind()) + "<br/>")
             self.response.write(str(item.key.urlsafe()) + "<br/>")
             self.response.write(str(item.key.delete()) + "<br/>")
Ejemplo n.º 25
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
Ejemplo n.º 26
0
    def new_customer(cls, email, password, creator_id, detailed_info=None, comment="New customer",
                     withdraw_period=None, make_prod=False, customer_type=None, promo_code=None, locale=None):
        from model import Tariff, Account, CustomerHistory

        customer = cls()
        customer.email = email
        customer.password = cls.password_hashing(password) if password else ""
        customer.deleted = None
        customer.created = utcnow().datetime
        customer.email_confirmed = False
        customer.blocked = False
        customer.customer_mode = cls.CUSTOMER_PRODUCTION_MODE if make_prod else cls.CUSTOMER_TEST_MODE
        customer.customer_type = customer_type if customer_type else cls.CUSTOMER_TYPE_PRIVATE_PERSON
        customer.withdraw_period = withdraw_period or conf.customer.default_withdraw_period
        customer.auto_withdraw_enabled = conf.payments.auto_withdraw_enable
        customer.auto_withdraw_balance_limit = conf.payments.auto_withdraw_balance_limit
        customer.auto_withdraw_amount = conf.payments.auto_withdraw_amount
        customer.locale = locale or conf.customer.default_locale
        customer.os_dashboard = conf.customer.default_openstack_dashboard

        default_tariff = Tariff.get_default().first()
        if not default_tariff:
            default_tariff = Tariff.query.filter_by(mutable=False).first() or Tariff.query.filter_by().first()
            if not default_tariff:
                raise errors.TariffNotFound()
        customer.tariff_id = default_tariff.tariff_id
        customer.balance_limit = conf.customer.balance_limits.get(default_tariff.currency,
                                                                  conf.customer.balance_limits.default)
        db.session.add(customer)
        db.session.flush()

        customer.init_subscriptions()
        template = 'customer' if make_prod else 'test_customer'
        customer.quota_init(template)
        customer.accounts.append(Account.create(default_tariff.currency, customer, creator_id, comment))

        if promo_code is not None:
            PromoCode.new_code(promo_code, customer.customer_id)

        CustomerHistory.new_customer(customer, creator_id, comment)
        if detailed_info:
            customer.create_info(customer.customer_type, detailed_info)
        auto_report_task = ScheduledTask(cls.AUTO_REPORT_TASK, customer.customer_id, customer.withdraw_period)
        db.session.add(auto_report_task)

        logbook.info("New customer created: {}", customer)
        if not make_prod:
            currency = customer.tariff.currency.upper()
            initial_balance = conf.customer.test_customer.balance.get(currency)
            logbook.debug("Initial balance for customer {}: {} {}", customer, initial_balance, currency)
            if initial_balance:
                customer.modify_balance(Decimal(initial_balance), currency, None, "Initial test balance")

        return customer
Ejemplo n.º 27
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')
Ejemplo n.º 28
0
def createAccount():
    form = forms.AccountCreationForm()
    if form.validate_on_submit():
        account = Account.create(form.firstname.data, form.lastname.data, form.promo.data, form.number.data)

        if form.balance.data is not None and form.balance.data != 0:
            Transaction.add(account.id, form.balance.data)

        return account.serialize()
    else:
        raise MissingFieldsError(form.errors.keys())
Ejemplo n.º 29
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)
Ejemplo n.º 30
0
    def get_or_create_account(self, currency, user_id):
        from model import Account

        account = self.get_account(currency)
        if account:
            return account

        account = Account.create(currency, self, user_id)
        self.accounts.append(account)
        db.session.flush()
        return account
Ejemplo n.º 31
0
def test_update():
    """
    """
    account = {
        'account_name': 'update',
        'start_on': '2021-05-03 00:00:00',
        'end_on': '2031-12-31 00:00:00',
    }
    Account.create(account, 999)
    account_created1 = Account.search('update', 999)
    print(account_created1)

    search_cond = {
        'account_name': 'update',
        'start_on': '2021-05-03 00:00:00',
        'end_on': '2031-12-31 00:00:00',
    }
    account_created = Account.search('update', 999)[0].toDict()
    assert account_created['account_name'] == 'update'
    assert account_created['start_on'] == '2021-05-03 00:00:00'
    assert account_created['end_on'] == '2031-12-31 00:00:00'

    account = {'id': account_updated['id'], 'end_ion': '2035-12-31 12:00:00'}
    assert Account.update(account, 999) == True
    search_cond = {'account_name': 'update', 'end_on': '2035-12-31 12:00:00'}
    account_updated = Account.search(search_cond, 999)[0].toDict()
    assert account_updated['account_name'] == 'update'
    assert account_updated['start_on'] == '2021-05-03 00:00:00'
    assert account_updated['end_on'] == '2035-12-31 00:00:00'
Ejemplo n.º 32
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")
Ejemplo n.º 33
0
 def post(self):
     email = self.request.get("email")
     self.set_session("email", email)
     
     uid = self.get_session("uid")
     user = Account.get_or_insert(key_name=uid)
     user.uid = uid
     user.email = email
     user.title = self.get_session("name")
     user.access_key = self.get_session("access_key")
     user.access_secret = self.get_session("access_secret")
     user.put()
     
     self.add_fetch_task(user.uid, user.email, user.title, user.access_key, user.access_secret, True, 1, 35, 0, 0)
     self.redirect("/done/")
Ejemplo n.º 34
0
def before_request():

    # check that the wsgi's environ set to an app subdomain
    if not service.is_app_domain():
        abort(404)

    # check for app in our system
    host = request.url.split('/')[2]
    domain = host.split(':')[0]
    account_name = domain.split('.')[0]
    account = Account.get_by_name(account_name)
    if account is None:
        return app.response_account_not_found()

    # if this app served as a custom domain, check that the app is allowed
    if request.environ['MUH_IS_CUSTOM_DOMAIN'] and \
       not account.custom_domain:
        return app.response_account_not_found()
    
    # check if the account has a canonical domain setup
    if account.custom_domain and \
       account.canonical_domain and \
       account.canonical_domain != request.environ['MUH_HTTP_HOST']:
        new_url = request.url.replace(
            request.environ['HTTP_HOST'],
            account.canonical_domain,
            1
        )
        return redirect(new_url, code=301)


    # check the app is not over the current month's transfer limit
    if account.transfer: # 0 is unlimited
        rds_key = 'xferm:{account_id}'.format(account_id=account.id)
        rds_field = year_month()
        xfer = rds.hget(rds_key, rds_field)
        if xfer is not None and int(xfer) > account.transfer:
            return app.response_account_transfer_exceeded()

    # new registrations might not have any app uploaded
    if account.application is None:
        return app.response_account_missing()

    # OK, you can go now
    g.account = account
    s = sha1()
    s.update(str(g.account.application.id))
    g.application_hash = s.hexdigest()
Ejemplo n.º 35
0
def test_getById():
    """
    """
    user_id = 1
    id = 1
    accounts = Account.getById(id, user_id)
    assert len(accounts) == 1
    pprint.pprint(accounts)
    account = accounts[0].toDict()
    assert account['id'] == 1
    assert account['account_name'] == 'ksato'
    assert account['start_on'] == '2021-04-25 15:08:02'
    assert account['end_on'] == '2030-12-31 00:00:00'
    assert account['created_by'] == 1
    #    assert account['created_at'] == ''
    assert account['updated_by'] == 1
Ejemplo n.º 36
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
Ejemplo n.º 37
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
Ejemplo n.º 38
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
Ejemplo n.º 39
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())
Ejemplo n.º 40
0
 def get(self):
     self.response.write(open('header.html').read())
     an = self.request.get("tfAcNo")
     # query from Googe NDB
     result = Account.query(
         ndb.OR(Account.AcNo == int(an), Account.AcBalance >= 40000))
     if result:
         self.response.write("<table border='1'>")
         for act in result:
             self.response.write("<tr>")
             self.response.write("<td>" + str(act.AcNo) + "</td>")
             self.response.write("<td>" + act.AcHName + "</td>")
             self.response.write("<td>" + str(act.AcBalance) + "</td>")
             self.response.write("<td>" + str(act.AcMobNo) + "</td>")
             self.response.write("<td>" + act.City + "</td>")
             self.response.write("</tr>")
         self.response.write("</table>")
     else:
         self.response.write("No Data Found")
Ejemplo n.º 41
0
 def _store_message(self, mail_message):
     receiver_name, receiver_address = parseaddr(mail_message.to)
     account = Account.get_by_email(receiver_address)
     if not account or account.valid_until < datetime.now():
         return
     sender_name, sender_address = parseaddr(mail_message.sender)
     body = mail_message.body.decode() if hasattr(mail_message, 'body') else None
     html = clean_html(mail_message.html.decode()) if hasattr(mail_message, 'html') else None
     db_message = Message(
         parent=account.key,
         sender_name=sender_name,
         sender_address=sender_address,
         receiver_name=receiver_name,
         receiver_address=receiver_address,
         reply_to=getattr(mail_message, 'reply_to', None),
         cc=getattr(mail_message, 'cc', None),
         bcc=getattr(mail_message, 'bcc', None),
         subject=getattr(mail_message, 'subject', None),
         date=datetime.now(),
         body=body,
         html=html
     )
     db_message.put()
     self._store_attachments(mail_message, db_message)
Ejemplo n.º 42
0
def getAccountByNumber(number):
    number = convert(int, number)
    return Account.getByNumber(number).serialize()
Ejemplo n.º 43
0
 def create_account(self):
     account = Account.create()
     self.session['account_id'] = account.key.id()
     return account
Ejemplo n.º 44
0
 def get_account(self):
     account_id = self.session.get('account_id')
     if account_id:
         account = Account.get_by_id(account_id)
         if account and account.is_valid:
             return account
Ejemplo n.º 45
0
def searchAccount(firstname):
    return [acc.serialize() for acc in Account.search(firstname)]
Ejemplo n.º 46
0
 def get_current_user(self):
     data = self.get(ME_URI, params={"alt":"json"}).read()
     account = Account()
     account.from_json(data)
     self.user = { "name":account.title, "uid":account.uid }
     return self.user
Ejemplo n.º 47
0
def getAccount(account_id):
    account_id = convert(int, account_id)
    return Account.get(account_id).serialize()