示例#1
0
def characters():
    user = g.user
    data = {}

    data['characters'] = user.characters
    for char in data['characters']:
        print images.url(char.image)

    return render_template('characters.html', title='Characters', user=user, data=data)
示例#2
0
def handle_request():
    if request.method == 'POST':
        if request.files:
            username = '******'

            filename = images.save(request.files['image'])
            url = images.url(filename)

            #---------------------

            result = predict(filename)

            #---------------------

            user = User.query.filter_by(username=username).first()
            if user is None: user = User(username=username)

            report = Report(user=user, data=json.dumps(result))

            image = Image(report=report)

            image.image_filename = filename
            image.image_url = url

            db.session.add(user)
            db.session.add(report)
            db.session.add(image)

            db.session.commit()

            return 'Report Generated'
        return 'No Files Recieved'
    return 'Method not POST'
示例#3
0
def manage_plant(id):
    plant = Plant.query.get(id)
    form = PlantManagementForm()
    if form.validate_on_submit():
        if form.action.data:
            print("Update the plant")
            # if location is not null, update the plant's location
            if form.location.data:
                plant.location = form.location.data
                flash('Congratulations, plant location updated')

            # if there is a photo, delete the old on and set the new one
            if request.files['photo']:
                os.remove(app.config['UPLOADS_DEFAULT_DEST'] +
                          plant.image_filename)

                filename = images.save(request.files['photo'])
                url = images.url(filename)
                plant.image_filename = filename
                plant.image_url = url
                flash('Congratulations, plant photo updated')

        if form.delete.data:
            print("delete the plant")
            db.session.delete(plant)
            flash('Congratulations, plant deleted')

        db.session.commit()

        return redirect(url_for('index'))
    return render_template('manage_plant.html', form=form)
示例#4
0
def displayImage():
    url = ''
    if request.method == 'POST':
        if 'file' in request.files:
            image = request.files['file']
            if image.filename == "":
                print("No filename")
                return redirect(request.url)

            if allowed_image(image.filename):
                if (FaceRecognition().detectFaces(image=image.stream)):
                    filename = Image.open(image)
                    secure_name = secure_filename(image.filename)
                    filename.save(Config.TEMPUSERIMG / secure_name)
                    url = images.url('processing/' + image.filename)
                    return jsonify(uploaded_image=url)
                else:
                    return jsonify(
                        error=404,
                        error_msg=
                        'There was no face detected in the uploaded image or there are more than 1 face detected in the uploaded image. Please upload again.'
                    ), 400

            else:
                flash("That file extension is not allowed")
                return redirect(request.url)
示例#5
0
def novo_servidor():
	form = FormServidor()	
	if request.method == 'POST':
		if form.validate_on_submit:
			filename = images.save(request.files['photo'])
			url = images.url(filename)	
			# Verifica se o cpf já existe
			cpf = form.cpf.data	
			retorno = Servidor.query.filter_by(cpf=cpf).first()	
			if retorno is not None:
				flash( 'O CPF já está cadastrado.')
				return render_template('pages/novo_servidor.html', title="Cadastro de Servidor", form=form)
			else:	# caso contrário insere no banco de dados			
				servidor = Servidor()
				servidor.nome = form.nome.data
				servidor.cpf  = cpf
				servidor.banco = form.banco.data
				servidor.agencia = form.agencia.data
				servidor.conta = form.conta.data
				servidor.tipoconta = form.tipoconta.data
				servidor.photo = filename
				servidor.photo_url = url
				db.session.add(servidor)
				db.session.commit()
				flash('Novo registro, {}, cadastrado!'.format(servidor.nome), 'sucess')
				return redirect(url_for('pages.servidores'))
		else:
			flash('ERROR! O registro não foi adicionado', 'error')
		
	return render_template('pages/novo_servidor.html', title="Cadastro de Servidor", form=form)
示例#6
0
def register():
    """
    Handle requests to the /register route
    Add a user to the database through the registration form
    """
    form = RegistrationForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            filename = images.save(request.files['user_photo'])
            url = images.url(filename)
            user = User(email=form.email.data,
                        username=form.username.data,
                        first_name=form.first_name.data,
                        last_name=form.last_name.data,
                        sex=form.sex.data,
                        number1=form.number1.data,
                        number2=form.number2.data,
                        country=form.country.data,
                        image_filename=filename,
                        image_url=url,
                        password=form.password.data)
            # add user to the database
            db.session.add(user)
            db.session.commit()
            flash('You have successfully registered! You may now login.')

            # redirect to the login page
            return redirect(url_for('auth.login'))

    # load registration template
    return render_template('auth/register.html', form=form, title='Register')
示例#7
0
def report():
    form = CaseForm()
    form.level.choices = [
        (building.buildingDesc, building.buildingDesc)
        for building in Building.query.filter_by(buildingID='B02').all()
    ]
    user = current_user.get_id()
    if request.method == 'POST':
        filename = secure_filename(images.save(request.files['photo']))
        url = images.url(filename)
        case = Case(photoFilename=filename,
                    photoURL=url,
                    building=form.building.data,
                    location=request.form['location'],
                    level=request.form['level'],
                    roomNum=form.unit.data,
                    typeOfFacility=request.form['facility'],
                    severity=form.severity.data,
                    comments=form.description.data,
                    userID=user)
        db.session.add(case)
        db.session.commit()
        # db.session.refresh(case)
        createGroupedBar()
        createBar()
        backlogPie()
        buildingPie()
        case_id = str(case.caseID)
        return redirect(url_for('success', caseid=case_id))
    return render_template('report.html', title='Case Reporting', form=form)
