def dataset(setup_database): session = setup_database # Creates user john = User(username="******") mary = User(username="******") session.add(john) session.add(mary) session.commit() # Creates account john_account = Account(balance=10.0) mary_account = Account(balance=5.0) joint_account = Account(balance=20.0) john.accounts.append(john_account) mary.accounts.append(mary_account) john.accounts.append(joint_account) mary.accounts.append(joint_account) session.add(john_account) session.add(mary_account) session.add(joint_account) session.commit() yield session
def test_basic_addition(self): """ Test roles on Django model classes. """ src = Account(balance=1000) dst = Account(balance=0) src.save() dst.save() accounts = Account.objects.all() assert len(accounts) == 2 assert accounts[0].balance == 1000, accounts[0].balance assert accounts[1].balance == 0, accounts[1].balance ctx = TransferMoney(src, dst) ctx.transfer_money(amount=100) print src, src.balance assert src.balance == 900 print dst, dst.balance assert dst.balance == 100 accounts = Account.objects.all() assert accounts[0].balance == 900, accounts[0].balance assert accounts[1].balance == 100, accounts[1].balance
def process(self): try: pre = Account().objects.order_by('-created').filter( subject=self.text[1]).first() except: self.pre = None else: self.pre = pre ac = Account().objects.create(place=self.text[0], subject=self.text[1], cost=self.text[2], created=datetime.datetime.now()) return ac
def add(): init_db() c1 = Customer('Anna', 'Smith', '*****@*****.**', datetime.datetime(1990, 5, 1)) c2 = Customer('John', 'Brown', '*****@*****.**', datetime.datetime(1992, 5, 1)) print(c1) a1 = Account(c1) a2 = Account(c2) db = DBSession().get() db.add(c1) db.add(c2) db.add(a1) db.add(a2) db.commit()
def save(self, role=1): user = Account(**self.data) user.role = role user.save() stuusr = Student(stuid=user.username, grade="20" + user.username[0:2]) stuusr.save() return user
def account_sync(request): """ API end point to sync the account that signed in via oauth. This API is called by [mankey] service. Logic: If account exists in database, fetch account + role and return if account does not exist, save the email into database as a visitor. sample request.data: { "name": "Tayler", "email": "*****@*****.**", "token":"AABBCC", } """ account = request.data email = account.get('email') name = account.get('name') log.debug( ' account_sync get request.data, receive account={0}, type={1}'.format( account, type(account))) user = {} # check account by email if account_exists(email): user = Account.objects.get(email=email) else: user = Account(name=name, email=email, status='v') user.save() serializer = AccountSerializer(user) return Response(serializer.data)
def register(): logger = logging.getLogger('Register') form =FormRegister() if request.method == 'POST': if form.validate_on_submit(): date_time = datetime.datetime.now() # user & email collision username = Account.query.filter(Account.username == form.username.data).first() email = Account.query.filter(Account.email == form.email.data).first() if username: flash('{} has been used.'.format(form.username.data)) if email: flash('The email "{}" has been used'.format(form.email.data)) if not username and not email: logger.debug('{} {} {}'.format(form.username.data, form.password.data, form.email.data)) account = Account(username=form.username.data , nickname=form.nickname.data , password=generate_password_hash(form.password.data) , email=form.email.data , permLevel=2 , signUpTime=date_time , lastLoginTime=date_time , icon=False) db.session.add(account) db.session.commit() return redirect(url_for('login')) return render_template('register.html', form=form)
def cw_register(request): username = request.POST.get('username', '') password = request.POST.get('password', '') email = request.POST.get('email', '') first_name = request.POST.get('first_name', '') last_name = request.POST.get('last_name', '') zip_code = request.POST.get('zip', '') if User.objects.filter(email=email).exists(): return HttpResponseBadRequest( reason='An account exists for this email address.') if User.objects.filter(username=username).exists(): return HttpResponseBadRequest(reason='Sorry, this username is taken.') try: User.objects.create_user(username, email, password) user = authenticate(username=username, password=password) user.is_active = False user.save() except Exception as e: return HttpResponseServerError(reason=str(e)) try: account = Account(user=user, email=email, first_name=first_name, last_name=last_name, zip_code=zip_code) account.save() login(request, user) return HttpResponse() except Exception as e: user.delete() return HttpResponseServerError(reason=str(e))
def get_alluser(db, arg): listObj = { "total": 0, "users": [], } start = arg["paras"].get("start") or 0 limit = arg["paras"].get("limit") or 100 cond = "WHERE 1=1 " ret = db.select(TB_ACCOUNT, cond=cond, limit=int(limit), offset=int(start)) if ret == -1: ERROR("get user list error") return (DB_ERR, None) for dur in db.cur: obj = dbmysql.row_to_dict(TB_ACCOUNT, dur) user = Account(db, dbObj=obj) user.loadFromObj() listObj["users"].append(user.toObj()) listObj["total"] = getAccountCount(db) return (OCT_SUCCESS, listObj)
def account_create(): first_name = request.get_json()['first_name'] last_name = request.get_json()['last_name'] init_balance = request.get_json()['balance'] body = {} error = False if first_name is None or init_balance is None: error = True abort(400) else: try: new_account = Account(first_name=first_name, last_name=last_name, balance=init_balance) db.session.add(new_account) db.session.commit() created_user_id = new_account.id body['account_id'] = new_account.id body['first_name'] = new_account.first_name body['last_name'] = new_account.last_name body['balance'] = new_account.balance except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() if error: abort(400) else: return jsonify(body)
def registration(): usernames = [x.username for x in User.query.all()] emails = [y.email for y in User.query.all()] rFirstName = request.form["rfirstname"] rLastName = request.form["rlastname"] email = request.form["email"] amount = request.form["amount"] rUsername = request.form["rusername"] rPassword = request.form["rpassword"] cPassword = request.form["cpassword"] if rUsername in usernames or email in emails: # username and email should be blank because one of them is already being used return render_template("registration.html", rpassword=rPassword, cpassword=cPassword, rfirstname=rFirstName, rlastname=rLastName, amount=amount) '''TODO: I want to be able to return to the registration page with a notifcation about the username/email already being used. How can I do this?''' elif rFirstName == "" or rLastName == "" or email == "" or amount == "" or rUsername == "" or rPassword == "" or cPassword == "": return render_template("registration.html", rusername=rUsername, rpassword=rPassword, cpassword=cPassword, alert1=True) else: if rPassword == cPassword: u1 = User(username=rUsername, password_hash=rPassword, email=email, first_name=rFirstName, last_name=rLastName) a1 = Account(balance=amount) db.session.add(u1) db.session.add(a1) u1.account = a1 db.session.commit() print("Added user to database") else: # don't reload cPassword because the passwords did not match return render_template("registration.html", rusername=rUsername, rpassword=rPassword, rfirstname=rFirstName, rlastname=rLastName, email=email, amount=amount, alert2=True) '''TODO: Add notification saying the passwords do not match''' return render_template("homepage.html", success=True)
def create_account(): form = CreateAccountForm() if request.method == 'POST': ws_cust_id = request.form.get('ws_cust_id') ws_acct_type = request.form.get('ws_acct_type') ws_amt = request.form.get('ws_amt') customer = Customer.query.filter_by(ws_cust_id=ws_cust_id).first() if customer: account = Account(ws_cust_id=ws_cust_id, ws_acct_type=ws_acct_type) account.ws_acct_balance = ws_amt account.ws_acct_crdate = datetime.now() account.ws_acct_lasttrdate = datetime.now() #ws_acct_duration db.session.add(account) db.session.commit() # to update status temp_acc = Account.query.order_by(Account.ws_acc_id.desc()).first() if temp_acc: update_status_account(temp_acc.ws_acc_id, 'created') flash("Account creation initiated !", "success") return render_template("customer.html", title="Account created", create_account=True) else: flash("Customer Id does not exist !", "danger") return render_template("create_account.html", form=form, create_account=True, title='Create Account')
def updateTNAAccountTable(file): with codecs.open(MEDIA_ROOT + '/' + str(file), "r", encoding="ISO-8859-1") as f: dateAmount_regex = r"(?P<day>\d{2}).(?P<month>\d{2}).\s*(\d+)\s*__________ \s*(?P<amount>(\d*,\d+)[-+])" beneficiary_regrex = r"(?P<beneficiary>(\w+)(.*?))\s*/[A-Z] " ref_num_regrex = r"(\w+)\s*(?P<ref_num>\d{20}(?!\d))" year_regrex = r"Entry date\s*(\d+).(\d+).(?P<year>\d{2})" year = ''; month = ''; day = ''; amount = ''; ref_num = ''; beneficiary = '' for line in f: if re.search(year_regrex, line): year = '20' + str(re.search(year_regrex, line).group('year')) if re.search(dateAmount_regex, line): month = str(re.search(dateAmount_regex, line).group("month")) day = str(re.search(dateAmount_regex, line).group("day")) amount = str(re.search(dateAmount_regex, line).group("amount")) if re.search(beneficiary_regrex, line): beneficiary = str(re.search(beneficiary_regrex, line).group('beneficiary')) if re.search(ref_num_regrex, line): ref_num = str(re.search(ref_num_regrex, line).group('ref_num'))[-4::] if year and month and day and amount and beneficiary: try: acc_exist = Account.objects.filter(year=year, month=month, day=day, amount=amount, beneficiary=beneficiary) except: acc_exist = [] if len(acc_exist) == 0: Account(year=year, month=month, day=day, amount=amount, beneficiary=beneficiary, ref_num=ref_num).save() month = ''; day = ''; amount = ''; ref_num = ''; beneficiary = ''
def accounts(): if request.method == 'GET': all_accounts = Account.query.all() for account in all_accounts: account.client1 = Client.query.get(account.client1) if account.client2 is not None: account.client2 = Client.query.get(account.client2) return render_template('account_list.html', accounts=all_accounts) else: # TODO: Complete create account process acc_no = request.form['acc_no'] acc_name = request.form['acc_name'] acc_type = AccountType.SAVINGS if request.form['acc_type'] == AccountType.SAVINGS.value \ else AccountType.CURRENT client1_email = request.form['client1'] client2_email = request.form['client2'] client1 = Client.query.filter_by(email=client1_email).first() client2 = None if len(client2_email) > 0: client2 = Client.query.filter_by(email=client2_email).first() client2 = client2.id if client2 is not None else None if client1 is not None: client1 = client1.id new_account = Account(acc_no, acc_name, acc_type, client1, client2) db.session.add(new_account) db.session.commit() db.session.refresh(new_account) return render_template('account_edit.html', account=new_account) else: return Response('Error in form!')
def engine(): engine = local_engine() engine.execute("DROP TABLE IF EXISTS transactions;") engine.execute("DROP TABLE IF EXISTS categories;") engine.execute("DROP TABLE IF EXISTS transaction_types;") engine.execute("DROP TABLE IF EXISTS accounts;") Base.metadata.create_all(engine) with session_scope(engine) as session: # See Transaction Types session.add_all( [TransactionType(name="Debit"), TransactionType(name="Credit")]) # Seed Categories session.add_all([ Category(name="Uncategorized"), Category(name="Travel"), Category(name="Going Out"), Category(name="Utilities"), Category(name="Rent"), Category(name="Paycheck"), ]) # Seed Account session.add(Account(name="Chase Checking 7526")) yield engine
def post(self): json_req = self.jsonifyRequestBody() data = json_req print data print "Entering account handler!" service_ids = data["service_ids"] print service_ids for id_ in service_ids.keys(): # Checks if account exists at all.. # Means only there cannot be two accounts with the same service_id accountExists = self.validateAccount(id_) if accountExists: print "Account exists" continue print "Creating account for id " + id_ acc = Account() acc.email = data["email"] print "gotten email" acc.serviceID = id_ acc.alias = service_ids[id_] print "got service id" acc.config = default_config print "set default configs" acc.key = ndb.Key(Account, id_) print "creating key" acc.put() print "Account sucessfully created" logging.info("Account has been put into the datastore") #Better flesh out fail state. self.writeSucessfulResponse("Account sucessfully created")
def create_account(): form = AccountForm() completion_msg = "" if form.validate_on_submit(): if form.save.data: new_account = Account(name=form.name.data, pnumber=form.pnumber.data, email=form.email.data, street=form.street.data, city=form.city.data, state=form.state.data, postal=form.postal.data, country=form.country.data, notes=form.notes.data) db.session.add(new_account) try: db.session.commit() except: completion_msg = "Failed to create account. Please try again." if completion_msg == "": completion_msg = "Success! The account has been saved." return redirect(url_for('view_account')) else: completion_msg = "Failed to create account. Please try again." return render_template("create_account.html", form=form, completion_msg=completion_msg)
def get_or_init_account(user): account = Account.all().filter('user =', user).get() if account is None: account = Account(user=user) account.put() return account
def process_request(self, request): account = Account() subdomain = request.GET.get('_subdomain') if subdomain is None: m = re.match('(?P<subdomain>\w+)\.(?P<domain>.*\..*)', request.META['SERVER_NAME']) if m is not None: subdomain = m.group('subdomain') url = request.META['SERVER_NAME'] + ( ':' + request.META['SERVER_PORT'] if (request.META['SERVER_PORT'] != '80') else '') if subdomain is None: return HttpResponseRedirect('http://www.' + url) if subdomain != 'www': try: account = Account.objects.get(subdomain__exact=subdomain) except: return HttpResponseRedirect('http://' + url) request.subdomain = subdomain request.account = account return None
def register(): errors = [] if request.method == 'GET': if current_user.get_id(): return redirect(url_for('home')) else: return render_template('register.html') if db.session.query(Account).filter_by(account_name=request.form['account_name']).count() > 1: errors.append('Account name is already taken.') if not request.form['account_name']: errors.append('Please enter a account name.') if not request.form['password']: errors.append('Please enter a password.') if errors: return jsonify({"status": "error", 'errors': errors}), 400 account = Account( account_name=request.form['account_name'], active_user=True, ) account.set_password(request.form['password']) try: db.session.add(account) db.session.commit() except Exception: errors.append("Name is already taken") if errors: return jsonify({"status": "error", 'errors': errors}), 400 login_user(account, remember=True) success_message = "Your account has been created!" return jsonify({"status": "success", "value": success_message}), 200
def add_user(db, arg): paras = arg["paras"] account = paras["account"] user = getAccount(db, userName=account) if (user): WARNING("user %s already exist" % account) return USER_ALREADY_EXIST user = Account(db) user.name = account user.password = b64_decode(paras["password"]) if (not user.name or not user.password): ERROR("not username or password specified") return NOT_ENOUGH_PARAS user.email = paras["email"] user.phone = paras["phoneNumber"] ret = user.add() return ret
def test_check_auth_redis_miss(self): db_handler = self.auth_handler.db_handler db_conn = db_handler.getEngine().connect() db_txn = db_conn.begin() try: db_session = Session(bind=db_conn) try: account = Account(auth_id='some_auth_id', username='******') db_session.add(account) db_session.flush() phonenumber = PhoneNumber(number='9740171794', account_id=account.id) db_session.add(phonenumber) db_session.commit() self.auth_handler.redis_client.hget.return_value = None self.auth_handler.redis_client.pipeline.return_value = redis_pipeline_mock = MagicMock( ) status, phonenums = self.auth_handler._check_auth( 'some_user', 'some_auth_id', db_session) self.assertTrue(status) self.assertEquals(set(['9740171794']), phonenums) self.assertEquals(redis_pipeline_mock.hset.call_count, 1) redis_pipeline_mock.hset.assert_called_with( self.auth_handler._REDIS_AUTH_HASH, 'some_user', 'some_auth_id') self.assertEquals(redis_pipeline_mock.sadd.call_count, 1) redis_pipeline_mock.sadd.assert_called_with( 'some_user', '9740171794') self.assertEquals(redis_pipeline_mock.execute.call_count, 1) finally: db_session.close() finally: db_txn.rollback() db_conn.close()
def register(): form = FormRegister() if form.validate_on_submit(): print("in") # catch time date_time = datetime.datetime.now() # user & email collision username = Account.query.filter( Account.username == form.username.data).first() email = Account.query.filter(Account.email == form.email.data).first() if username or email: return 'Username or Email collision' elif form.password.data != form.confirm.data: return 'two password is different' else: account = Account(uid=0, username=form.username.data, nickname=form.nickname.data, password=generate_password_hash( form.password.data), email=form.email.data, permLevel=False, signUpTime=date_time, lastLoginTime=date_time, icon=False) db.session.add(account) db.session.commit() flash('Success Thank You') return redirect(url_for('login')) return render_template('register.html', form=form)
def post(self): username = self.request.get('username') password = self.request.get('password') verify_password = self.request.get('verify') email = self.request.get('email') error = "" if username and password and verify_password: if password != verify_password: error = "Verify password is not matched" elif self.is_username_exist(username): error = "Username has already existed" else: hash_pw = encrypt.make_pw_hash(username, password) account = Account(username=username, password=hash_pw, email=email) account.put() account_id = account.key().id() cookie_account_id = encrypt.make_secure_cookie(account_id) # TODO: What is Path=/? self.response.headers.add_header( "Set-Cookie", "user_id={}; Path=/".format(cookie_account_id)) self.response.headers.add_header( "Set-Cookie", "username={}; Path=/".format(username)) self.redirect("/welcome") else: error = "Username, password and verify password is required!" self.render("sign_up.html", error=error, username=username, email=email)
def register_page(request): if request.method == 'POST': form = FormularzRejestracji(request.POST) if form.is_valid(): user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) user.save() acc = Account() acc.owner = user.username acc.balance = 0 acc.save() if form.cleaned_data['log_on']: user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) login(request, user) return HttpResponseRedirect("/blog/") else: template = get_template("registration/register_success.html") variables = RequestContext( request, {'username': form.cleaned_data['username']}) output = template.render(variables) return HttpResponse(output) else: form = FormularzRejestracji() template = get_template("registration/register.html") variables = RequestContext(request, {'form': form}) output = template.render(variables) return HttpResponse(output)
def register(): form = AdminForm( request.form ) #we are using data from the htnl template directlt and not the form username = request.form.get( 'username') #form.username.data, alternatively use the form data password = request.form.get('password') #form.password.data password1 = request.form.get('password1') #form.password1.data msg = '' if request.method == 'POST': account = Account() #Query the database and retrieve an account with similar data and if it exists, display errors qry = db.session.query(Account).filter(id == id).filter( Account.username == username).filter(Account.password == password) existing_account = qry.first() #print(existing_account.username) if existing_account: msg = 'Account already exists' # elif not re.match(r'[A-Za-z0-9]+', username):#Validate username to use only numbers and letters # msg = 'User name must contain only letters and numbers'#Dont forget to check how to validate frontend fields with re.match elif password != password1: #authenticate password validation msg = 'Passwords didnt match' else: save_user(account, new=True) msg = 'Successfully registered' elif request.method == 'POST': msg = 'Please Fill in the form' return render_template( 'register2.html', msg=msg) #Incase of form errors use the form again to register
def init_add_account(): global session, SERVER_MODE, engine logging.info('{}: Adding bot account'.format( sys._getframe().f_code.co_name)) BOT_ACCOUNTS = [ Account( account_id=823447412, # Insert your own Telegram API ID here account_api_id=949947, # Insert your own Telegram API ID here account_api_hash= '47e4ae290a26be30a688100e9e78093b', # Insert your own Telegram API Hash here account_is_bot=False, account_is_verified=False, account_is_restricted=False, account_first_name='转身Leave', account_last_name='黄', account_user_name='leave_one_e', account_phone= '+8618423502420', # Enter your burner phone number here account_is_enabled=True, account_tlogin=datetime.now(), account_tcreate=datetime.now(), account_tmodified=datetime.now()), ] for account in BOT_ACCOUNTS: session.add(account) session.commit()
def init_add_account(): global session, SERVER_MODE, engine logging.info(f'{sys._getframe().f_code.co_name}: Adding bot account') BOT_ACCOUNTS = [ Account( account_id=os.environ['TELEGRAM_ACCOUNT_ID'], account_api_id=os.environ['TELEGRAM_API_APP_ID'], account_api_hash=os.environ['TELEGRAM_API_HASH'], account_is_bot=False, account_is_verified=False, account_is_restricted=False, account_first_name=os.environ['TELEGRAM_ACCOUNT_FIRST_NAME'], account_last_name=os.environ['TELEGRAM_ACCOUNT_LAST_NAME'], account_user_name=os.environ['TELEGRAM_ACCOUNT_USER_NAME'], account_phone=os.environ[ 'TELEGRAM_ACCOUNT_PHONE_NUMBER'], # Enter your burner phone number here account_is_enabled=True, account_tlogin=datetime.now(), account_tcreate=datetime.now(), account_tmodified=datetime.now()), ] for account in BOT_ACCOUNTS: session.add(account) session.commit()
def init_add_account(): global session, SERVER_MODE, engine logging.info('{}: Adding bot account'.format( sys._getframe().f_code.co_name)) BOT_ACCOUNTS = [ Account( account_id=1234567, # Insert your own Telegram API ID here account_api_id=1234567, # Insert your own Telegram API ID here account_api_hash= '21b277e0daa5911b0f2616b8b669533c', # Insert your own Telegram API Hash here account_is_bot=False, account_is_verified=False, account_is_restricted=False, account_first_name='Darrin', account_last_name='OBrien', account_user_name='informer', account_phone='+14151234567', # Enter your burner phone number here account_is_enabled=True, account_tlogin=datetime.now(), account_tcreate=datetime.now(), account_tmodified=datetime.now()), ] for account in BOT_ACCOUNTS: session.add(account) session.commit()
def run(self): try: urls_article = [ 'https://mp.weixin.qq.com/s?src=11×tamp=1541559601&ver=1229&signature=ixTsG-RvK8H58t6D-CpW6olWI8hA52Wz-FRb12ZcrNG-lxR20YutoyLYUr-RB3w8WHjE1petjDcbbxZVxTChvPWM27qszWu0Z3zonjx8SEQB5mmgm1O9Eu*5qsFhnBCH&new=1' ] entity = None backpack_list = [] ftp_list = [] ftp_info = None for page_count, url in enumerate(urls_article): # if page_count < 15: # continue html = requests.get(url) # 确定account信息 name = pq(html.text)('#js_name').text() account_name = pq( html.text)('.profile_meta_value').eq(0).text() log('---{}---{}---'.format(name, account_name)) account = Account() account.name = name account.account = account_name account.get_account_id() article = Article() try: article.create(url, account) except RuntimeError as run_error: log('找不到浏览器 {}'.format(run_error)) log('第{}条 文章标题: {}'.format(page_count, article.title)) log("当前文章url: {}".format(url)) entity = JsonEntity(article, account) log('当前文章ID: {}'.format(entity.id)) # if entity.id in ids: # log('当前文章已存在,跳过') # continue backpack = Backpack() backpack.create(entity) backpack_list.append(backpack.create_backpack()) # self.save_to_mysql(entity) self.save_to_mongo(entity.to_dict()) # ftp包 ftp_info = Ftp(entity) name_xml = ftp_info.hash_md5(ftp_info.url) log('当前文章xml: {}'.format(name_xml)) self.create_xml(ftp_info.ftp_dict(), name_xml) ftp_list.append(name_xml) # if page_count >= 3: # break log("发包") # todo 发包超时,修改MTU if ftp_info is not None: entity.uploads_ftp(ftp_info, ftp_list) if entity: # entity.uploads(backpack_list) entity.uploads_datacenter_relay(backpack_list) entity.uploads_datacenter_unity(backpack_list) log("发包完成") except Exception as e: log("解析公众号错误 {}".format(e)) if 'chrome not reachable' in str(e): raise RuntimeError('chrome not reachable')