def agregar_foto(): """Agrega una foto nueva""" archive = request.files['file'] landscape = 'landscape' in request.form.keys() if allowed_file(archive.filename): hashname = hashlib.sha1(archive.read()).hexdigest() archive.seek(0) hashname += '.' + get_file_extension(archive.filename) photo = Image.open(archive) if not landscape: width = photo.size[0] * 800 / photo.size[1] size = (width, 800) else: height = photo.size[1] * 800 / photo.size[0] size = (800, height) photo_thumb = photo.resize(size, Image.ANTIALIAS) filename = os.path.join(UPLOAD_FOLDER, hashname) photo_thumb.save(filename, quality=98) photo.save(os.path.join(UPLOAD_FOLDER, 'originals', hashname), quality=98) tags = procesar_tags(request.form['tags']) models.Photo(title=request.form['title'], description=request.form['description'], filehash=hashname, tags=tags) models.commit() flash(u'Se subió el archivo: %s y se renombro: "%s"' % \ (archive.filename, filename)) else: flash(u'Error al subir el archivo %s' % archive.filename) return redirect(url_for('admin'))
def newtask(): build = models.Build[1] b = models.Job(build=build, status='initing') b.created = datetime.datetime.today() models.commit() taskqueue.que.put(b.id) return str(b.id)
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User( first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data, password=form.password.data ) db.session.add(user) try: commit(db.session) except: send_error_email() flash('There has been an error') return render_template('auth/register.html', form=form) flash('You are now registered.') token = user.generate_confirmation_token() context = { 'first_name': user.first_name, 'last_name': user.last_name, 'token': token } print(url_for('auth.confirm', token=token, _external=True)) send_email( recipients=[user.email], subject='Confirm your email address', template_name='confirmation', context=context ) flash('We sent you a verification email.') login_user(user) return redirect(url_for('profile.index')) return render_template('auth/register.html', form=form)
def edit(): form = EditProfileForm() if form.validate_on_submit(): user = User.query.filter_by(email=current_user.email).first() user.first_name = form.first_name.data user.last_name = form.last_name.data user.email = form.email.data user.city = form.city.data user.state = form.state.data user.zip_code = form.zip_code.data if form.password.data is not None: user.update_password(form.password.data) try: commit(db.session) except: send_error_email() flash('There has been an error') return render_template('profile/edit.html', form=form) return redirect(url_for('profile.index')) form.first_name.data = current_user.first_name form.last_name.data = current_user.last_name form.email.data = current_user.email form.city.data = current_user.city form.state.data = current_user.state form.zip_code.data = current_user.zip_code return render_template('profile/edit.html', form=form)
def index(): form = PlaceSearchForm() places = FavoritePlace.query.filter_by(user_id=current_user.id).all() context = {'form': form, 'places': places} if form.validate_on_submit(): place = FavoritePlace(user_id=current_user.id, city=form.city.data, country=form.country.data, place_id=form.destination_place_id.data) if place in places: flash('You already saved that destination to your favorite places') else: db.session.add(place) try: commit(db.session) except: send_error_email() flash('There has been an error') return render_template('profile/index.html', **context) context['places'] = FavoritePlace.query.filter_by( user_id=current_user.id).all() if not current_user.validated: url = 'Click <a href="{}" class="alert-link">here</a> to resend confirmation email'.format( url_for('auth.resend_confirmation')) msg = Markup('Your email has not been confirmed. {}'.format(url)) flash(msg) return render_template('profile/index.html', **context)
def actualizar_foto(photo_id): photo = models.Photo.query.filter_by(id=photo_id).one() photo.title = request.form['title'] photo.description = request.form['description'] photo.tags = procesar_tags(request.form['tags']) models.commit() flash(u"La fotografía %s fue actualizada correctamente" % photo.title) return redirect(url_for('admin'))
def post(self): cls = self.model_class rvals = request.get_json() or request.values.to_dict() # request data obj = cls.from_dict(rvals, self._relation_handler) commit() return json_response({'id': obj.id})
def create_db(): log.debug('Creating DB') import os exec_script(os.path.join(settings['folders']['sql_dir'], 'schema.sql')) from models import DAO, commit from utils.indexers import idx url_img = idx['TheMovieDb'].load_config() DAO['settings'].insert({'name':'TheMovieDb.img', 'value':url_img}) commit()
def procesar_tags(tag_string): tag_names = [b.strip() for b in tag_string.split(',') if b != ''] tags = [tag for tag in models.Tag.query.all() if tag.name in tag_names] existent_tag_names = [tag.name for tag in tags] new_tags = set(tag_names) - set(existent_tag_names) for tag in new_tags: tags.append(models.Tag(name=tag)) flash(u'Se creó el tag "%s"' % tag) models.commit() return tags
def erase_photo(photo_id): """Hace Borrado fisico de una foto""" photo = models.Photo.query.filter_by(id=photo_id).one() photo.delete() models.commit() delete_uploaded(photo.filehash) flash(u"Se elimino la foto '%s' y el archivo %s" % \ (photo.title, photo.filehash)) return redirect(url_for('ver_todas_las_fotos'))
def home(): address = flask.request.args.get('address') nocheck = (flask.request.args.get('force') == 'true') if address: reponame = cleanname(address) if not models.Repo.get(name=reponame): try: if nocheck: if flask.request.args.get('reponame') != address: return flask.render_template( 'index.html', error='reponame not match') desc = 'unknown desc - forceadd' else: desc = checkrepo(reponame) except Exception as e: force_add = ''' If you confirm this is a go main package. <form class="pull-right"> <input type="hidden" name="address" value="{reponame}"> <input type="hidden" name="force" value="true"> <input type="text" name="reponame" placeholder="Type repo name again"> <button class="btn btn-warning btn-xs">force add</button> </form>'''.format(reponame=reponame) error = str(e) + ' <br>- ' + force_add return flask.render_template('index.html', error=flask.Markup(error)) repo = models.Repo(name=reponame) repo.created = datetime.datetime.today() repo.description = desc repo.author = 'unknown .. unfinished' # add new job build = models.Build(repo=repo, tag='branch:master', status='initing') job = models.Job(build=build, status='initing', created=datetime.datetime.today()) models.commit() taskqueue.que.put(job.id) return flask.redirect('/' + reponame, 302) new = models.select(r for r in models.Repo).\ order_by(models.desc(models.Repo.created))[:10] top = models.select(r for r in models.Repo).\ order_by(models.desc(models.Repo.down_count))[:10] #error = 'Beta version, only for test for the time now.' error = None return flask.render_template('index.html', top_repos=top, new_repos=new, error=error)
def person_assign(id): person = Person[id] role = Role[request.form['role']] assignment = Assignment( person=person, role=role, year=int(request.form['year']), semester=int(request.form['semester']) ) commit() return redirect(url_for('person_show', id=person.id))
def build(): reponame = request.args.get('reponame') tag = request.args.get('tag') repo = models.Repo.get(name=reponame) build = models.Build.get(repo=repo, tag=tag) or \ models.Build(repo=repo, tag=tag) job = models.Job(build=build, status='initing') job.created = datetime.datetime.today() models.commit() taskqueue.que.put(job.id) return redirect('/task/%d' % job.id)
def post(self): cls = self.model_class rvals = self.getReqData() obj = cls.from_dict(rvals, self._relation_handler) try: commit() except TransactionIntegrityError as ex: obj = select(i for i in cls if i.hash == obj.hash)[:][0] abort(409, id=obj.id) return json_response({'id': obj.id})
def confirm(token): if current_user.validated: return redirect(url_for('profile.index')) if current_user.confirm(token): try: commit(db.session) flash('Thank you for confirming your account.') except: send_error_email() flash('There has been a server error') else: flash('The confirmation link is invalid or has expired') return redirect(url_for('profile.index'))
def put(self, id): cls = self.model_class try: obj = cls[id] except ObjectNotFound as ex: abort(404) rvals = request.get_json() or request.values.to_dict() # request data obj.update(rvals, self._relation_handler, exclude=('id')) commit() return json_response({'id': obj.id})
def test_token_confirmation(self): user = User( first_name='Adam', last_name='Mertz', email='*****@*****.**', password='******' ) db.session.add(user) commit(db.session) token = user.generate_confirmation_token() self.assertTrue(user.confirm(token), 'Confirmation token failed')
def test_token_expiration(self): user = User( first_name='Adam', last_name='Mertz', email='*****@*****.**', password='******' ) db.session.add(user) commit(db.session) token = user.generate_confirmation_token(expiration=1) time.sleep(3) self.assertFalse(user.confirm(token), 'Token should of expired')
def put(self, id): cls = self.model_class try: obj = cls[id] except ObjectNotFound as ex: abort(404) rvals = self.getReqData() obj.update(rvals, self._relation_handler, exclude=('id')) commit() return json_response({'id': obj.id})
def test_default_values_for_attributes(self): user = User( first_name='Adam', last_name='Mertz', email='*****@*****.**', password='******' ) db.session.add(user) commit(db.session) self.assertEqual(user.city, '', 'city should default to an empty string') self.assertEqual(user.state, '', 'state should default to an empty string') self.assertIsNone(user.zip_code, 'zip_code has no default') self.assertFalse(user.validated, 'validated should default to False')
def append_media(indexer, media, id): if not indexer: indexer = _current_indexer(media) data = idx[indexer].get_media(media, id) idx[indexer].store_img(data['poster']) if media == 'movie': DAO['movie'].insert(data) elif media == 'tv': DAO['tv'].insert(data) eps = [] for n_season in range(data['n_seasons']): eps.extend(idx[indexer].get_season(data['id'], n_season + 1, data['tv_id'])) DAO['episode'].insert_many(eps) commit() return {}
def get_user_info(): try: from models import create_model, commit, User, Game, GameUser data = request.get_json() user_code = data.get('user_code') game_code = data.get('game_code') if not user_code: # create new user user_code = generate_unique_code() user = create_model(User, code=user_code) else: user = User.find_by_code(user_code) assert user, "User not found" user.last_seen = datetime.datetime.now() result = { 'top_score': user.top_score, 'alias' : user.alias, 'user_code': user.code } if game_code: game = Game.find_by_code(game_code) or create_model(Game, code=game_code) if game.finished: result['error'] = "This game has already finished" else: game_user = GameUser.query.filter(GameUser.user_id == user.id).filter(GameUser.game_id == game.id).first() if not game_user: game_user = GameUser(game_id=game.id, user_id=user.id, created=datetime.datetime.now()) game.users.append(game_user) else: result['map'] = game_user.map commit() response = jsonify(result) # response.set_cookie('user_code', user_code, domain=request.host, expires=datetime.datetime.now() + datetime.timedelta(days=9000)) return response except Exception as e: print(traceback.format_exc()) return jsonify({'error': repr(e)})
def save_orders(): username = session.get("username") user_id = db.session.query( LoginModel.id).filter(LoginModel.username == username).first()[0] new_order = MyOrderModel() saved_orders = [] for item in session: if item.endswith("_order"): placed_items = json.dumps({item[:-6]: session.get(item)}) new_order.user_id = user_id new_order.order = placed_items new_order.save() saved_orders.append(item) commit() return saved_orders
def home(): address = flask.request.args.get('address') nocheck = (flask.request.args.get('force') == 'true') if address: reponame = cleanname(address) if not models.Repo.get(name=reponame): try: if nocheck: if flask.request.args.get('reponame') != address: return flask.render_template('index.html', error='reponame not match') desc = 'unknown desc - forceadd' else: desc = checkrepo(reponame) except Exception as e: force_add = ''' If you confirm this is a go main package. <form class="pull-right"> <input type="hidden" name="address" value="{reponame}"> <input type="hidden" name="force" value="true"> <input type="text" name="reponame" placeholder="Type repo name again"> <button class="btn btn-warning btn-xs">force add</button> </form>'''.format(reponame=reponame) error = str(e) + ' <br>- ' + force_add return flask.render_template('index.html', error=flask.Markup(error)) repo = models.Repo(name=reponame) repo.created = datetime.datetime.today() repo.description = desc repo.author = 'unknown .. unfinished' # add new job build = models.Build(repo=repo, tag='branch:master', status='initing') job = models.Job(build=build, status='initing', created=datetime.datetime.today()) models.commit() taskqueue.que.put(job.id) return flask.redirect('/'+reponame, 302) new = models.select(r for r in models.Repo).\ order_by(models.desc(models.Repo.created))[:10] top = models.select(r for r in models.Repo).\ order_by(models.desc(models.Repo.down_count))[:10] #error = 'Beta version, only for test for the time now.' error=None return flask.render_template('index.html', top_repos=top, new_repos=new, error=error)
def test_unique_email_validation(self): user = User(first_name='Steve', last_name='Sanchez', email='*****@*****.**', password='******') db.session.add(user) commit(db.session) form = RegistrationForm(first_name='Adam', last_name='Mertz', email='*****@*****.**', password='******', confirm='test') self.assertFalse(form.validate(), 'email should be validated as unique')
def test_email_uniqueness(self): user_one = User( first_name='Adam', last_name='Mertz', email='*****@*****.**', password='******' ) user_two = User( first_name='Steve', last_name='McQueen', email='*****@*****.**', password='******' ) db.session.add(user_one) commit(db.session) db.session.add(user_two) self.assertRaises(IntegrityError, commit, db.session)
def signup(): if request.method == 'GET': return render_template('signup.html') if request.method == 'POST': data = request.form username = data['username'].lower() email = data['email'].lower() password = data['password'] if not email or not password: return render_template('signup.html', error="missing email or password") user = models.User.get(email=email) if user: return render_template('signup.html', error="Email already exists") user = models.User(email=email) user.hash_password(password) models.commit() login_user(user) return redirect(url_for('index'))
def login(username, password): """logins the user if already exists or creates new row in users table for the new user""" password_hash = hashlib.md5(password) password = password_hash.hexdigest() try: user = db.session.query(LoginModel).filter( LoginModel.username == username).first() if user.username == username and user.password == password: return "success" elif user.username == username and user.password != password: return "Password is wrong" except: user = LoginModel() user.username = username user.password = password user.save() commit() return "success"
def test_default_attribute_values(self): user = User( first_name='Adam', last_name='Mertz', email='*****@*****.**', password='******' ) db.session.add(user) commit(db.session) place = FavoritePlace(user_id=user.id) db.session.add(place) commit(db.session) self.assertIsNotNone(place.added, 'added should have a value') self.assertIsInstance(place.added, datetime.datetime, 'added should be datetime object') self.assertEqual(place.city, '', 'city should default to empty string') self.assertEqual(place.country, '', 'country should default to empty string') self.assertEqual(place.place_id, '', 'place_id should default to empty string')
def reset(token): email = None try: s = get_url_serializer(current_app) email = s.loads(token, salt='recovery-key') except: abort(404) form = PasswordResetForm() if form.validate_on_submit(): user = User.query.filter_by(email=email).first_or_404() user.update_password(form.password.data) try: commit(db.session) except: send_error_email() flash('There has been an error') return redirect(url_for('auth.forgot_password')) flash('Password updated') return redirect(url_for('auth.login')) return render_template('auth/reset.html', form=form)
def update_user_info(): try: from models import User, commit data = request.get_json() user_code = data.get('user_code') user = User.find_by_code(user_code) assert user, 'User not found' assert data, 'user info data is missing' if 'top_score' in data: user.top_score = int(data['top_score']) if 'alias' in data: user.alias = data['alias'] commit() return jsonify({'result': 'OK'}) except Exception as e: return jsonify({'error': str(e)})
def no(): anon_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) today_utc = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) anon_shipped = models.select( s for s in models.Ship if s.ip_address == anon_ip and s.dt_shipped > today_utc) shipped = models.select(s for s in models.Ship if s.dt_shipped > today_utc) if anon_shipped: no = shipped.filter(lambda n: n.no).count() return render_template('no.html', shipped=shipped.count(), no=no, percent=(int(no)) / (int(shipped.count())) * 100) models.Ship(no=True, dt_shipped=datetime.utcnow(), ip_address=anon_ip) models.commit() no = shipped.filter(lambda n: n.no).count() return render_template('no.html', shipped=shipped.count(), no=no, percent=(int(no)) / (int(shipped.count())) * 100)
def test_equality(self): user = User( first_name='Adam', last_name='Mertz', email='*****@*****.**', password='******' ) db.session.add(user) commit(db.session) place_one = FavoritePlace(user_id=user.id) db.session.add(place_one) commit(db.session) place_two = FavoritePlace.query.first() self.assertEqual(place_one, place_two, '__eq__ does not work properly') place_three = FavoritePlace(user_id=user.id, place_id='blah') db.session.add(place_three) commit(db.session) self.assertNotEqual(place_one, place_three, '__ne__ does not work properly')
def check_pronounceability(word): stuff = text_clf.predict_proba([word]) pronounceability = round(100 * stuff[0][1], 2) models.Word(word=word, pronounceability=pronounceability) models.commit() return pronounceability
def wrap(*args, **kwargs): kind = None # Grab the session cookie if it exists. cookie = request.cookies.get(current_app.session_cookie_name, None) # Try get the Auth header data. try: auth = request.headers['Authorization'] kind, _, value = auth.partition(' ') if kind == 'Basic': value = base64.standard_b64decode(bytes(value, 'utf8')) id, _, pw = str(value, 'utf8').partition(':') elif kind == 'Google' or kind == 'Facebook': xtra = request.headers['X-Requested-With'] # elif kind == 'Token': except (KeyError, base64.binascii.Error) as ex: # print(type(ex)) return fn(*args, **kwargs) # If there was an Auth header, autheticate with that info, # and create a session. if kind == 'Basic': with db_session: user = select(u for u in User if u.email == id or u.username == id)[:] if len(user) == 1: if Password.verify(pw, user[0].password): sessionize(user=user[0].to_dict()) else: session.clear() elif not user: with db_session: user = User(email=id, password=pw) sessionize(user=user.to_dict()) else: session.clear() elif kind in ('Google', 'Facebook') and xtra == 'Fetch': kind = kind.lower() sec = client_secrets[kind]['web'] sec['provider'] = kind sec['token'] = value try: value = oauth.upgrade_token(**sec) ouser = oauth.get_user(provider=kind, **value) print(ouser) with db_session: user_oauth = select(o for o in OAuth if o.puid == ouser['id'])[:] if len(user_oauth) == 1: print(user_oauth[0].user) user = user_oauth[0].user.to_dict( ('password', 'oauth')) try: user['picture'] =\ ouser['picture']['data']['url'] except TypeError as ex: user['picture'] = ouser.get('picture', '') sessionize(user=user) elif not user_oauth: # with db_session: user = User(name=ouser.get('name')) user_oauth = OAuth( provider=kind, puid=ouser.get('id'), access_token=value.get('access_token', ''), refresh_token=value.get('refresh_token', ''), user=user) commit() user = user.to_dict(('password', 'oauth')) try: user['picture'] =\ ouser['picture']['data']['url'] except TypeError as ex: user['picture'] = ouser.get('picture', '') sessionize(user=user) except oauth.HTTPError as ex: abort(make_response(ex.text, ex.status_code)) elif kind is not None: # An unknown kind or kind 'None' session.clear() return fn(*args, **kwargs)
def roles_create(): name = request.form['name'] role = Role(name=name) commit() return jsonify(result=role.to_dict())
def person_create(): person = Person(name=request.form['name']) commit() return redirect(url_for('person_show', id=person.id))
def person_update(id): person = Person[id] person.name = request.form['name'] person.email = request.form['email'] commit() return redirect(request.path)
def delete_tag(tag_name): models.Tag.get_by(name=tag_name).delete() models.commit() flash(u'Se eliminó el tag "%s"' % tag_name) return redirect(url_for('admin'))