示例#8
0
def editPerson(clinic_id, region_name, person_id):
    person = Person.query.filter_by(id=person_id).one()
    form = EditPerson(person.name, person.email, obj=person)
    if form.validate_on_submit():
        if form.picture_url.data == person.picture_url:
            url = form.picture_url.data
            filename = person.picture_filename
        else:
            filename = images.save(request.files['picture_url'])
            url = images.url(filename)
        person.name = form.name.data
        person.comments = form.comments.data
        person.picture_filename = filename
        person.picture_url = url
        person.phone = form.phone.data
        person.email = form.email.data
        person.department = form.department.data
        person.date_of_request = form.date_of_request.data
        person.date_of_request2 = form.date_of_request2.data
        db.session.commit()
        flash('Изменения сохранены')
        return redirect(
            url_for('clients.showPersons',
                    region_name=region_name,
                    clinic_id=clinic_id))
    return render_template('/clients/edit_person.html',
                           title='Edit Client',
                           form=form,
                           person_id=person_id,
                           clinic_id=clinic_id,
                           region_name=region_name)
示例#9
0
 def import_data(self, request):
     """Import the data for this recipe by either saving the image associated
     with this recipe or saving the metadata associated with the recipe. If
     the metadata is being processed, the title and description of the recipe
     must always be specified."""
     try:
         if 'recipe_image' in request.files:
             filename = images.save(request.files['recipe_image'])
             self.image_filename = filename
             self.image_url = images.url(filename)
         else:
             json_data = request.get_json()
             self.recipe_title = json_data['title']
             self.recipe_description = json_data['description']
             if 'recipe_type' in json_data:
                 self.recipe_type = json_data['recipe_type']
             if 'rating' in json_data:
                 self.rating = json_data['rating']
             if 'ingredients' in json_data:
                 self.ingredients = json_data['ingredients']
             if 'recipe_steps' in json_data:
                 self.recipe_steps = json_data['recipe_steps']
             if 'inspiration' in json_data:
                 self.inspiration = json_data['inspiration']
     except KeyError as e:
         raise ValidationError('Invalid recipe: missing ' + e.args[0])
     return self
示例#10
0
文件: routes.py 项目: Diddley/ttp
def newclub():
    form = NewClubForm()
    if form.validate_on_submit():
        division = form.club_division.data
        filename = images.save(request.files['club_badge'])
        url = images.url(filename)
        club = Club(clb_name=form.clubname.data,
                    clb_town=form.club_town.data,
                    clb_postcode=form.club_postcode.data,
                    division_id=division.id,
                    clb_contract=form.club_contract.data,
                    clb_collab=form.club_collab.data,
                    clb_fundingapp=form.club_fundingapp.data,
                    clb_badge=url)
        db.session.add(club)
        db.session.commit()
        flash('You have successfully added ' + club.clb_name)
        return redirect(url_for('main.clubs'))
    # page = request.args.get('page', 1, type=int)
    # clubs = Club.query.order_by(Club.clb_name.asc()).paginate(
    #     page, current_app.config['POSTS_PER_PAGE'], False)
    # next_url = url_for(
    #     'main.clubs', page=clubs.next_num) if clubs.has_next else None
    # prev_url = url_for(
    #     'main.clubs', page=clubs.prev_num) if clubs.has_prev else None
    return render_template('form.html', title='Add Club', form=form)
示例#11
0
def show(name):
    image = Image.query.filter_by(name=name).first()
    if image is None:
        abort(404)

    url = images.url(image.filename)
    return render_template('show.html', 
                           url=url, 
                           name=name)
