def edit(id): product = select_row_from_table_by_id("products", id) images = [] try: product = product[0] except IndexError: abort(404) form = ProductForm() if request.method == 'GET': form.prepopulate_data(product) images = get_product_images(id) if form.validate_on_submit(): data = form.data.copy() data.pop("images", None) try: update("products", {"id": id}, data) except IntegrityError: form.name.errors = ('Product with given name already exists',) render_template('products/create.html', form=form) images = request.files.getlist("images") if images: for image in images: if image.filename: save_image(image, product.id) return redirect(url_for('product.edit', id=id)) return render_template('products/edit.html', form=form, images=images)
def photo(): query = create_query(search_param=request.args.get("search_param"), data=request.args.get("data")) auth_headers = { "Authorization": f"Client-ID {current_app.config['ACCESS_KEY']}", "Accept-Version": "v1", } res = (requests.get( current_app.config["RANDOM_URL"], headers=auth_headers, params=query) if query is not None else requests.get( current_app.config["RANDOM_URL"], headers=auth_headers)) if res.status_code == 200: try: img_url = res.json()["urls"]["small"] h = requests.head(img_url) content_type = h.headers.get("content-type") if is_image(content_type): r = requests.get(img_url) if r.status_code == 200: file_ext = content_type.split("/")[1] file_name = res.json()["id"] + "." + file_ext save_image(img_name=file_name, img_content=r.content) return render_template("photo.html", filename=file_name) else: return render_template("415.html"), 415 except (KeyError, OSError, ImageSaveError, Exception): return render_template("500.html"), 500 elif res.status_code == 404: return render_template("404.html"), 404 else: return render_template("external_error.html"), res.status_code
def upload_client_avatar(client_id): data = request.get_json() if not data: return jsonify(status="failed", message="No Data Sent!") if not data.get('type'): return jsonify(status="failed", message="Image type required!") if not data.get('img'): return jsonify(status="failed", message="Image data not sent!") if data.get('type').lower() not in Config.ALLOWED_EXTENSIONS: return jsonify(status="failed", message="Extension not supported!") client = Client.query.get(client_id) if not client: return jsonify(status='failed', message='Admin Not Found') unique_filename = str(uuid.uuid4()) + '.' + data['type'].lower() if client.img: delete_file(client.img, Config.AVATAR_UPLOAD_FOLDER) save_image( unique_filename, data['img'], Config.AVATAR_UPLOAD_FOLDER, Config.AVATAR_SIZE, True ) client.img = unique_filename db.session.commit() return jsonify( status='success', message='Client Avatar Upload', data=ClientSchema().dump(client) )
def restaurant_add(request): form = RestaurantForm(request.POST or None) group_restaurant = Group.objects.get(pk=settings.RESTAURANTS_GROUP_PK) if not request.user.is_superuser and group_restaurant not in request.user.groups.all( ): return utils.denied(request) if form.is_valid(): for i in ["midi1", "midi2", "midi3", "midi4", "midi5"]: if i in request.FILES: content = Content() content.name = i + " - " + str(form.cleaned_data["date"]) content.user = request.user content.content_type = "I" content.content_url = "image" content.state = "P" content.duration = 7 content.begin_date = timezone.datetime.combine( form.cleaned_data["date"], timezone.datetime(1, 1, 1, hour=10).time()) content.end_date = timezone.datetime.combine( form.cleaned_data["date"], timezone.datetime(1, 1, 1, hour=14).time()) content.feed = Feed.objects.get( pk=settings.RESTAURANTS_FEED_PK) validator(request.FILES[i]) content.save() utils.save_image(request.FILES[i], content, request.user) for i in ["soir1", "soir2", "soir3", "soir4", "soir5"]: if i in request.FILES: content = Content() content.name = i + " - " + str(form.cleaned_data["date"]) content.user = request.user content.content_type = "I" content.content_url = "image" content.state = "P" content.duration = 7 content.begin_date = timezone.datetime.combine( form.cleaned_data["date"], timezone.datetime(1, 1, 1, hour=14).time()) content.end_date = timezone.datetime.combine( form.cleaned_data["date"], timezone.datetime(1, 1, 1, hour=20).time()) content.feed = Feed.objects.get( pk=settings.RESTAURANTS_FEED_PK) validator(request.FILES[i]) content.save() utils.save_image(request.FILES[i], content, request.user) return redirect(reverse("content_list", args=[content.feed.pk])) else: return render(request, 'app/restaurants.html', {"form": form})
def update_user_profile_picture( *, db: Session = Depends(deps.get_db), user_id: str, image: UploadFile = File(...), current_user: models.User = Depends(deps.get_current_user), ) -> Any: """ Update a user's profile picture """ if current_user.id == user_id or ( (admin := crud.admin.get(db, current_user.id)) and schemas.AdminPermissions(admin.permissions).is_allowed("user")): if image.content_type not in ("image/png", "image/jpeg"): raise UnsupportedMediaTypeException( detail="Profile pictures can only be PNG or JPG images") if user := crud.user.get(db, user_id): filename = save_image(image) logging.info( f"User {current_user.id} ({current_user.email}) has updated their profile picture from" f"{current_user.profile_picture} to {filename}") return crud.user.update( db, db_obj=user, obj_in=schemas.UserUpdate(profile_picture=filename))
def content_create_image(request): form = ContentFormImage(request.POST or None) if not request.user.is_superuser: form.fields["feed"].queryset = Feed.objects.filter( submitter_group__in=request.user.groups.all()) if form.is_valid(): form.instance.user = request.user form.instance.content_type = "I" form.instance.content_url = "image" form.instance.state = 'P' validator(request.FILES['file']) content = form.save() utils.save_image(request.FILES['file'], content, request.user) return redirect(reverse("content_list", args=[content.feed.pk])) else: return render(request, 'app/add_content.html', locals())
def create_product(): form = ProductForm() if form.validate_on_submit(): data = form.data.copy() data.pop("images", None) try: product_id = insert_into_table('products', data) except IntegrityError: form.name.errors = ('Product with given name already exists',) return render_template('products/create.html', form=form) images = request.files.getlist("images") if images: for image in images: save_image(image, product_id) return redirect(url_for('product.list')) return render_template('products/create.html', form=form)
def edit_post(): post_form = PostForm() post_id = request.args.get('post') img_url = None if post_form.validate_on_submit() and 'image' in request.files: if post_id and Post.query.get(post_id): post = Post.query.get(post_id) post.title = post_form.title.data post.body = post_form.body.data img = Image.query.filter_by(post_id=post_id).first() images = save_image(request.files.getlist('image')) for url in images: img.url = url[0] img.url_t = url[1] db.session.add(img) db.session.add(post) flash('文章修改成功') else: post = Post(title=post_form.title.data, body=post_form.body.data, author=current_user._get_current_object()) db.session.add(post) images = save_image(request.files.getlist('image')) for url in images: img = Image(url=url[0], url_t=url[1], post=post) db.session.add(img) flash('文章创建成功') return redirect(url_for('.index')) if post_id: post = Post.query.get_or_404(post_id) post_form.title.data = post.title post_form.body.data = post.body img_url = post.images.first().url_t return render_template('create_post.html', post_form=post_form, img_url=img_url)
def create_post(): data = request.get_json() if not data: return jsonify(status='failed', message="No Data Sent") if not data.get("title"): return jsonify(status="failed", message="Title is Required") unique_filename = '' if data.get("img"): if not data['img'].get("src"): return jsonify(status="failed", message="Image data not sent!") if data['img'].get('type').lower() not in Config.ALLOWED_EXTENSIONS: return jsonify(status="failed", message="Extension not supported!") unique_filename = str(uuid.uuid4()) + '.' + data['img']['type'].lower() save_image( unique_filename, data['img'].get("src"), Config.POST_UPLOAD_FOLDER, Config.BLOG_SIZE ) post = Post() post.admin_id = 1 post.title = data.get('title') post.link = data.get('link') post.abstract = data.get('abstract') post.content = data.get('content') post.img = unique_filename post.category_id = data.get('category_id') post.is_sponsored = data.get('is_sponsored') db.session.add(post) db.session.commit() return jsonify( status="success", message='Post Created', data=PostSchema().dump(post) )
def editproduct(id): form = ProductForm() if id == 0: product = Product() product.stock = 0 else: product = Product.query.get(id) if form.validate_on_submit(): product.description = form.description.data product.active = form.active.data product.highlight = form.highlight.data if form.file.data: save_image(product, form.file, app) if id == 0: db.session.add(product) db.session.commit() flash(_('Gespeichert')) return redirect(url_for('main.manageproducts')) form.description.data = product.description form.active.data = product.active form.highlight.data = product.highlight return render_template('admin/edit_product.html', product=product, form=form)
def save_images(id_servico, lista): try: delete_servicos = ServicoImage.query.filter_by( servico_id=id_servico).all() for servico in delete_servicos: ServicoImage.query.filter_by(id=servico.id).delete() Image.query.filter_by(id=servico.image.id).delete() delete_image(servico.image.name + '.' + servico.image.ext, 'servicos') new_list = [] i = 0 for data in lista: name_img = 'servico-$id-image-$i' name_img = name_img.replace('$id', str(id_servico)) name_img = name_img.replace('$i', str(i)) name = name_img + '.' + data['image']['ext'] if data['image'].get('base64'): save_image(name, 'servicos', data['image']['base64']) del data['image']['base64'] image = Image(**data['image']) servico_image = ServicoImage(**data) servico_image.image = image servico_image.image.name = name_img servico_image.servico_id = id_servico new_list.append(servico_image) db.session.add(servico_image) i += 1 db.session.commit() response = ServicoImageSchema(many=True).dump(new_list) db.session.remove() return response, False except Exception as e: return False, e.__str__()
def get_photo(): incoming_query = request.args.to_dict() valid, msg = validate_query(incoming_query) if not valid: response = jsonify(msg) response.status_code = 400 return response outgoing_query = {} if incoming_query: for k, v in incoming_query.items(): outgoing_query = create_query(search_param=k, data=v) auth_headers = { "Authorization": f"Client-ID {current_app.config['ACCESS_KEY']}", "Accept-Version": "v1", } res = (requests.get( current_app.config["RANDOM_URL"], headers=auth_headers, params=outgoing_query, ) if outgoing_query else requests.get(current_app.config["RANDOM_URL"], headers=auth_headers)) if res.status_code == 200: try: img_url = res.json()["urls"]["small"] h = requests.head(img_url) content_type = h.headers.get("content-type") if is_image(content_type): r = requests.get(img_url) if r.status_code == 200: file_ext = content_type.split("/")[1] file_name = res.json()["id"] + "." + file_ext save_image(img_name=file_name, img_content=r.content) payload = { "thumb_url": os.path.join("http://localhost:5000/static", file_name), "message": "Click on the link provided to view a thumbnail of the photo", } response = jsonify(payload) return response except (ImageSaveError, KeyError): response = {"status_code": 500} return response elif res.status_code == 404: payload = { "message": "Please try again with a different search.", "error": res.json()["errors"], } response = jsonify(payload) response.status_code = 404 return response else: payload = { "message": "An error occurred while trying to communicate with the external server. Please check the error message and try again", "error": res.json()["errors"], } response = jsonify(payload) response.status_code = res.status_code return response