upload.py
2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
import colander
from deform import (
Form,
widget,
FileData,
)
from deform.interfaces import FileUploadTempStore
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from opensipkd.tools import (
get_ext,
get_settings,
dict_to_str,
SaveFile,
)
# from unggah import DbUpload
def route_list(request, p={}):
q = dict_to_str(p)
return HTTPFound(location=request.route_url('upload-logo', _query=q))
##########
# Unggah #
##########
# class UploadLogo(SaveFile):
# def save(self, fs):
# input_file = fs.file
# ext = get_ext(fs.filename)
# fullpath = self.create_fullpath(ext)
# output_file = open(fullpath, 'wb')
# input_file.seek(0)
# while True:
# data = input_file.read(2 << 16)
# if not data:
# break
# output_file.write(data)
# output_file.close()
# return fullpath
tmpstore = FileUploadTempStore()
class AddSchema(colander.Schema):
upload = colander.SchemaNode(
FileData(),
widget=widget.FileUploadWidget(tmpstore),
title='Unggah')
def get_form(schema_cls):
schema = schema_cls()
return Form(schema, buttons=('simpan', 'batalkan'))
@view_config(route_name='upload-logo',
renderer='templates/upload.pt',
permission='upload-logo')
def view_file(request):
form = get_form(AddSchema)
if request.POST:
if 'simpan' in request.POST:
settings = get_settings()
input_file = request.POST['upload'].file
filename = request.POST['upload'].filename.lower()
ext = get_ext(filename).lower()
if ext.lower() != '.png':
request.session.flash('File harus format png', 'error')
return dict(form=form.render())
_here = os.path.dirname(__file__)
static_path = os.path.join(os.path.dirname(_here), 'static')
if filename.startswith('logo'):
fname = f"logo{ext}"
elif filename.startswith('background'):
fname = f"background{ext}"
else:
fname=filename
fullpath = os.path.join( static_path, 'img/'+fname)
output_file = open(fullpath, 'wb')
input_file.seek(0)
while True:
data = input_file.read(2 << 16)
if not data:
break
output_file.write(data)
return route_list(request)
return dict(form=form.render())