示例#12
0
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and \
            form.validate_on_submit():

        filename = images.save(request.files['image'])
        url = images.url(filename)
        post = Post(title=form.title.data,
                    sub_title=form.sub_title.data,
                    body=form.body.data,
                    author=current_user._get_current_object(),
                    image_url=url,
                    image_filename=filename)

        topics = form.topics.data
        clean_topics = "".join(topics.split())
        topics_list = clean_topics.split(',')
        capitalized = [topic.capitalize() for topic in topics_list]

        for topic in capitalized:
            exists = Topic.query.filter_by(topic=topic).all()
            if exists:
                post.topics.append(exists[0])

            else:
                new_topic = Topic(topic=topic)
                post.topics.append(new_topic)

        db.session.add(post)
        db.session.commit()

        return redirect(url_for('.index'))

    page = request.args.get('page', 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page,
        per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    popular_posts = get_popular_posts()
    popular_topics = get_popular_topics()

    return render_template('index.html',
                           popular_posts=popular_posts,
                           popular_topics=popular_topics,
                           form=form,
                           posts=posts,
                           show_followed=show_followed,
                           pagination=pagination)
示例#13
0
def upload(id):
    event = Event.query.filter_by(id=int(id)).first_or_404()
    form = PhotoUploadForm()
    if form.validate_on_submit():
        name_path = 'event/eventphoto_{}.'.format(event.id)

        f = form.event_photo.data
        filename = images.save(request.files['event_photo'], name=name_path)
        event.image_url = images.url(filename)
        db.session.commit()
        return redirect(url_for('event', id=id))
    return render_template('upload.html', form=form)
示例#14
0
def edit_profile():
    form = EditProfileForm(user=current_user)
    if form.validate_on_submit():
        if not os.path.exists(current_app.config['UPLOADS_DEFAULT_DEST']):
            os.makedirs(current_app.config['UPLOADS_DEFAULT_DEST'])
            os.chmod(current_app.config['UPLOADS_DEFAULT_DEST'],
                     stat.S_IRWXU + stat.S_IRGRP + stat.S_IWGRP + stat.S_IROTH)
        elif not os.path.exists(current_app.config['IMG_THUMB_DEST']):
            os.makedirs(current_app.config['IMG_THUMB_DEST'])
            os.chmod(current_app.config['IMG_THUMB_DEST'],
                     stat.S_IRWXU + stat.S_IRGRP + stat.S_IWGRP + stat.S_IROTH)

        if form.avatar.data:
            avatar_filename = images.save(form.avatar.data)
            size = 50, 50
            im = Image.open(
                os.path.join(current_app.config['UPLOADS_DEFAULT_DEST'],
                             'images/', avatar_filename))
            im.thumbnail(size)
            file_split_name = os.path.splitext(avatar_filename)
            img_thumb = file_split_name[0] + '_thumbnail' + file_split_name[-1]
            im.save(
                os.path.join(current_app.config['IMG_THUMB_DEST'], img_thumb))
            current_user.thumb_head_img = url_for(
                'static', filename='uploads/thumbnails/' + img_thumb)
            current_user.head_img = images.url(avatar_filename)

        if form.location.data:
            current_user.location = form.location.data
        if form.phone.data:
            current_user.phone = form.phone.data
        if form.intro.data:
            current_user.info = form.intro.data
        current_user.username = form.username.data

        db.session.add(current_user)
        try:
            db.session.commit()
            flash('个人资料已经更新!')
        except:
            flash('未知错误!请重试或联系管理员')
            db.session.rollback()

        return redirect(url_for('.user', username=current_user.username))
    form.username.data = current_user.username
    form.phone.data = current_user.phone
    form.intro.data = current_user.info
    form.location.data = current_user.location
    return render_template('home/edit_profile.html',
                           form=form,
                           user=current_user)
示例#15
0
def add():
    form = AddUserForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            filename = images.save(request.files['user_image'])
            url = images.url(filename)
            new_user = User(form.name.data, form.email.data, form.sex.data, form.password.data, filename, url)
            db.session.add(new_user)
            db.session.commit()
            return redirect("/")
        else:
            flash("入力内容が間違っているため、ユーザー登録できませんでした。")


    return render_template("users/add.html", form=form)
示例#16
0
def upload():
    if request.method == 'POST':
        filename    = images.save(request.files['photo'])
        url_photo   = images.url(filename)
        user = User.query.get(current_user.id)
        user.url_photo = url_photo
        try:
            db.session.commit()
            flash('Photo uploaded', 'alert-success')
        except:
            flash('Photo did not load', 'alert-danger')        
        return redirect(url_for('main.profile'))
    elif request.method == 'GET':
        form = UploadForm()
        return render_template('main/upload.html', form=form)
示例#17
0
def upload_avatar():
    nickname = request.form['user_nickname']
    user = User.query.filter_by(nickname=nickname).first()

    if g.user.nickname != nickname:
        return abort(404)
    else:
        filename = images.save(request.files['avatar'])
        url = images.url(filename)

        user.set_avatar_url(url)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('user_profile', nickname=nickname, _external=True))
    return redirect(url_for('user_profile', nickname=nickname, _external=True))
示例#18
0
def add_cuisine():
    form = AddCuisineForm()
    if request.method == 'POST':
        print "Hello"
        if form.validate_on_submit():
            print form.errors
            filename = images.save(request.files['cuisine_img'])
            url = images.url(filename)
            addCuisine(form.title.data, form.description.data,
                       int(form.global_.data), int(form.preparation.data),
                       int(form.meal_type.data), int(form.main_ingr.data),
                       filename, url)

            return redirect(url_for('index'))

    return render_template('addcuisine.html', form=form)
示例#19
0
def input_charity_info():
    '''
    Redirect to this page after Stripe Connect
    Create the product and the plan which is connected to the charity
    '''
    print('AAAA')
    form = CharityInputForm()
    if form.validate_on_submit():  #This line should be fixed later.
        '''
        Save the charity's info into Charity data table
        '''
        print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
        filename = images.save(request.files['charity_logo'])
        image_url = images.url(filename)

        charity = Charity.query.filter_by(user_id=current_user.id).first()

        charity.charity_name = form.charity_name.data
        charity.charity_logo = image_url
        charity.description = form.description.data
        charity.link = form.link.data
        charity.is_form_done = True

        db.session.commit()

        stripe.api_key = stripe_keys['secret_key']

        try:
            product = stripe.Product.create(name='donation', type='service')

            #Plan should be created only once
            plan = stripe.Plan.create(
                nickname=current_user.id,  #Cannot be changed
                product=product.id,
                id=current_user.id,
                interval='month',
                currency='usd',
                amount=0)
        except:
            print('Error caused.')

        flash('Your Charity is registered successfully!')
        return redirect(url_for('index'))
    return render_template('input_charity_info.html',
                           title='Input Charity Info',
                           form=form)
