def create(self): banner = Banner(user_id=session.get("id"), title=self.title.data, image=upload_image(self.image.data), smallimage=upload_image(self.smallimage.data), url=self.url.data, status=self.status.data) db.session.add(banner) db.session.commit() return banner
def reply_to_reply(board_name, boards, post_id, reply_id, ip): p = PostCompiler(request, 'form_text', 'form_img', require_img=False) if p.valid: upload_image(p.img) create_reply_to_reply(post_id, reply_id, p.text, p.img, p.user, ip) flash(REPLY_MSG) return redirect( url_for('board_post', board_name=board_name, post_id=post_id))
def system_category_add(): form = CategoryForm() if request.method == "POST": if form.validate_on_submit(): data = form.data result = Category(name=data['name'], keywords=data['keywords'], description=data['description'], image=upload_image(data['image']), smallimage=upload_image(data['smallimage'])) db.session.add(result) db.session.commit() flash("新增成功", "ok") return render_template("admin/system/category/category_add.html", form=form)
def ask(): from utils import file_is_image, upload_image, add_question, post_to_fb user = get_logged_in_user() token = request.form.get('csrf_token') if not validate_csrf_token(token): return redirect(url_for('index')) title = request.form.get('title') body = request.form.get('body') image = request.files.get('image') if image: if not file_is_image(image): flash('Invalid Image Uploaded') return redirect(url_for('questions.user_questions')) image_url = upload_image(user, image) else: image_url = None _anonymous = request.form.get('anonymous') if _anonymous: anonymous = True else: anonymous = False add_question(user_id=user.id, title=title, body=body, image_url=image_url, anonymous=anonymous) post_to_fb(title) #TODO: notify admin flash( 'Your question has been received. Our doctors will contact you shortly' ) return redirect(url_for('questions.user_questions'))
def selfie2anime(): img_id = os.environ['id'] result_id = os.environ['result'] parser = get_parser() args = parser.parse_args("--phase test".split()) with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: #sess.reuse_variables() gan = UGATIT(sess, args) # build graph gan.build_model() # download target img download_path = os.path.join(img_path, img_id) download_image(images_bucket, img_id, dest=download_path) dataset_tool.create_from_images(record_path, img_path, True) # os.remove(del_record) img = gan.infer(download_path) image_url = upload_image(img, result_id) return download_path, img
def portfolio_update(site, host, netloc, csrf, logged_in, user_id_logged_in): """ Edit portfolio post url """ # POST parameters site_id = int(request.POST.get('site')) user_id = int(request.POST.get('user')) portfolio_id = int(request.POST.get('portfolio')) title = request.POST.get('title') description = request.POST.get('description') # Portfolio try: portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site) except Portfolio.DoesNotExist: return dict(status=False, info='Portfólio não encontrado') # Update upload portfolio image if request.files.get('upload'): img_path = site.get_image_path(IMAGE_PATH) original_file = os.path.join(img_path, portfolio.original_image) normalized_file = os.path.join(img_path, portfolio.normalized_image) thumbnail_file = os.path.join(img_path, portfolio.thumbnail_image) upload_response = upload_image(request, original_file, normalized_file, thumbnail_file, ORIG_SIZE, NORM_SIZE, THUMB_SIZE) if not upload_response['status']: return upload_response # Upload data portfolio.title = title portfolio.description = description portfolio.save() # Images data img_url = '%s/%s/' % (host, IMAGE_DIR) original_url = img_url + portfolio.original_image normalized_url = img_url + portfolio.normalized_image thumbnail_url = img_url + portfolio.thumbnail_image # Lista de portfolios atualizada try: portfolio_list = template('portfolios_admin_list.html', site=site, host=host, csrf=csrf, img_url=img_url) except Exception as exp: return dict(status=False, info='%s' % exp) # Return OK return dict(status=True, info='Atualizado com sucesso', portfolio_id=portfolio.get_id(), original=original_url, normalized=normalized_url, thumbnail=thumbnail_url, portfolio_list=portfolio_list)
def form_valid(self, form): try: with transaction.atomic(using="tiger_admin"): obj = form.save() if form.cleaned_data["logo_url"] is not None: directory = "%s%s" % (settings.LOGO_ROOT, object.id) logo_url = upload_image(form.cleaned_data["logo_url"], directory) object.logo_url = logo_url object.save() video_url = form.cleaned_data["video_url"] name = video_url.split("=")[-1] models.Video.objects.create( name=name, description="", video_url=video_url, host_url="%s/%s.mp4" % (obj.id, obj.id), company=obj ) tag = form.cleaned_data["tag"] models.CompanyTag.objects.get_or_create(company=obj, tag=tag) except Exception as e: logger.error( "create Website fail, roll back, website %s, operate by %s. Exception: %s", form.cleaned_data["name"], self.request.user, str(e), ) # add error in page return super(CompanyCreateView, self).form_invalid(form) logger.info("Website %s has been created by %s", form.cleaned_data["name"], self.request.user) return HttpResponseRedirect(self.get_success_url())
def edit(self, banner): banner.user_id = session.get("id") banner.title = self.title.data if self.image.data: if banner.image is not None: del_image(banner.image) banner.image = upload_image(self.image.data) if self.smallimage.data: if banner.smallimage is not None: del_image(banner.smallimage) banner.smallimage = upload_image(self.smallimage.data) banner.url = self.url.data banner.status = self.status.data banner.update_time = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") db.session.add(banner) db.session.commit() return banner
def picture_update(site, host, netloc, csrf, logged_in, user_id_logged_in): """ Edit picture post url """ # POST parameters site_id = int(request.POST.get('site')) user_id = int(request.POST.get('user')) portfolio_id = int(request.POST.get('portfolio')) picture_id = int(request.POST.get('picture')) title = request.POST.get('title') description = request.POST.get('description') # Portfolio try: portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site) except Portfolio.DoesNotExist: return dict(status=False, info='Portfólio não encontrado') # Picture try: picture = Picture.get(Picture.id == picture_id, Picture.site == site, Picture.portfolio == portfolio) except Picture.DoesNotExist: return dict(status=False, info='Imagem não encontrada') # Update upload picture image if request.files.get('upload'): img_path = site.get_image_path(IMAGE_PATH) original_file = os.path.join(img_path, picture.original_image) normalized_file = os.path.join(img_path, picture.normalized_image) thumbnail_file = os.path.join(img_path, picture.thumbnail_image) upload_response = upload_image(request, original_file, normalized_file, thumbnail_file, ORIG_SIZE, NORM_SIZE, THUMB_SIZE) if not upload_response['status']: return upload_response # Upload data picture.title = title picture.description = description picture.save() # Images data img_url = '%s/%s/' % (host, IMAGE_DIR) original_url = img_url + picture.original_image normalized_url = img_url + picture.normalized_image thumbnail_url = img_url + picture.thumbnail_image # Lista de pictures atualizada try: picture_list = template('pictures_admin_list.html', site=site, host=host, csrf=csrf, portfolio=portfolio, img_url=img_url) except Exception as exp: return dict(status=False, info='%s' % exp) # Return OK return dict(status=True, info='Atualizada com sucesso', picture_id=picture.get_id(), original=original_url, normalized=normalized_url, thumbnail=thumbnail_url, picture_list=picture_list)
def form_valid(self, form): form.instance.company_id = self.kwargs["pk"] if form.cleaned_data["url"] is not None: directory = "%s%s" % (settings.PDF_ROOT, self.kwargs["pk"]) pdf_url = upload_image(form.cleaned_data["url"], directory) form.instance.url = pdf_url obj = form.save() logger.info("PDF %s has been created by %s", obj.name, self.request.user) return HttpResponseRedirect(self.get_success_url())
def create(self): friend = Friends( name=self.name.data, website_logo=upload_image(self.website_logo.data), website=self.website.data, is_show=self.is_show.data ) db.session.add(friend) db.session.commit() return friend
def post_form(board_name, boards, ip): board_id = get_board_id(board_name) p = PostCompiler(request, 'form_text', 'form_img') if p.valid: if upload_image(p.img): create_post(board_id, p.text, p.img, p.user, ip) flash(POST_MSG) return redirect(url_for('board_catalog', board_name=board_name))
def create(self): ad = Ad( name=self.name.data, image=upload_image(self.image.data), path=self.path.data, status=self.status.data ) db.session.add(ad) db.session.commit() return ad
def form_valid(self, form): obj = form.save() if form.cleaned_data["url"] is not None: if form.cleaned_data["url"] != obj.url: directory = "%s%s" % (settings.PDF_ROOT, obj.id) pdf_url = upload_image(form.cleaned_data["url"], directory) obj.url = pdf_url obj.save() logger.info("PDF %s has been created by %s", obj.name, self.request.user) return HttpResponseRedirect(self.get_success_url())
def edit(self, friend): friend.name = self.name.data if self.website_logo.data: if friend.website_logo is not None: del_image(friend.website_logo) friend.website_logo = upload_image(self.website_logo.data) friend.website = self.website.data friend.is_show = self.is_show.data db.session.add(friend) db.session.commit() return friend
def system_category_edit(id=None): if id is None: result = {"status": 0, "data": "没有数据"} return jsonify(result) form = CategoryForm() result = Category.query.get_or_404(id) if request.method == "POST": if form.validate_on_submit(): data = form.data result.name = data['name'] result.keywords = data['keywords'] result.description = data['description'] result.image = upload_image(data['image']) result.smallimage = upload_image(data['smallimage']) db.session.add(result) db.session.commit() flash("保存成功", "ok") return render_template("admin/system/category/category_edit.html", form=form, result=result)
def edit(self, ad): ad.name = self.name.data if self.image.data: if ad.image is not None: del_image(ad.image) ad.image = upload_image(self.image.data) ad.path = self.path.data ad.status = self.status.data ad.update_time = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") db.session.add(ad) db.session.commit() return ad
def process_data(): try: name = request.form['name'] description = request.form['description'] image = request.files['image'] utils.upload_image(image, image.filename) print "getting data from image..." try: rekognize.analyze(image, image.filename) except Exeption as e: print 'Failed to add image: Error on line {}'.format( sys.exc_info()[-1].tb_lineno), type(e).__name__, e dataset = Dataset(name, description, "data") db.session.add(dataset) db.session.commit() except Exception as e: print 'Failed to add image: Error on line {}'.format( sys.exc_info()[-1].tb_lineno), type(e).__name__, e pass return redirect(url_for('index'))
def get_later_movie_info(city, app): r = requests.get(LATER_URL.format(city)) soup = BeautifulSoup(r.text) items = soup.find(id='showing-soon').findAll('div', {'item'}) for i in items: h = i.find('h3').find('a') url = h.attrs['href'] title = h.text content = '|'.join([li.text for li in i.findAll('li')[:4]]) image_url = i.find('a').find('img').attrs.get('src', '') # SA好变态, 感觉是防盗链了,下同 image_url = upload_image(image_url, 'thumb', app) yield u'<{url}|{title}> {content}'.format(**locals()), gen_attachment( content, image_url, image_type='thumb', title=title, title_link=url)
def get_later_movie_info(city): r = requests.get(LATER_URL.format(city)) soup = BeautifulSoup(r.text) items = soup.find(id="showing-soon").findAll("div", {"item"}) for i in items: h = i.find("h3").find("a") url = h.attrs["href"] title = h.text content = "|".join([li.text for li in i.findAll("li")[:4]]) image_url = i.find("a").find("img").attrs.get("src", "") # SA好变态, 感觉是防盗链了,下同 image_url = upload_image(image_url, "thumb") yield u"<{url}|{title}> {content}".format(**locals()), gen_attachment( content, image_url, image_type="thumb", title=title, title_link=url )
def form_valid(self, form): try: pk = self.kwargs.get("pk", 0) product = get_object_or_404(models.Product, pk=pk) if form.cleaned_data["is_cover"]: models.Gallery.objects.filter(product_id=pk).update(is_cover=False) directory = "%s%s" % (settings.MEDIA_ROOT, pk) image_url = upload_image(form.cleaned_data["image_url"], directory) form.instance.image_url = image_url form.instance.product = product form.save() except IntegrityError: form.on_duplicate_error() return self.form_invalid(form) return HttpResponseRedirect(self.get_success_url())
def get_later_movie_info(city): r = requests.get(LATER_URL.format(city)) soup = BeautifulSoup(r.text) items = soup.find(id='showing-soon').findAll('div', {'item'}) for i in items: h = i.find('h3').find('a') url = h.attrs['href'] title = h.text content = '|'.join([li.text for li in i.findAll('li')[:4]]) image_url = i.find('a').find('img').attrs.get('src', '') # SA好变态, 感觉是防盗链了,下同 image_url = upload_image(image_url, 'thumb') yield u'<{url}|{title}> {content}'.format(**locals()), gen_attachment( content, image_url, image_type='thumb', title=title, title_link=url)
def handle_friend_message(ctx): wechat_id = ctx.get('sender_id') if not wechat_id: return user_id = '/'.join(('wechat', g.wechat_client, wechat_id)) avatar_url = None resp = wechat.get_avatar.get(params={ 'client': g.wechat_client_encoded, 'id': wechat_id }, stream=True) if resp.ok: avatar_url = upload_image(resp.raw) payload = {'user_id': user_id} if 'sender_name' in ctx: payload['name'] = g.wechat_client + ': ' + ctx['sender_name'] if avatar_url: payload['avatar'] = {'type': 'avatar', 'image_url': avatar_url} resp = session.post(api('users'), json=payload) if not resp.ok: return image_url = None if ctx.get('format') == 'media' \ and ctx.get('media_mime', '').startswith('image'): image_url = upload_image(base64.b64decode(ctx['media_data'])) body = ctx['content'] if image_url: body = '[图片](%s)' % image_url reply_or_initiate(user_id, body)
def post_molt(): auth = require_auth(request) if auth: crab = api_utils.get_crab(auth["crab_id"]) if crab: molt_content = request.form.get("content") molt_image_link = request.form.get("image") molt_image = request.files.get("image") molt_source = request.form.get("source", "Crabber API") image_verified = False if molt_image_link: return abort(400, "Images must be submitted as files, not text.") if molt_image: if molt_image.filename != "": if molt_image and utils.allowed_file(molt_image.filename): image_verified = True else: return abort( 400, "There was a problem with the uploaded image." ) else: return abort(400, "Image filename is blank. Aborting.") if molt_content: if len(molt_content) <= config.MOLT_CHAR_LIMIT: if image_verified: molt_image = utils.upload_image(molt_image) if molt_image is None: return abort(400, "Image is corrupted.") new_molt = crab.molt( molt_content, image=molt_image, source=molt_source ) else: new_molt = crab.molt(molt_content, source=molt_source) return api_utils.molt_to_json(new_molt), 201 else: return abort( 400, description="Molt length must be less than or equal " f"to {config.MOLT_CHAR_LIMIT} characters.", ) else: return abort(400, description="Missing required content.") else: return abort(400, description="The authorized user no longer exists.") else: return abort(401, description="This endpoint requires authentication.")
def form_valid(self, form): try: with transaction.atomic(using="tiger_admin"): if form.cleaned_data["dis_order"] is None: form.instance.dis_order = self.object.dis_order if not form.instance.dis_order: form.instance.dis_order = 0 obj = form.save() if form.cleaned_data["logo_url"] is not None: if form.cleaned_data["logo_url"] != obj.logo_url: directory = "%s%s" % (settings.LOGO_ROOT, obj.id) logo_url = upload_image(form.cleaned_data["logo_url"], directory) obj.logo_url = logo_url obj.save() try: video = models.Video.objects.get(company=obj) if form.cleaned_data["video_url"] != video.video_url: video_url = form.cleaned_data["video_url"] name = video_url.split("=")[-1] models.Video.objects.filter(company=obj).update( name=name, description="", video_url=video_url, host_url="%s/%s.mp4" % (obj.id, obj.id) ) except models.Video.DoesNotExist: video_url = form.cleaned_data["video_url"] name = video_url.split("=")[-1] models.Video.objects.filter(company=obj).update( name=name, description="", video_url=video_url, host_url="%s/%s.mp4" % (obj.id, obj.id) ) tag = form.cleaned_data["tag"] models.CompanyTag.objects.filter(company=obj).update(tag=tag) except Exception as e: logger.error( "update Website fail, roll back, website %s, operate by %s. Exception: %s", form.cleaned_data["name"], self.request.user, str(e), ) # add error in page return super(CompanyUpdateView, self).form_invalid(form) logger.info("Website %s has been updated by %s", form.cleaned_data["name"], self.request.user) return HttpResponseRedirect(self.get_success_url())
def get_current_movie_info(city): r = requests.get(CURRENT_URL.format(city)) soup = BeautifulSoup(r.text) items = soup.find(id="nowplaying").find("ul", {"class": "lists"}).findAll("li", {"class": "poster"}) count = 0 for i in items: if count >= 10: continue img = i.find("img") title = img.attrs.get("alt", "") content = "|".join([li.text for li in i.findAll("li")[:4]]) url = i.find("a").attrs.get("href", "") image_url = img.attrs.get("src", "") image_url = upload_image(image_url, "thumb") count += 1 yield u"<{url}|{title}>".format(**locals()), gen_attachment( content, image_url, image_type="thumb", title=title, title_link=url )
def create(self): article = Article( top=self.top.data, user_id=session.get("id"), category_id=self.category_id.data, title=self.title.data, url_title=self.url_title.data, keywords=self.keywords.data, description=self.description.data, image=upload_image(self.image.data), content=self.content.data, markdown=self.markdown.data, relationship=self.relationship.data, status=self.status.data, create_time=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) db.session.add(article) db.session.commit() return article
def edit_molt(molt_ID): molt = api_utils.get_molt(molt_ID) if molt: auth = require_auth(request) if auth: crab = api_utils.get_crab(auth["crab_id"]) if crab: molt_content = request.form.get("content") molt_image_link = request.form.get("image") molt_image = request.files.get("image") image_verified = False if molt_image_link: return abort(400, "Images must be submitted as files, not text.") if molt_image: if molt_image.filename != "": if molt_image and utils.allowed_file(molt_image.filename): image_verified = True else: return abort( 400, "There was a problem with the uploaded image." ) else: return abort(400, "Image filename is blank. Aborting.") if molt.editable: if image_verified: if molt.editable: molt_image = utils.upload_image(molt_image) molt.edit(content=molt_content, image=molt_image) elif molt_content: molt.edit(content=molt_content) else: return abort(400, description="Missing required content.") # Return edited Molt return api_utils.molt_to_json(molt), 201 else: return abort(400, description="Molt is not editable.") else: return abort(400, description="The authorized user no longer exists.") else: return abort(401, description="This endpoint requires authentication.") else: return abort(404, description="No Molt with that ID.")
def get_current_movie_info(city, app): r = requests.get(CURRENT_URL.format(city)) soup = BeautifulSoup(r.text) items = soup.find(id='nowplaying').find('ul', {'class': 'lists'}).findAll( 'li', {'class': 'poster'}) count = 0 for i in items: if count >= 10: continue img = i.find('img') title = img.attrs.get('alt', '') content = '|'.join([li.text for li in i.findAll('li')[:4]]) url = i.find('a').attrs.get('href', '') image_url = img.attrs.get('src', '') image_url = upload_image(image_url, 'thumb', app) count += 1 yield u'<{url}|{title}>'.format(**locals()), gen_attachment( content, image_url, image_type='thumb', title=title, title_link=url)
def get_current_movie_info(city): r = requests.get(CURRENT_URL.format(city)) soup = BeautifulSoup(r.text) items = soup.find(id='nowplaying').find('ul', {'class': 'lists'}).findAll( 'li', {'class': 'poster'}) count = 0 for i in items: if count >= 10: continue img = i.find('img') title = img.attrs.get('alt', '') content = '|'.join([li.text for li in i.findAll('li')[:4]]) url = i.find('a').attrs.get('href', '') image_url = img.attrs.get('src', '') image_url = upload_image(image_url, 'thumb') count += 1 yield u'<{url}|{title}>'.format(**locals()), gen_attachment( content, image_url, image_type='thumb', title=title, title_link=url)
def add_game(): form = AddGameForm() if request.method == 'POST': if form.validate_on_submit(): data = { 'title': request.form.get('game_title'), 'alias': request.form.get('game_alias'), "player_rate": request.form.get('player_rate'), "bgg_rate": request.form.get('bgg_rate'), "player_min": request.form.get('player_min'), "player_max": request.form.get('player_max'), "language": request.form.get('language'), "type": request.form.get('game_type'), 'img_name': upload_image(request.files['img_name']) } new_post = GameModel(**data) db.session.add(new_post) db.session.commit() return redirect('/games') return render_template('add_game.html', form=form)
def edit(self, article): article.top = self.top.data article.user_id = session.get("id") article.category_id = self.category_id.data article.title = self.title.data article.url_title = self.url_title.data article.keywords = self.keywords.data article.description = self.description.data if self.image.data: if article.image is not None: del_image(article.image) article.image = upload_image(self.image.data) article.content = self.content.data article.markdown = self.markdown.data article.relationship = self.relationship.data article.update_time = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") article.status = self.status.data db.session.add(article) db.session.commit() return article
def select_image(path_to_images: str, interface_type: str = "Simple"): """ Show interface to choose the image, and load it Args: path_to_images (dict): path ot folder with images interface_type (dict): mode of the interface used Returns: (status, image) status (int): 0 - if everything is ok 1 - if there is error during loading of image file 2 - if user hasn't uploaded photo yet """ image_names_list = get_images_list(path_to_images) if len(image_names_list) < 1: return 1, 0 else: if interface_type in ["Professional", "Ultimate"]: image_name = st.sidebar.selectbox( "Select an image:", image_names_list + ["Upload my image"]) else: image_name = st.sidebar.selectbox("Select an image:", image_names_list) if image_name != "Upload my image": try: image = load_image(image_name, path_to_images) return 0, image except cv2.error: return 1, 0 else: try: image = upload_image() return 0, image except cv2.error: return 1, 0 except AttributeError: return 2, 0
# download target img download_path = os.path.join(img_path, img_id) download_image(images_bucket, img_id, dest=download_path) dataset_tool.create_from_images(record_path, img_path, True) # os.remove(del_record) img = gan.infer(download_path) image_url = upload_image(img, result_id) return download_path, img if __name__ == '__main__': num_steps = 1000 if 'steps' in os.environ: num_steps = int(os.environ['steps']) input_img, s2a_img = selfie2anime() project_real_images("record","/proj",1,10, stylegan_model_pkl, num_steps) result_fname = f'image0000-step{num_steps}.png' for x in os.listdir('/proj/img'): fname = os.path.basename(x) image_url = upload_image(f'/proj/img/{x}', "animeresult", fname) print(fname) image_url = upload_image(f'/proj/img/{result_fname}', "animeresult", 'result.png')