本文整理汇总了Python中forms.UploadForm类的典型用法代码示例。如果您正苦于以下问题:Python UploadForm类的具体用法?Python UploadForm怎么用?Python UploadForm使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UploadForm类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload
def upload():
form = UploadForm()
if form.validate_on_submit():
try:
name = form.name.data
filename = images.save(form.image.data, folder=unicode(g.user.id))
#Checks if Image is new or exists before commit changes
image = Image.query.filter_by(name = form.name.data).first()
if image is None:
image = Image(name = name, filename = filename, uid=g.user.id)
message = "%r image uploaded." % name
else:
old_file = image.filename
image.filename = filename
message = "%r image changed." % name
db.session.add(image)
db.session.commit()
flash(message)
return redirect(url_for('index'))
except UploadNotAllowed:
flash("Not allowed to upload image")
else:
filename = None
return render_template('upload.html',
form = form,
filename = filename)
示例2: index
def index():
subtitle = "Transfer books to Internet Archive"
form = UploadForm(request.form)
if request.method == "POST":
if form.validate():
book_id = html_escape(form.book_id.data)
email = html_escape(form.email.data) if form.email.data not in (None, "") else ""
book = bridge.fields(form.library_id.data, book_id, email)
book_id = book.Id if book.Id not in (None, "") else book_id
redis = redis_py.Redis()
redis_key3 = keys.redis_key3
book_key = "%s:%s:%s" % (redis_key3, form.library_id.data, book_id)
library_url_key = book_key + ":library_url"
redis_py.set(library_url_key, form.book_id.data, True)
redis.expire(library_url_key, 60 * 15)
verification_status_no = book.verify_fields()
if verification_status_no != 0:
flash(error_msg(verification_status_no, book))
return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
else:
if redundant_request(book) == True:
flash(error_msg(50))
return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
book_info = bridge.book_info(form.library_id.data, book_id)
if isinstance(book_info, (int, long, float, complex)):
flash(error_msg(book_info))
return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
confirm_resp = make_response(minify(render_template("confirm.html", book_info=book_info, form=form)))
uuid = urandom(32).encode("hex")
confirm_resp.set_cookie("bub_session", uuid)
store_request(book, uuid)
return confirm_resp
return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
else:
return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
示例3: handleImagePopAdd
def handleImagePopAdd(request, addForm, field, template="form/popmediaadd.html"):
if not request.method == "POST":
f = UploadForm()
ctx = {'form': f, 'field': field}
return render(request, template, ctx)
f = UploadForm(request.POST, request.FILES)
if not f.is_valid() and not request.FILES['file'].name.endswith('.svg'):
ctx = {'form': f, 'field': field}
return render(request, template, ctx)
file = request.FILES['file']
store_in_s3(file.name, file.read())
p = Image(url="http://%s.s3.amazonaws.com/%s" % (bucket, file.name))
if isinstance(request.user, AnonymousUser):
p.user = User.objects.get(username="Anonymous")
else:
p.user = User.objects.get(username=request.user)
if request.POST['artist']:
p.artist = User.objects.get(pk=request.POST['artist'])
p.save()
newObject = p
# Self destruction:
if newObject:
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' %\
(escape(newObject._get_pk_val()), escape(newObject)))
示例4: upload_img
def upload_img(request):
form = UploadForm()
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
if not os.path.isdir(app_settings['DIC_UPLOAD_FULL']):
os.makedirs(app_settings['DIC_UPLOAD_FULL'])
filename = "%s.%s" % (get_file_code(), form.cleaned_data['image'].name.split('.')[-1])
filepath = os.path.join(app_settings['DIC_UPLOAD_FULL'], filename)
fileurl = '%s%s' % (app_settings['DIC_IMG_URL'], filename)
f = open(filepath, 'wb+')
for chunk in form.cleaned_data['image'].chunks():
f.write(chunk)
f.close()
image = Image.open(filepath)
if image.size[0] > app_settings['DIC_IMG_SIZE'][0] and image.size[1] > app_settings['DIC_IMG_SIZE'][1]:
image.thumbnail(app_settings['DIC_IMG_SIZE'], Image.ANTIALIAS)
print filepath
image.save(filepath)
width_b = image.size[0]
height_b = image.size[1]
width = int(request.GET.get('w'))
height = int(request.GET.get('h'))
return HttpResponseRedirect('%s?filename=%s&w=%s&h=%s&wb=%s&hb=%s' % (reverse('dic-crop-img'), filename, width, height, width_b, height_b))
return render_to_response('django_img_crop/upload-img.html', {'form': form, 'is_popup': True}, context_instance=RequestContext(request))
示例5: upload
def upload():
if g.user.files.count() >=100:
flash("You can't upload more than 100 files")
return redirect(url_for('index'))
form=UploadForm()
if form.validate_on_submit():
file=form.file.data
filename = secure_filename(file.filename)
#create sha1 of file
url=sha1(file.read()).hexdigest()
f=File.query.filter_by(url=url).first()
if f is None:
file.seek(0)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], url))
else:
if f.own==g.user:
flash('File already exist in your storage(%s)'%f.name)
else:
flash("File already exist(%s in %s's storage)"%(f.name,f.own.nickname))
newfile=File(url=url,timestamp=datetime.datetime.utcnow(),name=filename,own=g.user)
db.session.add(newfile)
db.session.commit()
return redirect(url_for('index'))
return render_template('upload.html',form=form)
示例6: upload_file
def upload_file():
form = UploadForm()
if request.method == "POST":
if form.validate() == False:
flash("All fields are required.")
return render_template("upload.html", form=form)
else:
file = request.files["filename"]
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
msg = Message(form.subject.data, sender="[email protected]", recipients=["[email protected]"])
msg.body = """
From: %s <%s>
Subject: %s
PeakCaller: %s
SupplementalInfo: %s
File Name: %s
""" % (
form.name.data,
form.email.data,
form.subject.data,
form.peakcaller.data,
form.supplementalinfo.data,
filename,
)
mail.send(msg)
return redirect(url_for("uploaded_file", filename=filename))
elif request.method == "GET":
return render_template("upload.html", form=form)
示例7: upload_file
def upload_file(request):
resp = {}
url = str(request.get_full_path())
pid = url.split("/")[-1]
try:
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
#获取表单信息
xlsfile = form.cleaned_data['Filedata']
filename = xlsfile.name
#写入数据库
uf = Upload(Filedata = xlsfile, uptime = datetime.datetime.now())
uf.save()
filepath = uf.Filedata
uipath = unicode(str(filepath), "utf8")
uipath = os.path.join(settings.MEDIA_ROOT,uipath)
excel_table_byindex(request,file= uipath, pid = pid)
resp['success'] = True
else:
form = UploadForm()
except Exception,e:
info = "%s" % (sys.exc_info()[1])
resp['success'] = False
resp['message'] = info
示例8: index
def index():
form = UploadForm()
if request.method == 'POST' and form.validate_on_submit():
bucket_name = app.config['BUCKET_NAME']
key = uuid.uuid4()
filename = str(key) + '.ics'
fullpath = '/' + bucket_name + '/' + filename
upfile = request.files['csv_file']
try:
ics_file = converter.convert(upfile)
except (ContentError, HeadersError, DatetimeFormatError) as error:
flash(error, 'danger')
return render_template('index.html', form=form, links=base_links,
links_title=links_title)
else:
mtype = 'text/calendar'
with gcs.open(fullpath, 'w', content_type=mtype) as w:
w.write(ics_file)
session['key'] = key
return redirect(url_for('success'))
for field, errors in form.errors.items():
for error in errors:
msg = "Whups! {}".format(error)
flash(msg)
return render_template('index.html', form=form, links=base_links,
links_title=links_title)
示例9: judge_action
def judge_action(request):
form = UploadForm(request.POST)
if form.is_valid():
data = form.cleaned_data
context = data['context']
if '_auth_user_id' in request.session:
user_id = request.session['_auth_user_id']
user = User.objects.get(id=user_id)
else:
user = None
if request.FILES.has_key('image'):
image = request.FILES['image']
else:
image = None
if image != None and image.size > 3 * 1024 * 1024:
return render_to_response('result.jinja', {'state':'2', 'message':u'图片最大3M', 'url':'/main/upload'}, RequestContext(request))
item = Item.objects.create(
user=user,
context=context,
time=datetime.now(),
image=image,
status=0,
agree=random.randint(100, 200),
disagree=random.randint(0, 50),
score=int(time.time() / (60 * 60) * 1000),
)
item.save()
return render_to_response('result.jinja', {'state':'1', 'message':u'上传成功', 'url':'/main/upload'}, RequestContext(request))
else:
for field in form:
if field.errors:
return render_to_response('result.jinja', {'state':'2', 'message':field.errors, 'url':'/main/upload'}, RequestContext(request))
示例10: editCustomerCodes
def editCustomerCodes(customer_id=None):
form = UploadForm()
if form.validate_on_submit() and form.filename.data:
file = form.filename.data
filename = 'cust_' + str(customer_id) + '.csv'
file.save(os.path.join(CUSTOMER_CODES_PATH, filename))
try:
parse_csv(os.path.join(CUSTOMER_CODES_PATH, filename))
flash(gettext('CSV uploaded and processed sucessfully.'))
except:
flash(gettext('Upload unsuccessful! File could not be parsed!'))
redirect('/settings/editcustomercodes')
def_file_path = getCustomerCodesDefinitionFiles(customer_id)
if def_file_path:
try:
def_file_data = parse_csv(def_file_path[0])
except:
def_file_data = []
else:
def_file_data = []
customer = Customer.query.get(customer_id)
return render_template('/settings/editcustomercodes.html',
title=gettext("Edit Customer Codes"),
customer=customer,
def_file_data=def_file_data,
form=form)
示例11: upload
def upload():
form = UploadForm()
if form.validate():
if form.title.data == "":
flash("Must include title")
return redirect(request.referrer + "#add_form")
filename = secure_filename(form.photo.data.filename)
pos = filename.rfind('.')
#flash(str(filename[pos + 1: ] in ALLOWED_EXTENSIONS))
if pos < 0 or (pos >= 0 and (not filename[pos + 1 : ] in ALLOWED_EXTENSIONS)):
flash("Error: Invalid extension, pleases use jpg or png")
return redirect(request.referrer + '#add_form')
form.photo.file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
pin = Pin(title=form.title.data,
img=filename,
dscrp=form.dscrp.data,
orig=True,
date=datetime.now(),
pinner=current_user.to_dbref(),
repins=0,
like_count=0)
pin.save()
flash("Image has been uploaded.")
else:
flash("Image upload error.")
return redirect(request.referrer + "#add_form" or url_for("index"))
示例12: upload
def upload(request):
if request.method == "POST":
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
subject = form.cleaned_data["subject"]
message = form.cleaned_data["message"]
attach2 = request.FILES["attach"]
sender = form.cleaned_data["sender"]
cc_myself = form.cleaned_data["cc_myself"]
recipient = ["[email protected]"]
if cc_myself:
recipient.append(sender)
try:
mail = EmailMessage(subject, message, sender, recipient, ["EMAIL_ADDRESS"])
mail.attach(attach2.name, attach2.read(), attach2.content_type)
mail.send()
except:
return "Attachment error"
return HttpResponseRedirect(reverse("feel_home"))
else:
# Dynamic initial values.
form = UploadForm(initial={"sender": "Email address"})
return render(request, "upload.html", {"form": form})
示例13: get_form
def get_form(self):
if 'key' in request.args:
if request.endpoint == "photos":
self.page.assets['new_photo'] = request.args['key']
self.form = PostForm()
self.form.photo.data = self.page.assets['new_photo']
self.template = "post_form.html"
else:
self.page.assets['new_photo'] = request.args['key']
self.form = EditForm()
self.form.photo.data = self.page.assets['new_photo']
self.form.about_me.data = g.user.about_me
self.form.nickname.data = g.user.nickname
self.template = "update_photo.html"
else:
if request.is_xhr:
if request.endpoint == "photos":
self.form = UploadForm(prefix="").s3_upload_form()
else:
if request.endpoint == "photos":
key = "user-images/" + str(g.user.id) + "/" + str(uuid4()) + ".jpeg"
message = "Select New Photo"
redirect_url = request.base_url
else:
key = "user-images/" + str(g.user.id) + "/profile_image/" + str(uuid4()) + ".jpeg"
message = "Change Profile Picture"
redirect_url = request.base_url
self.form = UploadForm(key=key, message=message, redirect_url=redirect_url).s3_upload_form()
示例14: upload
def upload():
form = UploadForm()
if request.method == 'POST' and form.validate():
g.user.avatar = form.uri.data
db_session.add(g.user.avatar)
db_session.commit()
return redirect(url_for("home", username=g.user.username))
return render_template("upload.html", form=form, user=g.user)
示例15: upload
def upload():
if not current_user.is_admin():
return 'Not Authorized', 500
form = UploadForm(request.form)
if form.validate_on_submit():
#save and process it
pass
return render_template('upload.html', form=form)