示例#20
0
def update_photo(id):
	row = Servidor.query.filter_by(id=id).first()
	if row:
		form = FormPhoto(request.form, obj=row)
		if request.method == 'POST' and form.validate_on_submit:
			filename = images.save(request.files['photo'])
			url = images.url(filename)
			updeted = Servidor.query.filter_by(id=id).update({
				Servidor.photo : filename,
				Servidor.photo_url: url
			})	
			db.session.commit()	
			flash('Foto atualizada com sucesso!', 'sucess')	
			return redirect(url_for('pages.servidores'))
		return render_template('pages/update_photo.html', form=form, row=row)
	else:
		flash('O Registro com ID: #{}, não existe na base de dados.'.format(id), 'error')
		return redirect(url_for('pages.servidores'))
示例#21
0
def add_recipe():
    form = AddRecipeForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            filename = images.save(request.files['recipe_image'])
            url = images.url(filename)
            new_recipe = Recipe(form.recipe_title.data,
                                form.recipe_description.data, current_user.id,
                                True, filename, url)
            db.session.add(new_recipe)
            db.session.commit()
            flash('New Recipe, {0}, added!'.format(new_recipe.recipe_title),
                  'success')
            return redirect(url_for('recipes.user_recipes'))
        else:
            flash_errors(form)
            flash('ERROR! Recipe was not added!', 'error')

    return render_template('add_recipe.html', form=form)
示例#22
0
def index():
    form = ProfileForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            filename = images.save(request.files['img'])
            url = images.url(filename)
            from app.models import Profile
            new_profile = Profile(name=form.name.data,
                                  image_filename=filename,
                                  image_url=url)
            db.session.add(new_profile)
            db.session.commit()
            flash('New profile, {}, added!'.format(new_profile.name),
                  'success')
            return redirect(url_for('main.display_profile'))
        else:
            flash_errors(form)
            flash('ERROR! Profile was not added.', 'error')
    return render_template('add_profile.html', form=form)
示例#23
0
def make_post(chat_name):
    form = PostForm(chat_name=chat_name)
    if form.validate_on_submit():
        chat_name = form.chat_name.data

        new_post = Post(title=form.title.data, body=form.body.data, author=current_user)
        new_post.chat = Chat.query.filter_by(name=chat_name).first()

        if 'image' in request.files and request.files['image']:
            filename = images.save(form.image.data)
            url = images.url(filename)
            image = Image(filename=filename, url=url)
            new_post.attachment = image

        db.session.add(new_post)
        db.session.commit()
        flash('Your post is now live!')
        return redirect(url_for('main.show_chat', name=chat_name))
    return render_template('make_post.html', title="New Post", form=form)
示例#24
0
def edit_profile():
    form = EditProfileForm(current_user.username)
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        current_user.zipcode = form.zipcode.data
        filename = images.save(request.files['image'])
        current_user.image_filename = filename
        current_user.image_url = images.url(filename)
        db.session.commit()
        flash(_('Your changes have been saved!'))
        return redirect(url_for('edit_profile'))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me
        form.zipcode.data = current_user.zipcode
    return render_template('edit_profile.html',
                           title=_('Edit Profile'),
                           form=form)
示例#25
0
def addNew():
	if current_user.is_admin:
		page_title="Grace this world with a new post, Sensei"
		post=NewPost()
		if request.method=='POST' and post.validate_on_submit():
			if 'post_image' not in request.files:
				flash('No Files')
				return 'no file found'
			filename=images.save(request.files['post_image'])
			url=images.url(filename)
			blogpost=Post(post.title.data, post.category.data, post.content.data, filename, url)
			save_changes(blogpost, post, isnew=True)
			# return render_template('postData.html', form=post)
			return redirect(url_for('index'))
		else:
			flash(post.errors)
		
		return render_template('newpost.html', form=post, title=page_title)
	else:
		abort(404)
示例#26
0
def upload():
    form = UploadForm()
    if request.method == 'POST':
        if form.validate_on_submit():

            username = form.username.data

            filename = images.save(request.files['image'])
            url = images.url(filename)

            #---------------------

            result = predict(filename)

            #---------------------

            user = User.query.filter_by(username=username).first()
            if user is None: user = User(username=username)

            report = Report(user=user, data=json.dumps(result))

            image = Image(report=report)

            image.image_filename = filename
            image.image_url = url

            db.session.add(user)
            db.session.add(report)
            db.session.add(image)

            db.session.commit()

            flash(
                'User Report for username: {} generated. '.format(
                    form.username.data), 'success')
            return redirect(url_for('report', report_id=report.id))
        else:
            flash_errors(form)
            flash('ERROR! Report was not generated.', 'error')

    return render_template('upload.html', title='Upload', form=form)
