def registrace_idCard(): form = IDFormular() if form.validate_on_submit(): try: if not form.soubor.data.filename.rsplit( '.', 1)[1].lower() in ['jpg', 'png']: raise Exception file_name = secure_filename(form.soubor.data.filename) session['idPath'] = os.path.join(app.config["UPLOAD_FOLDER"], file_name) form.soubor.data.save(session['idPath']) response = UploadImageRandom(session['idPath']) session['cloudinaryId'] = response['public_id'] except Exception as error: flash( "Nepodařilo se nahrát foto, zkontrolujte prosím zda jde o soubor s obrázkem jpg/png a zkuste znovu, v případě přetrvávajícíh potíží kontaktujte administrátora.", FlashStyle.Danger) return render_template("/registrace_idCard.html", form=form) # flash("Foto nahráno, jsme u posledního kroku registrace :-) ", FlashStyle.Success) return redirect(url_for("login_bp.comment")) return render_template("/registrace_idCard.html", form=form)
def delete(self): if request.method == 'GET': id_list = request.params.get('id') id_list = id_list.split(',') id_list = [int(e) for e in id_list if e] else: id_list = request.forms.getall('id') query = self.model.select().where(self.pk << id_list) if request.method == 'GET': collected = {} if self.delete_collect_objects: for obj in query: collected[obj.get_id()] = self.collect_objects(obj) elif request.method == 'POST': count = query.count() for obj in query: obj.delete_instance(recursive=self.delete_recursive) flash('Successfully deleted %s %ss' % (count, self.get_display_name()), 'success') return redirect(url_for(self.get_url_name('index'))) return render_template(self.templates['delete'], **dict( model_admin=self, query=query, collected=collected, **self.get_extra_context() ))
def POST(self, name): session = web.ses cookie = session.get('gso', '') gso = get_gso(cookie=cookie) password = gso.get_password(name) myedit_form = edit_form(password) if not myedit_form.validates(): return self.render.new(web.ses.username, myedit_form()) else: session = web.ses values = web.input() args = {} args['account'] = values['account'] password = values['cpassword'] args['description'] = values['description'] args['type'] = values['type'] args['expiration'] = int(values['expiration']) cookie = session.get('gso', '') try: gso = get_gso(cookie=cookie) gso.del_password(name) gso.set_raw_password(name, password, args) flash("Contraseña <strong>'%s'</strong> modificada" % str(name)) except: flash("Contraseña '%s' <strong>NO</strong> modificada" % str(name), 'error') raise web.seeother('/')
def comment(): form = TextFormular() if form.validate_on_submit(): dbUser = DBUser.LoadFromSession('dbUserRegistration') dbUser.info = form.comment.data dbUser.id = DBAccess.GetSequencerNextVal('users_id_seq') dbUser.telephone2 = form.telephone.data dbUser.InsertDB() response = RenameImageToPrivate(session['cloudinaryId'], (str(dbUser.id) + 'OP')) imageUrl = response['url'] ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) token = ts.dumps(dbUser.id, salt='email-confirm-key') confirm_url = url_for('login_bp.user_confirmation', token=token, _external=True) SendMail( GetEmail('noreplyMail'), GetEmail('adminMail'), 'Zaregistrován nový uživatel', f'''<html>Nový uživatel zaregistrovan, čeká na schválení. <br> <img src={GetImageUrl(dbUser.id)}>foto</img> <br> <img src={imageUrl}>OP</img> <br> jméno a příjmení: {dbUser.first_name} {dbUser.surname} <br> email: {dbUser.email} <br> telefon: {dbUser.telephone} <br> adresa: {dbUser.street}, {dbUser.town} <br> info: {dbUser.info} <br> telefon na kontaktní osobu (seniora registruje někdo jiný): {dbUser.telephone2} <br> Pro schválení uživatele klikněte na následující link {confirm_url} </html>''' ) SendMail( GetEmail('noreplyMail'), '*****@*****.**', 'Zaregistrován nový uživatel', f'''<html>Nový uživatel zaregistrovan, čeká na schválení. <br> <img src={GetImageUrl(dbUser.id)}>foto</img> <br> <img src={imageUrl}>OP</img> <br> jméno a příjmení: {dbUser.first_name} {dbUser.surname} <br> email: {dbUser.email} <br> telefon: {dbUser.telephone} <br> adresa: {dbUser.street}, {dbUser.town} <br> info: {dbUser.info}, <br> telefon na kontaktní osobu (seniora registruje někdo jiný): {dbUser.telephone2}, <br> Pro schválení uživatele klikněte na následující link {confirm_url} </html>''' ) SendMail( GetEmail('noreplyMail'), '*****@*****.**', 'Zaregistrován nový uživatel', f'<html>Nový uživatel zaregistrovan, čeká na schválení. <br> <img src={GetImageUrl(dbUser.id)}>foto</img> <br> <img src={imageUrl}>OP</img> <br> údaje: {dbUser.__dict__} <br> Pro schválení uživatele klikněte na následující link {confirm_url}' ) flash( f'Registrace uživatele {dbUser.first_name} {dbUser.surname} úspěšně dokončena. Váš profil nyní musíme zkontrolovat. Zabere nám to maximálně 48 hodin. Prosíme, mějte strpení. Ruční ověřování považujeme za nezbytnost kvůli bezpečnosti. O schválení vás budeme informovat emailem.', FlashStyle.Success) SendMail( GetEmail('noreplyMail'), dbUser.email, 'Registrace na Seniore.org', 'Děkujeme za vaši registraci na Seniore.org. Váš profil nyní musíme zkontrolovat. Zabere nám to maximálně 48 hodin. Prosíme, mějte strpení. Ruční ověřování považujeme za nezbytnost kvůli bezpečnosti. O schválení vás budeme informovat emailem. Děkujeme, tým Seniore.org' ) return redirect(url_for("login_bp.login")) return render_template("/registraceComment.html", form=form)
def registration_email(): emailForm = EmailForm() if emailForm.validate_on_submit(): sleep(3) if request.form.getlist('conditionsAccept') != ['1', '2']: flash(f'Je potřeba souhlasit s podmínkami.', FlashStyle.Danger) return render_template("registrace_email.html", form=emailForm) if DBAccess.ExecuteScalar( 'select id from users where trim(email) ilike %s', (emailForm.email.data.strip(), )) is not None: flash( f'Uživatel {emailForm.email.data} je již zaregistrován, zvolte jiný email.', FlashStyle.Danger) emailForm.email.data = None return render_template("registrace_email.html", form=emailForm) else: ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) token = ts.dumps(emailForm.email.data.strip(), salt='email-confirm-key') confirm_url = url_for('login_bp.email_confirmation', token=token, _external=True) email_text = f'Prosím klikněte na následující odkaz pro ověření vašeho emailu a pokračování v registraci.<br>Tento odkaz bude platný následujících 24 hodin.<br>{confirm_url} <br> Pokud odkaz nefunguje, prosíme, je nutné ho zkopírovat a celý vložit do vašeho prohlížeče.' SendMail(GetEmail('noreplyMail'), emailForm.email.data.strip(), 'Seniore.org - ověření emailu', email_text) #flash("Na zadanou adresu byl odeslán email s odkazem na pokračování v registraci.",FlashStyle.Success) emailForm.submit.label.text = "Odeslat ověřovací email znovu" return render_template("registrace_email2.html", form=emailForm) return render_template("registrace_email.html", form=emailForm)
def lost_password(): emailForm = EmailForm() if emailForm.validate_on_submit(): sleep(3) if DBAccess.ExecuteScalar('select id from users where email ilike %s', (emailForm.email.data, )) is None: flash( f'Uživatel {emailForm.email.data} nebyl nalezen, zvolte jiný email.', FlashStyle.Danger) emailForm.email.data = None return render_template("registrace_email.html", form=emailForm) else: ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) token = ts.dumps(emailForm.email.data, salt='email-renew-key') confirm_url = url_for('login_bp.new_password', token=token, _external=True) email_text = f'Prosím klikněte na následující odkaz pro zadání nového hesla.<br>Tento odkaz bude platný následujících 24 hodin.<br>{confirm_url}' SendMail(GetEmail('noreplyMail'), emailForm.email.data, 'Seniore.cz - obnova zapomenutého hesla', email_text) flash( "Na zadanou adresu byl odeslán email s odkazem na obnovu hesla.", FlashStyle.Success) emailForm.submit.label.text = "Odeslat email znovu" return render_template("lost_password.html", form=emailForm) return render_template("lost_password.html", form=emailForm)
def train(self, X, y, batch_size=32, n_epochs=20, shuffle=True): for i in xrange(n_epochs): print 'Epoch {} / {}'.format(i + 1, n_epochs) batch_gen = BatchGen(X, y, batch_size, shuffle=shuffle) for j, (Xb, yb) in enumerate(batch_gen): flash('Batch', j, batch_gen.n_batches) _ = self._feedforward(Xb) self._backprop(yb)
def login_user(self, user): from mole.sessions import get_current_session session = get_current_session() session['logged_in'] = True session['user_pk'] = user.get_id() session.permanent = True # g.user = user flash('You are logged in as %s' % user.username, 'success')
def GET(self): username = session.get('username', '') session.username = '' cookie = session.get('gso', '') gso = get_gso(cookie=cookie) gso.logout() session.gso = '' flash("Usuario desautenticado") raise web.seeother('/index')
def GET(self, name): # TODO preguntar username = session.get("username", "") cookie = session.get("gso", "") gso = get_gso(cookie=cookie) gso.del_password(name) flash("Contraseña '%s' borrada" % str(name)) raise web.seeother("/list")
def logout_user(self, user): from mole.sessions import get_current_session session = get_current_session() if self.clear_session: session.clear() else: session.pop('logged_in', None) # g.user = None flash('You are now logged out', 'success')
def registrace_address(): form = RegistrationFormAddress() if form.validate_on_submit(): dbUser = DBUser.LoadFromSession('dbUserRegistration') dbUser.town = form.town.data dbUser.street = form.street.data # dbUser.street_number = form.street_number.data dbUser.post_code = form.post_code.data kwargs = dbUser.__dict__ address = "{} {} {}".format(kwargs["street"], kwargs["town"], kwargs["post_code"]) # address = "{} {} {} {}".format(kwargs["street"], kwargs["street_number"], kwargs["town"], kwargs["post_code"]) coordinates = GetCoordinates(address) if (coordinates is not None): # dbUser.latitude = coordinates[0] # dbUser.longitude = coordinates[1] dbUser.latitude = round(coordinates[0], 5) dbUser.longitude = round(coordinates[1], 5) x = 1 y = 1 difference = 0.00001 originalLatitude = dbUser.latitude originalLongitue = dbUser.longitude #check if same coordinates already exists while DBAccess.ExecuteScalar( 'select id from users where latitude=%s and longitude=%s', ( dbUser.latitude, dbUser.longitude, )) is not None: #if exists add difference and try again and again.. dbUser.latitude = originalLatitude + x * difference dbUser.longitude = originalLongitue + y * difference if x != -1: x -= 1 elif y != -1: y -= 1 else: x = 1 y = 1 difference += 0.00001 else: flash('Nenalezeny souřadnice pro vaši adresu', FlashStyle.Danger) return render_template("registrace_address.html", form=form) dbUser.SaveToSession('dbUserRegistration') #return redirect(url_for("login_bp.photo")) return redirect(url_for("login_bp.registrace_idCard")) return render_template("registrace_address.html", form=form)
def stop_bot(bot, bcancel_orders=False, status=None, exitcode=0, alert_trader=True): if (bcancel_orders): logging.info("Cancelling current instruction") bot.cancel_instruction() if (status): bot.end(status=status) if (alert_trader): # error on server side if it's in brpop rds.lpush("trader:action", json.dumps({'uid': bot.uid, "type": "stop_bot"})) bot.update_blueprint() utils.flash("bot '{}' is stopping. Status: {}".format(bot.name, bot.status), "info", sync=False) sys.exit(exitcode)
def sluzby_update(): services = DBAccess.ExecuteSQL("select * from services") form = regFormBuilder( services ) # put all services to form, but I need to display it - by for cycle below form.checkBoxes.clear() # not to have duplicates on website form.checkBoxes = [] for index in form.checkBoxIndexes: form.checkBoxes.append( getattr(form, "checkbox%d" % index) ) # displaying checkboxes on # set all existing services with checked button, to be developed # for checkbox in form.checkBoxes: # existing_services = DBAccess.ExecuteScalar( # "select * from users_services where id_users=%s and " # "id_services=%s and id_demand_offer=%s", # (nextId, checkbox.id, form.demandOffer.data), # ) # if service in existing_services: # checkbox.data = True if form.validate_on_submit(): # if validated, save in db nextId = session["id_user"] services_checked = [] for index in form.checkBoxIndexes: checkbox = getattr(form, "checkbox%d" % index) if checkbox.data: existing_combination = DBAccess.ExecuteScalar( "select count(*) from users_services where id_users=%s and " "id_services=%s and id_demand_offer=%s", (nextId, checkbox.id, form.demandOffer.data), ) text = DictionaryDemandOffer.get( form.demandOffer.data, "unknown").lower() if existing_combination == 0: flash( f'Zadaná kombinace {session["user"]}, {text} a {checkbox.label.text} neexistuje.' ) else: DBAccess.ExecuteUpdate( "delete from users_services where id_users = %s and id_services = %s and id_demand_offer= %s", (nextId, checkbox.id, form.demandOffer.data), ) services_checked.append(checkbox.label) kwargs = { "demand_offer": DictionaryDemandOffer.get(form.demandOffer.data, "unknown"), "category": services_checked, } # return redirect(url_for("overview_bp.prehled_all")) return render_template("sluzby_success.html", **kwargs) return render_template("sluzby_update.html", form=form)
def cb_send_order(order_msg): """ sends the order to cb's API, with retries. If unreachable, republish the received message to itself """ auth_client = rw_auth() try: # Send buy/sell order if (order_msg['type'] == "order"): if (order_msg['side'] == "buy"): recv = cb_buy(order_msg) logging.info("Buy order sent. recv = %s" % recv) elif (order_msg['side'] == 'sell'): recv = cb_sell(order_msg) logging.info("Sell order sent. recv = %s" % recv) channel = channels['new_order'] + order_msg['uid'] # Send cancel order: elif (order_msg['type'] == 'cancel_order'): logging.info("Cancel Order '%s'" % order_msg['order_id']) recv = cb_cancel_order(order_msg['order_id']) channel = channels['cancel_order'] + order_msg['uid'] # get order status elif (order_msg['type'] == 'get_order_status'): recv = cb_get_order(order_msg['order_id']) channel = channels['order_status'] + order_msg['order_id'] # Unknown message else: logging.warning("Message type unknown in " + str(recv)) except requests.exceptions.ReadTimeout: order_msg = signmsg(order_msg) logging.error("ReadTimeout ! Re-register message '%s'" % order_msg) utils.flash("ReadTimeout ! Re-register message '%s'" % json.dumps(order_msg), "danger", sync=False) if ("send_retries" in order_msg.keys()): order_msg['send_retries'] += 1 else: order_msg['send_retries'] = 1 rds.lpush(channels['in'], json.dumps(order_msg)) return recv = signmsg(recv) # if order is refused: if ("message" in recv.keys()): recv["type"] = "refused" rds.lpush(channels['error'], json.dumps(recv)) utils.flash("Order refused ; '%s'" % json.dumps(recv), "danger", sync=False) logging.error("Order refused ; '%s'" % json.dumps(recv)) if 'id' in recv.keys(): # in some case cb api names 'id' the 'order_id' recv['order_id'] = recv.get('id') rds.lpush(channel, json.dumps(recv)) logging.info("pushed '{}' to '{}'".format(recv, channel))
def text_synth(): dist = {} for root, _, files in os.walk('data'): for file in files: fn = os.path.join(root, file) with open(fn, 'r') as f: text = f.read() text = re.split(r'\s', text) print(fn, len(text)) for word in text: word = clean_word(word) if len(word) > 25 or len(word) < 1: continue dist[word] = dist.get(word, 0) + 1 print('Unique words - ', len(dist)) # sort based on frequency sorted_dist = sorted(dist.items(), key=lambda i: i[1], reverse=True) new_dist = {} rank = len(sorted_dist) for k, v in sorted_dist: mod_freq = math.ceil(math.log(v, 1.9) * math.log(rank, 1.8)) if mod_freq > 0: new_dist[k] = mod_freq rank -= 1 # add numbers for i in range(50000): new_dist[gen_num()] = 1 print( f'A smoothing distribution, word count updated from {sum(dist.values())} to {sum(new_dist.values())}.' ) all_words = [] for word in new_dist: for i in range(new_dist[word]): all_words.append(word) np.random.shuffle(all_words) args = list(enumerate(all_words, 1)) # write images flash(lambda p: write_word(*p), args, max_workers=6144)
def registrace(): form = RegistrationForm() if form.validate_on_submit(): if (form.password.data != form.passwordAgain.data): flash('Hesla nejsou stejná.', FlashStyle.Danger) email = session['confirmed_email'] form.email.data = email return render_template("registrace.html", form=form) email = session['confirmed_email'] form.email.data = email dbUser = DBUser() dbUser.email = form.email.data dbUser.password = form.password.data dbUser.level = 0 if DBAccess.ExecuteScalar('select id from users where email=%s', (dbUser.email, )) is not None: flash( f'Uživatel {dbUser.email} je již zaregistrován, zvolte jiný email.', FlashStyle.Danger) dbUser.email = None form.email.data = None return render_template("registrace.html", form=form) dbUser.salt = salt = DBAccess.ExecuteScalar("select salt()") #md% tranform password use md5 function on password + salt # md5Pass = hashlib.md5((dbUser.password+dbUser.salt).encode()).hexdigest() # dbUser.password = md5Pass bcrypt = Bcrypt() dbUser.password = bcrypt.generate_password_hash( dbUser.password).decode('UTF-8') dbUser.SaveToSession('dbUserRegistration') return redirect(url_for("login_bp.registrace_name")) #email = session.pop('confirmed_email',None) email = session.get('confirmed_email') if (email is None): abort(403) form.email.data = email return render_template("registrace.html", form=form)
def POST(self): session = web.ses cookie = session.get('gso', '') gso = get_gso(cookie=cookie) values = web.input() ####### CHANGE PASSWORD ####### if 'change' in values: if not change_pass.validates(): return self.render.options(session.username, web.SERVER, change_pass(), delete()) elif not check_user_password(session.username, values['password']): flash("Contraseña de usuario incorrecta", "error") raise web.seeother('/options') else: gso.change_password(values['rpassword']) flash("Contraseña cambiada correctamente") raise web.seeother('/options') ####### UNREGISTER ####### elif 'delete' in values: if not delete.validates(): return self.render.options(session.username, web.SERVER, change_pass(), delete()) elif not check_user_password(session.username, values['password']): flash("Contraseña de usuario incorrecta", "error") raise web.seeother('/options') else: flash("Usuario <b>%s</b> borrado" % session.username) session.username = '' session.gso = '' gso.unregister() raise web.seeother('/login') ####### importar ####### elif 'restore' in values: file = web.input(myfile={}) to_import = file['myfile'].value filename = file['myfile'].filename gso.restore(to_import) flash("Fichero de contraseñas <b>%s</b> importado" % filename) raise web.seeother('/options') raise web.seeother('/options')
def sluzby_upload(): services = DBAccess.ExecuteSQL("select * from services") form = regFormBuilder( services ) # put all services to form, but I need to display it - by for cycle below form.checkBoxes.clear() # not to have duplicates on website for index in form.checkBoxIndexes: form.checkBoxes.append( getattr(form, "checkbox%d" % index) ) # displaying checkboxes on website if form.validate_on_submit(): # if validated, save in db nextId = session["id_user"] services_checked = [] for index in form.checkBoxIndexes: checkbox = getattr(form, "checkbox%d" % index) if checkbox.data: # for every checked services in form, save.. existing_combination = DBAccess.ExecuteScalar( "select count(*) from users_services where id_users=%s and " "id_services=%s and id_demand_offer=%s", (nextId, checkbox.id, form.demandOffer.data), ) text = DictionaryDemandOffer.get( form.demandOffer.data, "unknown" ).lower() if existing_combination > 0: flash( f'Zadaná kombinace {session["user"]}, {text} a {checkbox.label.text} již existuje.', FlashStyle.Danger ) else: DBAccess.ExecuteInsert( "insert into users_services " "(id_users, id_services, id_demand_offer) values (%s, %s, %s)", (nextId, checkbox.id, form.demandOffer.data), ) services_checked.append(checkbox.label) kwargs = { "demand_offer": DictionaryDemandOffer.get(form.demandOffer.data, "unknown"), "category": services_checked, } return render_template("sluzby_success.html", **kwargs) return render_template("sluzby.html", form=form)
def add(self): Form = self.get_add_form() instance = self.model() if request.method == 'POST': form = Form(request.forms) if form.validate(): instance = self.save_model(instance, form, True) flash('New %s saved successfully' % self.get_display_name(), 'success') return self.dispatch_save_redirect(instance) else: form = Form() return render_template(self.templates['add'], model_admin=self, form=form, instance=instance, **self.get_extra_context() )
def login(): form = LoginForm() if form.validate_on_submit(): sleep(3) user = form.user.data.strip() userRow = DBAccess.ExecuteSQL( "select email, password, first_name, surname, id, level,salt from " "users where trim(email) ilike %s", (user, ), ) if userRow is None: flash("Uživatel nenalezen", FlashStyle.Danger) return render_template("login.html", form=form) userRow = userRow[0] # execute sql gets list with one item, ie:[(email, password, first_name, # surname, id)], we need just (), ie tuple salt = userRow[6] def addSalt(passwordArg): return passwordArg + salt #md5Pass = hashlib.md5(addSalt(str(form.password.data)).encode()).hexdigest() bcrypt = Bcrypt() #bcryptHash = bcrypt.generate_password_hash(addSalt(str(form.password.data))) # check if second item is equal to hashed password try: if bcrypt.check_password_hash(userRow[1], form.password.data) == False: flash("Špatné heslo", FlashStyle.Danger) return render_template("login.html", form=form) except: flash("Špatné heslo", FlashStyle.Danger) return render_template("login.html", form=form) if userRow[5] == 0: flash( "Uživatel není ověřen, počkejte prosím na ověření" " administrátorem stránek.", FlashStyle.Danger) return render_template("login.html", form=form) session["user"] = user session["id_user"] = userRow[4] session["level_user"] = userRow[5] dbUser = DBAccess.GetDBUserById(userRow[4]) dbUser.SaveToSession('dbUser') # flash("Uživatel/ka {0} {1} přihlášen/a".format(userRow[2], userRow[3]), FlashStyle.Success) return redirect(url_for("overview_bp.prehled_all")) return render_template("login.html", form=form)
def POST(self): lform = form_login() if not lform.validates(): return self.render.login(form_login=lform) values = web.input() name = values['username'] pwd = values['password'] gso = get_gso() gso.auth(name, pwd) if gso.name: session.username = name session.gso = gso.cookie else: flash("Usuario o contraseña incorrectos", "error") raise web.seeother('/login') raise web.seeother('/index')
def new_password(token): try: ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) email = ts.loads(token, salt="email-renew-key", max_age=86400) except: abort(403) form = NewPasswordForm() if (form.validate_on_submit()): if (form.password.data != form.passwordAgain.data): flash('Hesla nejsou stejná.', FlashStyle.Danger) return render_template('new_password.html', form=form, email=email) #salt = DBAccess.ExecuteScalar("select salt()") #md5Pass = hashlib.md5((form.password.data+salt).encode()).hexdigest() bcrypt = Bcrypt() bcryptHash = bcrypt.generate_password_hash( form.password.data).decode('UTF -8') DBAccess.ExecuteUpdate( 'update users set password=%s where email like %s', (bcryptHash, email)) flash('Nové heslo nastaveno, nyní se zkuste přihlásit.', FlashStyle.Success) return redirect(url_for('login_bp.login'), ) return render_template('new_password.html', form=form, email=email)
def POST(self): nform = new_form() if not nform.validates(): return self.render.new(web.ses.username, nform) else: session = web.ses values = web.input() name = values['name'] args = {} args['account'] = values['account'] password = values['cpassword'] args['description'] = values['description'] args['type'] = values['type'] args['expiration'] = int(values['expiration']) cookie = session.get('gso', '') gso = get_gso(cookie=cookie) gso.set_raw_password(name, password, args) flash("Contraseña '%s' añadida" % str(name)) raise web.seeother('/')
def edit(self, pk): try: instance = self.get_object(pk) except self.model.DoesNotExist: abort(404) Form = self.get_edit_form(instance) if request.method == 'POST': form = Form(request.forms, obj=instance) if form.validate(): self.save_model(instance, form, False) flash('Changes to %s saved successfully' % self.get_display_name(), 'success') return self.dispatch_save_redirect(instance) else: form = Form(obj=instance) return render_template(self.templates['edit'], model_admin=self, instance=instance, form=form, **self.get_extra_context() )
def login(self): error = None Form = self.get_login_form() if request.method == 'POST': form = Form(request.forms) if form.validate(): authenticated_user = self.authenticate( form.username.data, form.password.data, ) if authenticated_user: self.login_user(authenticated_user) return redirect( request.params.get('next') or \ self.default_next_url ) else: flash('Incorrect username or password') else: form = Form() return render_template('auth/login.html', error=error, form=form)
def POST(self): rform = generate_reg_form(*session.rform) if not rform: raise web.seeother('/login') if not rform.validates(): return self.render.login(form_reg=rform) else: gso = get_gso() values = web.input() name = values['rusername'] pwd = values['rpassword'] if gso.check_user_name(name): errors = [u"%s no está disponible" % name] flash(errors, 'error') return self.render.login(form_reg=rform) else: gso.register(name, pwd) flash([u"Registrado con exito %s" % name]) raise web.seeother("/login")
def on_message(self, msg): self.message_count += 1 logging.info("ws received:" + str(msg)) msg = signmsg(msg) if (msg['type'] == "error"): print "Error: ", msg logging.error(msg) rds.lpush("cb:wsuser:error", msg) elif (msg["type"] == "subscriptions"): logging.info("Subscriptions : " + str(msg)) return elif msg['type'] == "done": print msg rds.lpush(channels["order_done"] + msg['order_id'], json.dumps(msg)) logging.info("Order done. Reason: {} order_id: {}".format( msg['reason'], msg['order_id'])) utils.flash("Order done. Reason: {} order_id: {}".format( msg['reason'], msg['order_id']), "info", sync=False) if (not msg["type"] in self.encountered_types): print(json.dumps(msg, indent=4, sort_keys=True)) self.encountered_types.append(msg["type"])
def senior_registration(): form = SeniorRegistrationForm() if (form.validate_on_submit()): if form.password.data != form.passwordAgain.data: flash('Hesla nejsou totožná!', FlashStyle.Danger) return render_template('senior_registration.html', form=form) if DBAccess.ExecuteScalar( 'select id from users where trim(email) ilike %s', (form.email.data.strip(), )) is not None: flash( f'Uživatel {form.email.data} je již zaregistrován, zvolte jiný email.', FlashStyle.Danger) form.email.data = None return render_template('senior_registration.html', form=form) dbUser = DBUser() dbUser.first_name = form.first_name.data dbUser.surname = form.surname.data dbUser.email = form.email.data dbUser.telephone = form.telephone.data dbUser.telephone2 = form.telephone2.data dbUser.comment = form.comment.data dbUser.street = form.street.data dbUser.street_number = form.street_number.data if (form.street_number.data == ''): dbUser.street_number = 1 dbUser.town = form.town.data dbUser.post_code = form.post_code.data dbUser.password = form.password.data bcrypt = Bcrypt() dbUser.password = bcrypt.generate_password_hash( dbUser.password).decode('UTF-8') dbUser.level = 1 address = '{} {} {}'.format(dbUser.street, dbUser.town, dbUser.post_code) coordinates = GetCoordinates(address) if (coordinates is not None): dbUser.latitude = round(coordinates[0], 5) dbUser.longitude = round(coordinates[1], 5) x = 1 y = 1 difference = 0.00001 originalLatitude = dbUser.latitude originalLongitue = dbUser.longitude #check if same coordinates already exists while DBAccess.ExecuteScalar( 'select id from users where latitude=%s and longitude=%s', ( dbUser.latitude, dbUser.longitude, )) is not None: #if exists add difference and try again and again.. dbUser.latitude = originalLatitude + x * difference dbUser.longitude = originalLongitue + y * difference if x != -1: x -= 1 elif y != -1: y -= 1 else: x = 1 y = 1 difference += 0.00001 else: flash('Nenalezeny souřadnice pro vaši adresu', FlashStyle.Danger) return render_template('senior_registration.html', form=form) dbUser.salt = salt = DBAccess.ExecuteScalar("select salt()") dbUser.id = DBAccess.GetSequencerNextVal('users_id_seq') dbUser.InsertDB() flash( f'Senior {dbUser.first_name} {dbUser.surname} email: {dbUser.email} vložen do databáze a nastaven jako ověřený.', FlashStyle.Success) return redirect(url_for("login_bp.login")) return render_template('senior_registration.html', form=form)
def profil_editace(): regForm = ProfilUpdateForm() dbUser = DBUser.LoadFromSession('dbUser') if (regForm.validate_on_submit()): dbUser.first_name = regForm.first_name.data dbUser.surname = regForm.surname.data dbUser.telephone = regForm.telephone.data dbUser.street = regForm.street.data # dbUser.street_number = regForm.street_number.data dbUser.post_code = regForm.post_code.data dbUser.town = regForm.town.data dbUser.info = regForm.info.data address = "{} {} {}".format(dbUser.street, dbUser.town, dbUser.post_code) coordinates = GetCoordinates(address) if (coordinates is not None): dbUser.latitude = coordinates[0] dbUser.longitude = coordinates[1] else: flash('Nenalezeny souřadnice pro vaši adresu', FlashStyle.Danger) return render_template("profil_editace.html", form=regForm) dbUser.UpdateDB() dbUser.SaveToSession('dbUser') if (regForm.soubor.data is not None and regForm.soubor.data.filename != ''): file_name = secure_filename(regForm.soubor.data.filename) path = os.path.join(app.config["UPLOAD_FOLDER"], file_name) regForm.soubor.data.save(path) json = UploadImage(path, str(dbUser.id) + 'new') version = json['version'] newImageUrl = GetImageUrl(str(dbUser.id) + 'new', version=version) RenameImage(str(dbUser.id) + 'new', str(dbUser.id)) DeleteImage(str(dbUser.id) + 'new') SendMail( GetEmail('noreplyMail'), dbUser.email, "Seniore.org - schválení profilové fotografie", "Vaše nové profilové foto na app.seniore.org bude nahráno na váš profil. Může to chvilku zabrat, mějte, prosím, strpení." ) # ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) # token = ts.dumps(dbUser.email, salt='change-photo-key') # confirm_url = url_for( # 'profile_bp.change_photo_confirm', # token=token, # _external=True) # denied_url = url_for( # 'profile_bp.change_photo_denied', # token=token, # _external=True) # noCacheSufix = '?nocache=<?php echo time(); ?' # email_text = f'''Uživatel { dbUser.first_name } {dbUser.surname} {dbUser.email} si změnil profilovou fotografii. <br>\ # <img src={GetImageUrl(dbUser.id)+noCacheSufix}>původní foto</img> <br>\ # <img src={newImageUrl+noCacheSufix}>nové foto</img> <br>\ # Link pro schválení fotografie {confirm_url} <br>\ # Link pro odmítnutí fotografie {denied_url}''' # SendMail("*****@*****.**",to_emails,'Seniore.cz - schválení profilové fotografie',email_text) # flash("Nová profilová fotografie byla odeslána administrátorovi ke schválení, o výsledku budete informováni emailem.",FlashStyle.Success) return redirect(url_for('profile_bp.profil')) regForm.first_name.data = dbUser.first_name regForm.surname.data = dbUser.surname regForm.telephone.data = dbUser.telephone regForm.street.data = dbUser.street # regForm.street_number.data = dbUser.street_number regForm.post_code.data = dbUser.post_code regForm.town.data = dbUser.town regForm.info.data = dbUser.info return render_template("profil_editace.html", form=regForm)
order_msg['uid'], order_msg['type'] except: logging.error("Message is not well formatted. Pushed to cambisim:error") rds.lpush(channels['error'], str(rdsmsg)) continue if (order_msg['type'] == "order"): if ( order_msg['side'] == "buy"): if (order_msg['size'] * order_msg['price'] > 10000): rds.lpush(channels['new_order'] + order_msg['uid'], json.dumps({"message": "Insufficient funds", "type": "refused"})) continue order_id = orderbook.buy(order_msg) elif ( order_msg['side'] == 'sell'): order_id = orderbook.sell(order_msg) rds.lpush(channels['new_order'] + order_msg['uid'], json.dumps({ 'type': 'received', 'order_id': order_id})) utils.flash("Order '%s' (%s) received" % (order_id, order_msg['side']), "info", sync=False) elif (order_msg['type'] == "cancel_order"): logging.info("Cancel Order '%s'" % order_msg['order_id']) orderbook.cancel_order(order_msg['order_id']) rds.lpush(channels['cancel_order'] + order_msg['uid'], json.dumps({ 'type': 'order_canceled', 'order_id': order_msg['order_id']})) utils.flash("Order '%s' canceled" % order_msg['order_id'], "info", sync=False) elif (order_msg['type'] == "get_order_status"): order = orderbook.get_order(order_msg['order_id']) if order is None: order = {'order_id': order_msg['order_id'], 'status': 'canceled'} rds.lpush(channels['order_status'] + order_msg['order_id'], json.dumps(order)) else: logging.warning("Message type unknown in " + str(order_msg)) # simulate market tickers = {}
def cancel_order(self, order_id): index = self.get_order_index(order_id) if index is None: utils.flash("order '{}' not found. Can't be canceled".format(order_id), "error", sync=false ) else: self.del_order(order_id)
# logging logging.basicConfig(format='%(asctime)s %(message)s', filename='/logs/cambista.log', level=logging.NOTSET) rds = utils.redis_connect() # coinbase connections try: auth_client = rw_auth() wsClient = ro_auth() except Exception as e: errmsg = "Cambista can't be started. Reason: '%s'. Please verify your json key files %s and %s" % ( e, cb_ro_keys, cb_rw_keys) print errmsg utils.flash(errmsg, 'danger') logging.error(errmsg) #sys.exit(78) sys.exit(0) # not restarted by docker-compose quote_increments = set_quote_increment(auth_client, pairs) wsClient.start() logging.info("Cambista is ready") # set cambista info regkey = os.environ.get("CAMBISTA_CHANNELS") + cambista_channel rds.set(regkey, json.dumps(cambista.to_dict())) while (True): # Workaround disconnect after 60sec of inactivity: if wsClient.ws:
def sluzby_delete(): DBAccess.ExecuteUpdate('delete from users_services where id_users = %s',(session['id_user'],)) flash('''Byly smazány všechny vaše poskytované/poptávané služby a proto budete skryti na mapě dobrovolníků/seniorů. Pro znovuzobrazení na mapě stačí kliknout na "Zobrazit mě ostatním" a přidat nějakou službu.''',FlashStyle.Success) return redirect(url_for("overview_bp.prehled_all"))
rds = utils.redis_connect() uid = sys.argv[1] logging.info("%s Spawning Orderbot" % uid) try: botdata = json.loads(rds.get("trader:startbot:" + uid)) except Exception as e: logging.error("Error '{}': no data in redis's 'trader:startbot:{}'".format( e, uid)) sys.exit(9) mybot = bot.OrderBot(botdata, rds) rds.delete("trader:startbot:" + uid) mybot.update_blueprint() utils.flash("bot '{}' initialized".format(mybot.name), "success", sync=False) for instruction in mybot.iter_instructions(): waited_order_id = mybot.get_order_id() if waited_order_id is None: # send new order to Cambista waited_order_id = mybot.send_order() if (waited_order_id is None): logging.info("Bot {} ({}): Order refused. Reason: {}".format( mybot.name, mybot.uid[:8], mybot.error)) utils.flash("Bot '{}': Order refused. Reason: {}".format( mybot.name, mybot.error), "danger", sync=False) stop_bot(mybot, status="order refused", exitcode=4) mybot.set_order_id(waited_order_id)
def redis_del(key): rds.delete(key) utils.flash("deleted '%s'" % key,'danger') return redirect(request.referrer) #url_for("redis_ls"))