示例#27
0
def due_days1():
    user = get_current_user()
    try:
        if not user:
            return redirect(url_for('home'))
    except AttributeError:
        return redirect(url_for('home'))
    teacher = get_current_teacher()
    reason = request.form.get('reason')
    form = PhotoForm(meta={'csrf': False})
    get = Attendance.query.filter_by(for_sabab=True).first()
    if form.validate_on_submit():
        filename = images.save(form.image.data)
        image_url = images.url(filename)
        add = reason_apset_days(student_id=user.id,
                                img_due_days=image_url,reason_due=reason,
                                date_abset=get.apset,group_id=get.group_id)
        db.session.add(add)
        db.session.commit()

    return render_template('student/Sababli_kun.html', user=user, teacher=teacher,form=form, get=get)
示例#28
0
def add_stock():
    """
    Add a stock to the database
    """
    check_admin()

    add_stock = True

    form = StockForm()
    if form.validate_on_submit():
        fil = images.save(request.files['img'])
        fil_url = images.url(fil)

        stock = Stock(
            name=form.name.data,
            details=form.details.data,
            purpose=form.purpose.data,
            unit_price=form.unit_price.data,
            image_filename=fil,
            image_url=fil_url,
        )

        try:
            # add item to the database
            db.session.add(stock)
            db.session.commit()
            flash('You have successfully added a new item.')
        except:
            # in case item is not added
            flash('Error: item was not added to database.')

        # redirect to items page
        return redirect(url_for('admin.list_stocks'))

    # load stock template
    return render_template('admin/stocks/stock.html',
                           action="Add",
                           add_stock=add_stock,
                           form=form,
                           title="Add Item")
示例#29
0
def register_plant():
    form = PlantRegistrationForm()
    if form.validate_on_submit():
        last_watered_datetime = datetime.combine(form.last_watered_date.data,
                                                 form.last_watered_time.data)

        filename = images.save(request.files['photo'])
        url = images.url(filename)

        plant = Plant(name=form.name.data,
                      location=form.location.data,
                      last_watered=last_watered_datetime,
                      image_filename=filename,
                      image_url=url)

        db.session.add(plant)
        db.session.commit()
        flash('Congratulations, new plant registered')
        return redirect(url_for('index'))
    return render_template('register_plant.html',
                           title='Register Plant',
                           form=form)
示例#30
0
def showPersons(region_name, clinic_id):
    form = NewPerson()
    if form.validate_on_submit():
        if not form.picture_url.data:
            filename = '-.png'
            url = 'images/-.png'
        else:
            filename = images.save(request.files['picture_url'])
            url = images.url(filename)
        newPerson = Person(name=form.name.data,
                           comments=form.comments.data,
                           picture_filename=filename,
                           picture_url=url,
                           phone=form.phone.data,
                           email=form.email.data,
                           department=form.department.data,
                           date_of_request=form.date_of_request.data,
                           date_of_request2=form.date_of_request2.data,
                           author=current_user,
                           region_name=region_name,
                           clinic_id=clinic_id)
        db.session.add(newPerson)
        db.session.commit()
        flash('Новый клиент "{}" добавлен!'.format(form.name.data))
        return redirect(
            url_for('clients.showPersons',
                    clinic_id=clinic_id,
                    region_name=region_name))
    persons = Person.query.filter_by(clinic_id=clinic_id).order_by(
        Person.last_visit.desc())
    clinic = Clinic.query.filter_by(id=clinic_id).one()
    return render_template("/clients/persons.html",
                           title='Клиенты',
                           persons=persons,
                           form=form,
                           region_name=region_name,
                           clinic=clinic)
示例#31
0
 def avatar_url(self):
     if self.avatar:
         return images.url(self.avatar)
     else:
         return '/static/images/thumb.jpg'
示例#32
0
def save_destination(form, destination=None, new=True):
    # PHOTOS
    try:
        request_featured_photo = request.files['featured_photo']
    except KeyError:
        request_featured_photo = False

    if request_featured_photo:
        if new:
            photo_folder_name = form.title.data + '-' + secrets.token_hex(16)
            featured_photo_with_folder = images.save(
                request.files['featured_photo'], folder=photo_folder_name)
            featured_photo = featured_photo_with_folder.split('/')[1]
            featured_photo_filename = featured_photo.split('.')[0]
            featured_photo_extension = featured_photo.split('.')[-1]
            photo_dir = os.path.join(
                current_app.config["UPLOADED_IMAGES_DEST"], photo_folder_name)

            photo_folder_url = images.url(featured_photo_with_folder).split(
                featured_photo)[0]

            current_app.q.enqueue(create_image_set, photo_dir, featured_photo)
        else:
            # Bruke tidligere skapt folder, og hente featured_photo fra form:
            photo_folder_name = destination.photo_folder_url.split(
                '/static/uploads/images/'
            )[-1]  # http://127.0.0.1:5000/static/uploads/images/Oskarshamn-7296b6784120247d3125ace582cdc17e/
            featured_photo_with_folder = images.save(
                request.files['featured_photo'], folder=photo_folder_name)
            featured_photo = featured_photo_with_folder.split('/')[1]
            featured_photo_filename = featured_photo.split('.')[0]
            featured_photo_extension = featured_photo.split('.')[-1]
            photo_dir = os.path.join(
                current_app.config["UPLOADED_IMAGES_DEST"], photo_folder_name
            )  # samma struktur som photo_dir: app/static/uploads/images/Oskarshamn-7296b6784120247d3125ace582cdc17e/
            # photo_folder_url = images.url(featured_photo_with_folder).split(featured_photo)[0]
            # Sende til enqueue
            current_app.q.enqueue(create_image_set, photo_dir, featured_photo)
            # Oppdatere befintlig destination med url/fil/extension
            # - Gjørs nedan

    # COUNTRY & CONTINENT
    country = pycountry_convert.country_alpha2_to_country_name(
        form.country.data)

    continent_code = pycountry_convert.country_alpha2_to_continent_code(
        form.country.data)
    continents = {
        'AF': 'Africa',
        'AN': 'Antarctica',
        'AS': 'Asia',
        'EU': 'Europe',
        'NA': 'North America',
        'OC': 'Oceania',
        'SA': 'South America'
    }
    continent = continents[continent_code]

    # Add new destination
    if new:
        d = Destination(title=form.title.data,
                        country=country,
                        continent=continent,
                        weather_ltd=form.weather_ltd.data,
                        weather_lng=form.weather_lng.data,
                        photo_folder_url=photo_folder_url,
                        featured_photo_filename=featured_photo_filename,
                        featured_photo_extension=featured_photo_extension,
                        description=form.description.data,
                        author=current_user)
        db.session.add(d)
        db.session.commit()
    else:
        destination.title = form.title.data
        destination.country = country
        destination.continent = continent
        destination.weather_ltd = form.weather_ltd.data
        destination.weather_ltd = form.weather_lng.data
        # destination.photo_folder_url = photo_folder_url  # trenger ikke oppdatere denne
        if request_featured_photo:
            destination.featured_photo_filename = featured_photo_filename
        if request_featured_photo:
            destination.featured_photo_extension = featured_photo_extension
        destination.description = form.description.data
        # edited by ??
        db.session.commit()

    if new:
        d = Destination.query.order_by(Destination.id.desc()).first()
    else:
        d = destination

    # Additional photos
    if request.files.getlist('additional_photos'):
        additional_photos_object = []
        for photo in request.files.getlist('additional_photos'):
            photo_folder_name = d.photo_folder_url.split(
                '/static/uploads/images/')[-1]
            additional_photo_folder_name = photo_folder_name + 'additional_photos'
            additional_photo_with_folder = images.save(
                photo, folder=additional_photo_folder_name)
            additional_photo = additional_photo_with_folder.split('/')[2]
            additional_photo_filename = additional_photo.split('.')[0]
            additional_photo_extension = additional_photo.split('.')[-1]
            photo_dir = os.path.join(
                current_app.config["UPLOADED_IMAGES_DEST"],
                additional_photo_folder_name)

            current_app.q.enqueue(create_image_set, photo_dir,
                                  additional_photo)

            additional_photos_object.append(
                AdditionalPhotos(
                    additional_photo_filename=additional_photo_filename,
                    additional_photo_extension=additional_photo_extension,
                    destination_id=d.id))
        db.session.bulk_save_objects(additional_photos_object)

    # COST
    cost_form_currency = form.cost_form_currency.data
    if cost_form_currency != 'EUR':  # EUR on default
        # Getting rate from ratesAPI
        payload = {'base': cost_form_currency, 'symbols': 'EUR'}
        api_currency_data = requests.get('https://api.ratesapi.io/api/latest',
                                         params=payload)

        if api_currency_data.status_code == 200:
            json_api_currency_data = api_currency_data.json()
            conversion_rate = json_api_currency_data['rates']['EUR']

            cost_form_currency = 'EUR'

            beer_at_establishment = Decimal(
                conversion_rate) * form.beer_at_establishment.data  # required
            coffee_at_establishment = Decimal(
                conversion_rate
            ) * form.coffee_at_establishment.data  # required
            restaurant_inexpensive_meal = Decimal(
                conversion_rate
            ) * form.restaurant_inexpensive_meal.data  # required
            groceries_one_week = Decimal(
                conversion_rate) * form.groceries_one_week.data  # required
            car_rent_one_week = \
                (Decimal(conversion_rate) * form.car_rent_one_week.data) if (type(form.car_rent_one_week.data) == Decimal) \
                else 0
            gas_one_liter = \
                (Decimal(conversion_rate) * form.gas_one_liter.data) if (type(form.gas_one_liter.data) == Decimal) else 0
            km_per_day = \
                (Decimal(conversion_rate) * form.km_per_day.data) if (type(form.km_per_day.data) == Decimal) else 0
            tent_per_day = \
                (Decimal(conversion_rate) * form.tent_per_day.data) if (type(form.tent_per_day.data) == Decimal) else None
            van_per_day = \
                (Decimal(conversion_rate) * form.van_per_day.data) if (type(form.van_per_day.data) == Decimal) else None
            camping_per_day = \
                (Decimal(conversion_rate) * form.camping_per_day.data) if (type(form.camping_per_day.data) == Decimal) \
                else None
            hostel_per_day = \
                (Decimal(conversion_rate) * form.hostel_per_day.data) if (type(form.hostel_per_day.data) == Decimal) \
                else None
            apartment_per_day = \
                (Decimal(conversion_rate) * form.apartment_per_day.data) if (type(form.apartment_per_day.data) == Decimal) \
                else None
            house_per_day = \
                (Decimal(conversion_rate) * form.house_per_day.data) if (type(form.house_per_day.data) == Decimal) else None
            hotel_per_day = \
                        (Decimal(conversion_rate) * form.hotel_per_day.data) if (type(form.hotel_per_day.data) == Decimal) else None
        else:
            beer_at_establishment = form.beer_at_establishment.data  # required
            coffee_at_establishment = form.coffee_at_establishment.data  # required
            restaurant_inexpensive_meal = form.restaurant_inexpensive_meal.data  # required
            groceries_one_week = form.groceries_one_week.data  # required
            car_rent_one_week = form.car_rent_one_week.data if (type(form.car_rent_one_week.data) == Decimal) \
                else 0
            gas_one_liter = form.gas_one_liter.data if (type(
                form.gas_one_liter.data) == Decimal) else 0
            km_per_day = form.km_per_day.data if (type(form.km_per_day.data)
                                                  == Decimal) else 0
            tent_per_day = form.tent_per_day.data if (type(
                form.tent_per_day.data) == Decimal) else None
            van_per_day = form.van_per_day.data if (type(form.van_per_day.data)
                                                    == Decimal) else None
            camping_per_day = form.camping_per_day.data if (type(
                form.camping_per_day.data) == Decimal) else None
            hostel_per_day = form.hostel_per_day.data if (type(
                form.hostel_per_day.data) == Decimal) else None
            apartment_per_day = form.apartment_per_day.data if (type(form.apartment_per_day.data) == Decimal) \
                else None
            house_per_day = form.house_per_day.data if (type(
                form.house_per_day.data) == Decimal) else None
            hotel_per_day = form.hotel_per_day.data if (type(
                form.hotel_per_day.data) == Decimal) else None
    else:
        beer_at_establishment = form.beer_at_establishment.data  # required
        coffee_at_establishment = form.coffee_at_establishment.data  # required
        restaurant_inexpensive_meal = form.restaurant_inexpensive_meal.data  # required
        groceries_one_week = form.groceries_one_week.data  # required
        car_rent_one_week = form.car_rent_one_week.data if (type(
            form.car_rent_one_week.data) == Decimal) else 0
        gas_one_liter = form.gas_one_liter.data if (type(
            form.gas_one_liter.data) == Decimal) else 0
        km_per_day = form.km_per_day.data if (type(form.km_per_day.data)
                                              == Decimal) else 0
        tent_per_day = form.tent_per_day.data if (type(form.tent_per_day.data)
                                                  == Decimal) else None
        van_per_day = form.van_per_day.data if (type(form.van_per_day.data)
                                                == Decimal) else None
        camping_per_day = form.camping_per_day.data if (type(
            form.camping_per_day.data) == Decimal) else None
        hostel_per_day = form.hostel_per_day.data if (type(
            form.hostel_per_day.data) == Decimal) else None
        apartment_per_day = form.apartment_per_day.data if (type(
            form.apartment_per_day.data) == Decimal) else None
        house_per_day = form.house_per_day.data if (type(
            form.house_per_day.data) == Decimal) else None
        hotel_per_day = form.hotel_per_day.data if (type(
            form.hotel_per_day.data) == Decimal) else None

    accomodations_form_data = {
        "tent_per_day": tent_per_day,
        "van_per_day": van_per_day,
        "camping_per_day": camping_per_day,
        "hostel_per_day": hostel_per_day,
        "apartment_per_day": apartment_per_day,
        "house_per_day": house_per_day,
        "hotel_per_day": hotel_per_day
    }

    for key in list(accomodations_form_data
                    ):  # Makes a list of al the keys in the dict
        if accomodations_form_data[key] is None:
            del accomodations_form_data[key]

    if accomodations_form_data:  # Checking so it's not empty
        cheapest_accomodation = min(accomodations_form_data,
                                    key=accomodations_form_data.get)
    else:  # if it is empty
        accomodations_form_data = {'no_info': 0}
        cheapest_accomodation = 'no_info'

    avg_weekly_cost = \
        3 * beer_at_establishment + \
        3 * coffee_at_establishment + \
        2 * restaurant_inexpensive_meal + \
        1 * groceries_one_week + \
        1 * car_rent_one_week + \
        7 * gas_one_liter * km_per_day + \
        7 * accomodations_form_data[cheapest_accomodation]

    avg_weekly_cost_rounded = int(avg_weekly_cost)

    if new:
        cost = Cost(
            cost_form_currency=cost_form_currency,
            beer_at_establishment=beer_at_establishment,
            coffee_at_establishment=coffee_at_establishment,
            restaurant_inexpensive_meal=restaurant_inexpensive_meal,
            groceries_one_week=groceries_one_week,
            car_rent_one_week=car_rent_one_week,
            gas_one_liter=gas_one_liter,
            km_per_day=km_per_day,
            tent_per_day=tent_per_day,
            van_per_day=van_per_day,
            camping_per_day=camping_per_day,
            hostel_per_day=hostel_per_day,
            apartment_per_day=apartment_per_day,
            house_per_day=house_per_day,
            hotel_per_day=hotel_per_day,
            accomodation_used_for_avg_weekly_cost=cheapest_accomodation,
            avg_weekly_cost=avg_weekly_cost_rounded,
            destination_id=d.id)
        db.session.add(cost)
    else:
        cost = Cost.query.filter(Cost.destination_id == d.id).first()
        cost.beer_at_establishment = beer_at_establishment
        cost.cost_form_currency = cost_form_currency
        cost.coffee_at_establishment = coffee_at_establishment
        cost.restaurant_inexpensive_meal = restaurant_inexpensive_meal
        cost.groceries_one_week = groceries_one_week
        cost.car_rent_one_week = car_rent_one_week
        cost.gas_one_liter = gas_one_liter
        cost.km_per_day = km_per_day
        cost.tent_per_day = tent_per_day
        cost.van_per_day = van_per_day
        cost.camping_per_day = camping_per_day
        cost.hostel_per_day = hostel_per_day
        cost.apartment_per_day = apartment_per_day
        cost.house_per_day = house_per_day
        cost.hotel_per_day = hotel_per_day
        cost.accomodation_used_for_avg_weekly_cost = cheapest_accomodation
        cost.avg_weekly_cost = avg_weekly_cost_rounded

    # ROUTES
    if new:
        routes = Routes(traditional=form.traditional.data,
                        sport=form.sport.data,
                        bouldering=form.bouldering.data,
                        main_discipline=form.main_discipline.data,
                        easy_routes=form.easy_routes.data,
                        intermediate_routes=form.intermediate_routes.data,
                        hard_routes=form.hard_routes.data,
                        very_hard_routes=form.very_hard_routes.data,
                        total_routes=form.total_routes.data,
                        total_trad=form.total_trad.data,
                        total_sport=form.total_sport.data,
                        total_boulders=form.total_boulders.data,
                        destination_id=d.id)
        db.session.add(routes)
    else:
        routes = Routes.query.filter(Routes.destination_id == d.id).first()
        routes.traditional = form.traditional.data
        routes.sport = form.sport.data
        routes.bouldering = form.bouldering.data
        routes.main_discipline = form.main_discipline.data
        routes.easy_routes = form.easy_routes.data
        routes.intermediate_routes = form.intermediate_routes.data
        routes.hard_routes = form.hard_routes.data
        routes.very_hard_routes = form.very_hard_routes.data
        routes.total_routes = form.total_routes.data
        routes.total_trad = form.total_trad.data
        routes.total_sport = form.total_sport.data
        routes.total_boulders = form.total_boulders.data
        # db.session.commit()  # her?

    # MONTHS
    if new:
        months = Months(january=form.january.data,
                        february=form.february.data,
                        march=form.march.data,
                        april=form.april.data,
                        may=form.may.data,
                        june=form.june.data,
                        july=form.july.data,
                        august=form.august.data,
                        september=form.september.data,
                        october=form.october.data,
                        november=form.november.data,
                        december=form.december.data,
                        destination_id=d.id)
        db.session.add(months)
    else:
        months = Months.query.filter(Months.destination_id == d.id).first()
        months.january = form.january.data
        months.february = form.february.data
        months.march = form.march.data
        months.april = form.april.data
        months.may = form.may.data
        months.june = form.june.data
        months.july = form.july.data
        months.august = form.august.data
        months.september = form.september.data
        months.october = form.october.data
        months.november = form.november.data
        months.december = form.december.data

    # ACCOMODATION
    if new:
        accomodation = Accomodation(tent=form.tent.data,
                                    van=form.van.data,
                                    hostel=form.hostel.data,
                                    camping=form.camping.data,
                                    apartment=form.apartment.data,
                                    house=form.house.data,
                                    hotel=form.hotel.data,
                                    destination_id=d.id)
        db.session.add(accomodation)
    else:
        accomodation = Accomodation.query.filter(
            Accomodation.destination_id == d.id).first()
        accomodation.tent = form.tent.data
        accomodation.van = form.van.data
        accomodation.hostel = form.hostel.data
        accomodation.camping = form.camping.data
        accomodation.apartment = form.apartment.data
        accomodation.house = form.house.data
        accomodation.hotel = form.hotel.data

    # APPROACH
    if new:
        approach = Approach(easy=form.easy.data,
                            moderate=form.moderate.data,
                            hardcore=form.hardcore.data,
                            destination_id=d.id)
        db.session.add(approach)
    else:
        approach = Approach.query.filter(
            Approach.destination_id == d.id).first()
        approach.easy = form.easy.data
        approach.moderate = form.moderate.data
        approach.hardcore = form.hardcore.data

    # CAR
    if new:
        car = Car(
            not_needed=form.not_needed.data,
            good_to_have=form.good_to_have.data,
            must_have=form.must_have.data,
            # rent_scooter_locally=form.rent_scooter_locally.data,
            # rent_car_locally=form.rent_car_locally.data,
            destination_id=d.id)
        db.session.add(car)
    else:
        car = Car.query.filter(Car.destination_id == d.id).first()
        car.not_needed = form.not_needed.data
        car.good_to_have = form.good_to_have.data
        car.must_have = form.must_have.data
        # car.rent_scooter_locally = form.rent_scooter_locally.data,
        # car.rent_car_locally = form.rent_car_locally.data

    db.session.commit()
    return True  # Hvordan returnere False hvis den failer?
示例#33
0
 def url(self):
     return images.url(self.filename)