Beispiel #1
0
def application(env, start_response):
    formdata = FieldStorage(environ=env, fp=env['wsgi.input'])
    response_texts = []
    for key in formdata.keys():
        data = formdata[key]
        # if data.type == 'application/octet-stream':
        if getattr(data, '_binary_file', None) and data.filename:
            filename = data.filename
            filesize = 0
            opath = os.path.join('uploads', filename)
            with open(opath, 'wb', 10240) as ofile:
                for chunk in buffer(data.file):
                    filesize += len(chunk)
                    ofile.write(chunk)
            response_texts.append('%s <%s bytes>' % (filename, filesize))
        else:
            """在这里处理非文件的表单数据"""
            text = '%s: %s' % (data.name, data.value)
            response_texts.append(text)

    response_body = html % {'message': ', '.join(response_texts)}
    response_body = response_body.encode()

    status = '200 OK'
    response_headers = [
        ('Content-Type', 'text/html'),
        ('Content-Length', str(len(response_body)))
    ]

    start_response(status, response_headers)
    return [response_body]
Beispiel #2
0
def StoredHandler(environ, start_response):
	from cgi import FieldStorage
	import cgitb; cgitb.enable(display=0, logdir="/tmp")
	form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
	print(form.keys())

	start_response('200 Ok', [('Content-type', 'text/javascript')])

	if "oper" not in form:
		#print("Bad Request")
		return [json.dumps([False, 'Bad Request'])]

	method = environ['REQUEST_METHOD'].upper()
	if method == 'GET' or method == 'HEAD':
		return [json.dumps([False, 'bad request'])]
	oper = form['oper']
	print(oper)
	section = form.getfirst('roof', 'imsto')
	# section = form['section'] if form.has_key('section') else 'imsto'

	imsto = load_imsto(section)
	if oper.value == 'delete':
		id = form['id']
		r = imsto.delete(id.value)
		print r
		return [json.dumps(r)]
	if oper.value == 'add':

		if "new_file" not in form:
			return [json.dumps([False, 'please select a file'])]

		new_file = form['new_file']
		if new_file is None:
			return [json.dumps([False, 'invalid upload field'])]
		# print(type(new_file))
		result = []
		if type(new_file) == type([]):
			for f in new_file:
				print('%r %r %r %r %r %r' % (f.name, f.filename, f.type, f.disposition, f.file, f.length))
				r = imsto.store(f.file, ctype=f.type, name=f.filename)
				print 'store: %r, result %r' % (f.name, r)
				if type(r) == type([]):
					result.append(r)
				else:
					result.append(False)
		else:
			f = new_file
			print('single file %r %r' % (f.name, f.filename))
			try:
				result = imsto.store(f.file, ctype=f.type, name=f.filename)
				print 'store: %r, result %r' % (f.name, result)
			except Exception, e:
				result = [False, e.message]
				print "\n".join(get_traceback()) + "\n"
			
		if hasattr(imsto, 'close'):
			imsto.close()
		
		return [json.dumps(result)]
Beispiel #3
0
def handle_action(environ, start_response, config):
    global available_tables
    fields = FieldStorage(fp = environ['wsgi.input'], environ = environ)
    action = fields.getfirst('a')
    datadir = config['datadir']
    sessiondir = config['sessiondir']

    if action in ['plot', 'png', 'svg', 'pdf']:

        settings = {}
        for k in fields.keys():
            if k[0] in 'xyzcmsorntwhfgl':
                settings[k] = fields.getfirst(k).strip().decode('utf8', errors = 'ignore')

        images = make_plot(settings, config)
        for k, v in images.items():
            images[k] = 'plots/' + basename(v)

        if action == 'plot':
            return serve_json(images, start_response)

        elif action in ['png', 'svg', 'pdf']:
            return serve_plot(images[action], start_response, config)



    elif action == 'list':
        if not available_tables or time() - available_tables[0] > 86400:
            available_tables = time(), ctplot.plot.available_tables(datadir)
        return serve_json(available_tables[1], start_response)

    elif action == 'save':
        id = fields.getfirst('id').strip()
        if len(id) < 8: raise RuntimeError('session id must have at least 8 digits')
        data = fields.getfirst('data').strip()
        with open(os.path.join(sessiondir, '{}.session'.format(id)), 'w') as f:
            f.write(data.replace('},{', '},\n{'))
        return serve_json('saved {}'.format(id), start_response)

    elif action == 'load':
        id = fields.getfirst('id').strip()
        if len(id) < 8: raise RuntimeError('session id must have at least 8 digits')
        try:
            with open(os.path.join(sessiondir, '{}.session'.format(id))) as f:
                return serve_plain(f.read(), start_response)
        except:
            return serve_json('no data for {}'.format(id), start_response)

    elif action == 'newid':
        id = randomChars(16)
        while os.path.isfile(os.path.join(sessiondir, '{}.session'.format(id))):
            id = randomChars(16)
        return serve_plain(id, start_response)

    else:
        raise ValueError('unknown action {}'.format(action))
Beispiel #4
0
    def go(self):
        self.cookies = {}
        self.error = ''
        form = FieldStorage()
        if not list(form.keys()):
            self.show_form()
            return

        if 'person' in form:
            print(form.keys())
            self.who = form['person'].value.strip().title()
            if self.who == '':
                self.error = 'Your name is required.(blank)'
        else:
            self.error = 'Your name is required.(missing)'

        self.cookies['user'] = unquote(
            form['cookie'].value.strip()) if 'cookie' in form else ''

        if 'lang' in form:
            lang_data = form['lang']
            if isinstance(lang_data, list):
                self.langs = [eachLang.value for eachLang in lang_data]
            else:
                self.langs = [lang_data.value]
        else:
            self.error = 'At least one language required'

        if 'upfile' in form:
            upfile = form['upfile']
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''

        if not self.error:
            self.doResult()
        else:
            self.show_error()
Beispiel #5
0
    def go(self):
        "run the AdvCGI and show in the web"
        self.cookies = {}
        self.error = ''
        form = FieldStorage()

        if form.keys() == []:
            self.show_form()
            return
       
        if form.has_key('personName'):
            self.cookies['user'] = unquote(strip(form['personName'].value))
            self.user = strip(form['personName'].value)
            result = self.checkDB()
            if result > 0:   #greater than 0 mean name had exist
                self.error = 'Your name %s is exist!' % (self.user)
            if self.user == '':
                self.error = 'Your name is required. (blacnk)'
        else:
            self.cookies['user'] = ''
            self.error = 'Your name is required. (missing)'

        if form.has_key('personPassword'):
            self.passwd = strip(form['personPassword'].value)
            if self.passwd == '':
                self.error = 'Your password is required. (blank)'
        else:
            self.error = 'Your password is required. (missing)'
        if form.has_key('personPassword2'):
            self.passwd2 = strip(form['personPassword2'].value)
            if self.passwd2 == '':
                self.error = 'Your password is required to input again. (blank)'
        else:
            self.error = 'Your password is required to input again. (missing)'

        if len(self.passwd) > 0 and len(self.passwd2) > 0:
            if self.passwd != self.passwd2: 
                self.error = 'Your passwords are not the same!'

        if form.has_key('upfile'):
            upfile = form['upfile']
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
                self.fn = ''
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''

        if not self.error:
            self.do_results()
        else:
            self.show_error()
Beispiel #6
0
    def go(self):
        "run the AdvCGI and show in the web"
        self.cookies = {}
        self.error = ''
        form = FieldStorage()

        if form.keys() == []:
            self.show_form()
            return

        if form.has_key('personName'):
            self.cookies['user'] = unquote(strip(form['personName'].value))
            self.user = strip(form['personName'].value)
            result = self.checkDB()
            if result > 0:  #greater than 0 mean name had exist
                self.error = 'Your name %s is exist!' % (self.user)
            if self.user == '':
                self.error = 'Your name is required. (blacnk)'
        else:
            self.cookies['user'] = ''
            self.error = 'Your name is required. (missing)'

        if form.has_key('personPassword'):
            self.passwd = strip(form['personPassword'].value)
            if self.passwd == '':
                self.error = 'Your password is required. (blank)'
        else:
            self.error = 'Your password is required. (missing)'
        if form.has_key('personPassword2'):
            self.passwd2 = strip(form['personPassword2'].value)
            if self.passwd2 == '':
                self.error = 'Your password is required to input again. (blank)'
        else:
            self.error = 'Your password is required to input again. (missing)'

        if len(self.passwd) > 0 and len(self.passwd2) > 0:
            if self.passwd != self.passwd2:
                self.error = 'Your passwords are not the same!'

        if form.has_key('upfile'):
            upfile = form['upfile']
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
                self.fn = ''
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''

        if not self.error:
            self.do_results()
        else:
            self.show_error()
Beispiel #7
0
    def go(self):  # determine which page to return
        try:
            self.cookies = {}
            self.error = ''
            form = FieldStorage()
            if form.keys() == []:
                self.showForm()
                return

            if form.has_key('person'):
                logger.info("form['person'].value is:%s" %
                            (form['person'].value, ))
                self.who = capwords(strip(form['person'].value))
                if self.who == '':
                    self.error = 'Your name is required. (blank)'
            else:
                self.error = 'Your name is required. (missing)'

            if form.has_key('cookie'):
                logger.info("form['cookie'].value is:%s" %
                            (form['cookie'].value, ))
                self.cookies['user'] = unquote(strip(\
                                form['cookie'].value))
            else:
                self.cookies['user'] = ''

            self.langs = []
            if form.has_key('lang'):
                langdata = form['lang']
                if type(langdata) == type([]):
                    for eachLang in langdata:
                        self.langs.append(eachLang.value)
                else:
                    self.langs.append(langdata.value)
            else:
                self.error = 'At least one language required.'

            if form.has_key('upfile'):
                upfile = form["upfile"]
                self.fn = upfile.filename or ''
                if upfile.file:
                    self.fp = upfile.file
                else:
                    self.fp = StringIO('(no data)')
            else:
                self.fp = StringIO('(no file)')
                self.fn = ''

            if not self.error:
                self.doResult()
            else:
                self.showError()
        except:
            logger.exception("Error!!!")
Beispiel #8
0
    def go(self):  # determine which page to return
        self.cookies = {}
        self.error = ''
        form = FieldStorage()

        # come in from the null or return
        if form.keys() == []:
            self.showForm()
            return

        # come in from the form only
        # get the person
        if form.has_key('person'):
            self.who = capwords(strip(form['person'].value))
            if self.who == '':
                self.error = 'Your name is required. (blank)'
        else:
            self.error = 'Your name is required. (missing)'

        # the cookie field
        if form.has_key('cookie'):
            self.cookies['user'] = unquote(strip(form['cookie'].value))
        else:
            self.cookies['user'] = ''

        # the language
        self.langs = []
        if form.has_key('lang'):
            langdata = form['lang']
            if type(langdata) == type([]):
                for eachLang in langdata:
                    self.langs.append(eachLang.value)
            else:
                self.langs.append(langdata.value)
        else:
            self.error = 'At least one language required.'

        # resolve the file
        if form.has_key('upfile'):
            upfile = form["upfile"]
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''

        # error or not
        if not self.error:
            self.doResults()
        else:
            self.showError()
Beispiel #9
0
   def go(self):                # determine which page to return
       self.cookies = {}
       self.error = ''
       form = FieldStorage()
       if form.keys() == []:
           self.showForm()
           return

    #    if form.has_key('person'):
       if 'person' in form:
        #    self.who = capwords(strip(form['person'].value))
           self.who=form['person'].value.strip().title()
           if self.who == '':
               self.error = 'Your name is required. (blank)'
       else:
           self.error = 'Your name is required. (missing)'

    #    if form.has_key('cookie'):
       if 'cookie' in form:
           self.cookies['user'] = unquote(form['cookie'].value.strip())
       else:
           self.cookies['user'] = ''

       self.langs = []
    #    if form.has_key('lang'):
       if 'lang' in form:
           langdata = form['lang']
           if type(langdata) == type([]):
               for eachLang in langdata:
                   self.langs.append(eachLang.value)
           else:
               self.langs.append(langdata.value)
       else:
           self.error = 'At least one language required.'

    #    if form.has_key('upfile'):
       if 'upfile' in form:
           upfile = form["upfile"]
        #    print(AdvCGI.header+upfile.filename)
           self.fn = upfile.filename or ''
           if upfile.file:
               self.fp = upfile.file
               
           else:
               self.fp = StringIO('(no data)')
       else:
           self.fp = StringIO('(no file)')
           self.fn = ''

       if not self.error:
           self.doResults()
       else:
           self.showError()
Beispiel #10
0
def debug_form_contents(form: cgi.FieldStorage,
                        to_stderr: bool = True,
                        to_logger: bool = False) -> None:
    """
    Writes the keys and values of a CGI form to ``stderr``.
    """
    for k in form.keys():
        text = f"{k} = {form.getvalue(k)}"
        if to_stderr:
            sys.stderr.write(text)
        if to_logger:
            log.info(text)
Beispiel #11
0
def print_env(environ, start_response):
	"""list environ items"""
	import os
	print(os.environ)
	from cgi import FieldStorage
	form = FieldStorage(environ=environ)
	#print(form.keys())
	for k in form.keys():
		print ('k: %s' % k)
		f = form[k]
		print (f)
	start_response('200 OK', [('Content-Type', 'text/plain')])
	return ['\n'.join(['%s: %r' % item for item in environ.items()])]
Beispiel #12
0
    def do_POST(self):
        form = FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST',
                         'CONTENT_TYPE':self.headers['Content-Type'],
                         })

        self.post = {}
        for name in form.keys():
            self.post[name] = form[name].value

        return self.do_GET()
Beispiel #13
0
    def do_POST(self):
        form = FieldStorage(fp=self.rfile,
                            headers=self.headers,
                            environ={
                                'REQUEST_METHOD': 'POST',
                                'CONTENT_TYPE': self.headers['Content-Type'],
                            })

        self.post = {}
        for name in form.keys():
            self.post[name] = form[name].value

        return self.do_GET()
Beispiel #14
0
    def go(self):
        self.error = ''

        form = FieldStorage()

        if form.keys() == []:
            #s('calling showForm()\n')
            self.showForm()
            return

        if form.has_key('person'):
            self.who = capwords(strip(form['person'].value))
            if self.who == '':
                self.error = 'Your name is required. (blank)'
        else:
            self.error = 'Your name is required. (missing)'

        if form.has_key('cookie'):
            self.cookies['user'] = unquote(strip(form['cookie'].value))
        else:
            self.cookies['user'] = ''

        self.langs = []
        if form.has_key('lang'):
            langdata = form['lang']
            if type(langdata) == type([]):
                for eachLang in langdata:
                    self.langs.append(eachLang.value)
            else:
                self.langs.append(langdata.value)
        else:
            self.error = 'At least one language required.'

        if form.has_key('upfile'):
            upfile = form["upfile"]
            self.fn = upfile.filename or ''
            #s('filename is %s??\n' % self.fn)
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''

        if not self.error:
            #s('calling doResults()\n')
            self.doResults()
        else:
            #s('calling showError()\n')
            self.showError()
Beispiel #15
0
        def go(self):
                self.error = ''

                form = FieldStorage()

                if form.keys() == []:
                    #s('calling showForm()\n')
                    self.showForm()
                    return

                if form.has_key('person'):
                        self.who = form['person'].value.strip().title()
                        if self.who == '':
                                self.error = 'Your name is required. (blank)'
                else:
                        self.error = 'Your name is required. (missing)'

                if form.has_key('cookie'):
                        self.cookies['user'] = unquote(form['cookie'].value.strip())
                else:
                        self.cookies['user'] = ''

                self.langs = []
                if form.has_key('lang'):
                        langdata = form['lang']
                        if type(langdata) == type([]):
                                for eachLang in langdata:
                                        self.langs.append(eachLang.value)
                        else:
                                self.langs.append(langdata.value)
                else:
                        self.error = 'At least one language required.'

                if form.has_key('upfile'):
                        upfile = form["upfile"]
                        self.fn = upfile.filename or ''
                        #s('filename is %s??\n' % self.fn)
                        if upfile.file:
                                self.fp = upfile.file
                        else:
                                self.fp = StringIO('(no data)')
                else:
                        self.fp = StringIO('(no file)')
                        self.fn = ''

                if not self.error:
                        #s('calling doResults()\n')
                        self.doResults()
                else:
                        #s('calling showError()\n')
                        self.showError()
Beispiel #16
0
    def go(self):
        """
        Dynamic generate the HTML page
        """
        self.cookies = {}
        self.error = ""
        form = FieldStorage()

        if not form.keys():
            self.show_form()
            return

        if form.has_key('person'):
            self.who = form['person'].value.strip().title()
            if self.who == "":
                self.error = "Your name is required. (blank)"
        else:
            self.error = "Your name is required. (missing)"

        if form.has_key('cookie'):
            self.cookies['user'] = unquote(form['cookie'].value.strip())
        else:
            self.cookies['user'] = ""

        self.langs = []
        if form.has_key('lang'):
            lang_data = form['lang']

            if isinstance(lang_data, list):
                for eachLang in lang_data:
                    self.langs.append(eachLang.value)
            else:
                self.langs.append(lang_data)
        else:
            self.error = 'At least one language required.'

        if form.has_key('upfile'):
            upfile = form['upfile']
            self.fn = upfile.filename or ""
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
        else:
            self.fp = StringIO('(no file)')
            self.fn = ""

        if not self.error:
            self.do_results()
        else:
            self.show_error()
Beispiel #17
0
 def parse_body(self):
     content_type, _ = self.content_type
     if content_type == 'application/json':
         self._body = json.loads(self.get_raw_body())
     elif content_type == 'application/x-www-form-urlencoded':
         self._body = dict(parse.parse_qsl(self.get_raw_body()))
     elif content_type == 'multipart/form-data':
         fs = FieldStorage(self.environ['wsgi.input'], environ=self.environ)
         self._body, self._uploads = {}, {}
         for name in fs.keys():
             if fs[name].filename is None:
                 self._body[name] = fs[name].value
             else:
                 self._uploads[name] = fs[name]
Beispiel #18
0
def stored_process(environ, start_response):
	from cgi import FieldStorage
	import cgitb; cgitb.enable(display=0, logdir="/tmp")
	form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
	print(form.keys())

	start_response('200 Ok', [('Content-type', 'text/javascript')])

	if "oper" not in form:
		#print("Bad Request")
		return [json.dumps([False, 'Bad Request'])]

	method = environ['REQUEST_METHOD'].upper()
	if method == 'GET' or method == 'HEAD':
		return [json.dumps([False, 'bad request'])]
	oper = form['oper']
	print(oper)
	from store import ImSto
	imsto = ImSto()
	if oper.value == 'delete':
		id = form['id']
		return [json.dumps(imsto.delete(id.value))]
	if oper.value == 'add':

		if "new_file" not in form:
			return [json.dumps([False, 'please select a file'])]

		new_file = form['new_file']
		if new_file is None:
			return [json.dumps([False, 'invalid upload field'])]
		print(type(new_file))
		result = []
		if type(new_file) == type([]):
			for f in new_file:
				print('%r %r %r %r %r %r' % (f.name, f.filename, f.type, f.disposition, f.file, f.length))
				id = imsto.store(f.file, ctype=f.type, name=f.filename)
				print('new_id: %r' % id)
				result.append(id)
		else:
			f = new_file
			print('single file %r %r' % (f.name, f.filename))
			id = imsto.store(f.file, ctype=f.type, name=f.filename)
			print('new_id: %r' % id)
			result = id
		if hasattr(imsto, 'close'):
			imsto.close()
		
		return [json.dumps(result)]
	else:
		return [json.dumps([False, 'invalid operation'])]
Beispiel #19
0
    def do_POST(self):
        form = FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={
                "REQUEST_METHOD": "POST",
                "CONTENT_TYPE": self.headers["Content-Type"],
            },
        )

        self.post = {}
        for name in form.keys():
            self.post[name] = form[name].value

        return self.do_GET()
Beispiel #20
0
    def do_POST(self):
        form = FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={
                "REQUEST_METHOD": "POST",
                "CONTENT_TYPE": self.headers["Content-Type"],
            },
        )

        self.post = {}
        for name in form.keys():
            self.post[name] = form[name].value

        return self.do_GET()
Beispiel #21
0
    def go(self):                # determine which page to return
        self.cookies = {}
        self.error = ''
        form = FieldStorage()
        if form.keys() == []:
            self.showForm()
            return
 
        if 'person' in form:
            self.who = capwords(form['person'].value.strip())
            if self.who == '':
                self.error = 'Your name is required. (blank)'
        else:
            self.error = 'Your name is required. (missing)'
 
        if 'cookie' in form:
            self.cookies['user'] = unquote(form['cookie'].value.strip())
        else:
            self.cookies['user'] = ''
 
        self.langs = []
        if 'lang' in form:
            langdata = form['lang']
            if isinstance(langdata, list):
                for eachLang in langdata:
                    self.langs.append(eachLang.value)
            else:
                self.langs.append(langdata.value)
        else:
            self.error = 'At least one language required.'
 
        if 'upfile' in form:
            upfile = form["upfile"]
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''
 
        if not self.error:
            self.doResults()
        else:
            self.showError()
Beispiel #22
0
    def extractParam(self):
        """Turn muti part encoded form into params."""
        params = []
        try:
            environ = {
                'CONTENT_TYPE': self.headers['content-type'],
                'CONTENT_LENGTH': self.headers['content-length'],
                'REQUEST_METHOD': 'POST',
            }
        except KeyError:
            trace('# Warning: missing header content-type or content-length'
                  ' in file: %s not an http request ?\n' % self.file_path)
            return params

        form = FieldStorage(fp=StringIO(self.body),
                            environ=environ,
                            keep_blank_values=True)
        try:
            keys = form.keys()
        except TypeError:
            trace('# Using custom data for request: %s ' % self.file_path)
            params = Data(self.headers['content-type'], self.body)
            return params

        for item in form.list:

            key = item.name
            value = item.value
            filename = item.filename

            if filename is None:
                params.append([key, value])
            else:
                # got a file upload
                filename = filename or ''
                params.append([key, 'Upload("%s")' % filename])
                if filename:
                    if os.path.exists(filename):
                        trace('# Warning: uploaded file: %s already'
                              ' exists, keep it.\n' % filename)
                    else:
                        trace('# Saving uploaded file: %s\n' % filename)
                        f = open(filename, 'w')
                        f.write(str(value))
                        f.close()
        return params
def __parse_post_body(environ, ignore_get=False):
    post_data = {}

    # accept post json
    if environ["CONTENT_TYPE"].strip(';') == "application/json" and environ["REQUEST_METHOD"] == "POST":
        storage = environ['wsgi.input'].read()
        if storage:
            return json.loads(storage)

    storage = FieldStorage(environ['wsgi.input'], environ=environ, keep_blank_values=True)

    # accept get querystring
    if not ignore_get:
        for k in storage.keys():
            post_data[k] = storage.getvalue(k)

    return post_data
Beispiel #24
0
    def __call__(self, environ, start_response):
        self.requests += 1

        self.params = parse_qs(environ['QUERY_STRING'])
        if environ.get('REQUEST_METHOD', 'GET').lower() == 'post':
            fs = FieldStorage(fp=environ['wsgi.input'], environ = environ, keep_blank_values = True)
            for k in fs.keys():
                self.params[k] = [fs.getvalue(k, ''),]
        else:
                sys.stderr.write("Usando GET\n")

        self.path = environ.get('PATH_INFO', '').lstrip('/').rstrip('/')
        if not bool(self.path):
            self.path = "index"
        self.environ = environ
        self.start_response = start_response
        return self._dispatch()
Beispiel #25
0
    def extractParam(self):
        """Turn muti part encoded form into params."""
        params = []
        try:
            environ = {
                'CONTENT_TYPE': self.headers['content-type'],
                'CONTENT_LENGTH': self.headers['content-length'],
                'REQUEST_METHOD': 'POST',
                }
        except KeyError:
            trace('# Warning: missing header content-type or content-length'
                  ' in file: %s not an http request ?\n' % self.file_path)
            return params

        form = FieldStorage(fp=StringIO(self.body),
                            environ=environ,
                            keep_blank_values=True)
        try:
            keys = form.keys()
        except TypeError:
            trace('# Using custom data for request: %s ' % self.file_path)
            params = Data(self.headers['content-type'], self.body)
            return params

        for item in form.list:
            
            key = item.name
            value = item.value
            filename = item.filename
            
            if filename is None:
                params.append([key, value])
            else:
                # got a file upload
                filename = filename or ''
                params.append([key, 'Upload("%s")' % filename])
                if filename:
                    if os.path.exists(filename):
                        trace('# Warning: uploaded file: %s already'
                              ' exists, keep it.\n' % filename)
                    else:
                        trace('# Saving uploaded file: %s\n' % filename)
                        f = open(filename, 'w')
                        f.write(str(value))
                        f.close()
        return params
Beispiel #26
0
    def parse_POST(self):
        ctype, pdict = parse_header(self.headers['content-type'])

        if ctype == 'multipart/form-data':

            form = FieldStorage(fp=self.rfile,
                                headers=self.headers,
                                environ={
                                    "REQUEST_METHOD": "POST",
                                    "CONTENT_TYPE":
                                    self.headers['Content-Type']
                                })

            postvars = {}

            for key in form.keys():

                if key == 'image':
                    fileImage = form['image'].file
                    postvars['image'] = Image.open(BytesIO(fileImage.read()))
                else:
                    if type(form[key].value) == type(b''):
                        postvars[key] = form[key].value.decode()
                    else:
                        postvars[key] = form[key].value

        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers['content-length'])
            data_str = self.rfile.read(length)
            fields = parse_qs(data_str, keep_blank_values=1)

            postvars = dict()
            for key in list(fields.keys()):
                postvars[key.decode()] = fields[key][0].decode()

        elif "image/" in ctype:
            length = int(self.headers['content-length'])
            im_str = self.rfile.read(length)
            image = Image.open(BytesIO(im_str))

            postvars = {'image': image}

        else:
            postvars = {}
        return postvars
Beispiel #27
0
def extract_fields():
    form = FieldStorage()
    if Fields.zip in form.keys():
        file_item = form[Fields.zip]
        if file_item.filename:
            if file_item.done == -1:
                raise Exception("File not fully downloaded.")
            else:
                product_name = get_str_value(form, Fields.product_name)
                product_version = get_str_value(form, Fields.product_version)
                comment = get_str_value(form, Fields.comment)
                zip_content = form.getvalue(Fields.zip)
                return fields_tuple(zip_content, file_item.filename,
                                    product_name, product_version, comment)
        else:
            raise Exception(Fields.zip + " field is not a file")
    else:
        raise Exception("No " + Fields.zip + " field")
Beispiel #28
0
def upload(env):
    status = '302 FOUND'
    headers = [
        ('Content-Type', 'text/html; charset=utf-8'),
        ('Status', '302'),  # must be str
        ('Location', '/'),
    ]
    form = FieldStorage(environ=env, fp=env['wsgi.input'])
    for key in form.keys():
        data = form[key]
        if _is_file(data):
            filename = data.filename  # basename
            file = data.file
            final_filename = _save_file(
                file, filename)  # 返回最终文件名,因为保存过程中,可能重命名为 xx_1 xx_2
            username = secure.get_username(env)
            secure.insert_file_info(filename=final_filename, username=username)
    return status, headers, b''
Beispiel #29
0
    def go(self):
        # determine which page to return
        self.cookies = {}
        self.error = ''
        form = FieldStorage()

        # handler pageData from client
        if not form.keys():
            self.showForm()
            return

        if 'person' in form:    # 取person给self.who
            self.who = form['person'].value.strip().title()
            if self.who == '':
                self.error = 'Your name is required.(blank)'
        else:
            self.error = 'Your name is required.(missing)'

        self.cookies['user'] = unquote(form['cookie'].value.strip()) if 'cookie' in form else ''    # 取cookie给self.cookies

        if 'lang' in form:      # 取lang给self.langs
            langData = form['lang']
            if isinstance(langData, list):
                self.langs = [eachLang.value for eachLang in langData]
            else:
                self.langs = [langData.value]
        else:
            self.error = 'At least one language required.'

        if 'upfile' in form:    # 取upfile的filename和file分别给self.fn和self.fp
            upfile = form['upfile']
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
        else:
            self.fp = StringIO('(no file')
            self.fn = ''

        if not self.error:  # self.error处理
            self.doResults()
        else:
            self.showError()
Beispiel #30
0
def _process_multipartform(environ):
    """
    Read ``multipart/form-data`` using ``FieldStorage``, return
    a dictionary of form data and set ``tiddlyweb.input_files``
    to a list of available files.
    """
    posted_data = {}
    try:
        field_storage = FieldStorage(fp=environ['wsgi.input'],
                environ=environ, keep_blank_values=True)
    except ValueError as exc:
        raise HTTP400('Invalid post, bad form: %s' % exc)
    for key in field_storage.keys():
        if (hasattr(field_storage[key], 'filename')
                and field_storage[key].filename):
            environ['tiddlyweb.input_files'].append(
                    field_storage[key])
        else:
            posted_data[key] = field_storage.getlist(key)
    return posted_data
Beispiel #31
0
    def extract_post_data(self):
        "Populates the POST variable"
        data = {}

        # Copy enviroment so we dont get GET-variables in the result.
        env = self.ENV.copy()
        env['QUERY_STRING'] = ''

        if env.get('REQUEST_METHOD', 'GET') == 'POST':
            _data = FieldStorage(
                fp=self.ENV['wsgi.input'],
                environ=env,
                keep_blank_values=False
            )
            for key in _data.keys():
                value = self._parse_field(_data[key], key, _data)
                if value is not None:
                    self._assign_field_to_section(key, value, data)

        self.POST = data
def GetCGIdata():
    "CGI POST und GET Daten zur einfacheren Verarbeitung zusammen in ein Dict packen"
    CGIdata = {}
    if os.environ.has_key('QUERY_STRING'):
        # GET URL-Parameter parsen
        for i in os.environ['QUERY_STRING'].split("&"):
            i = i.split("=")
            if len(i) == 1:
                if i[0] != "":
                    CGIdata[i[0]] = ""
            else:
                CGIdata[i[0]] = i[1]

    from cgi import FieldStorage
    FieldStorageData = FieldStorage()
    # POST Daten auswerten
    for i in FieldStorageData.keys():
        CGIdata[i] = FieldStorageData.getvalue(i)

    return CGIdata
Beispiel #33
0
def _process_multipartform(environ):
    """
    Read ``multipart/form-data`` using ``FieldStorage``, return
    a dictionary of form data and set ``tiddlyweb.input_files``
    to a list of available files.
    """
    posted_data = {}
    try:
        field_storage = FieldStorage(fp=environ['wsgi.input'],
                                     environ=environ,
                                     keep_blank_values=True)
    except ValueError as exc:
        raise HTTP400('Invalid post, bad form: %s' % exc)
    for key in field_storage.keys():
        if (hasattr(field_storage[key], 'filename')
                and field_storage[key].filename):
            environ['tiddlyweb.input_files'].append(field_storage[key])
        else:
            posted_data[key] = field_storage.getlist(key)
    return posted_data
def GetCGIdata():
    "CGI POST und GET Daten zur einfacheren Verarbeitung zusammen in ein Dict packen"
    CGIdata={}
    if os.environ.has_key('QUERY_STRING'):
        # GET URL-Parameter parsen
        for i in os.environ['QUERY_STRING'].split("&"):
            i=i.split("=")
            if len(i)==1:
                if i[0]!="":
                    CGIdata[ i[0] ] = ""
            else:
                CGIdata[ i[0] ] = i[1]

    from cgi import FieldStorage
    FieldStorageData = FieldStorage()
    # POST Daten auswerten
    for i in FieldStorageData.keys():
        CGIdata[i]=FieldStorageData.getvalue(i)

    return CGIdata
    def go(self):
        self.cookies = {}
        self.error = ''
        form = FieldStorage()
        if not form.keys():
            self.showForm()
            return

        if 'person' in form:
            self.who = form['person'].value.strip().title()
            if self.who == '':
                self.error = 'Your name is required. (blank)'
        else:
            self.error = 'Your name is required. (missing)'

        self.cookies['user'] = unquote(form['cookie'].value.strip()) if 'cookie' in form else ''
        if 'lang' in form:
            langData = form['lang']
            if isinstance(langData, list):
                self.langs = [eachLang.value for eachLang in langData]
            else:
                self.langs = [langData.value]
        else:
            self.error = 'At least one language required.'

        if 'upfile' in form:
            upfile = form['upfile']
            self.fn = upfile.filename or ''
            if upfile.file:
                self.fp = upfile.file
            else:
                self.fp = StringIO('(no data)')
        else:
            self.fp = StringIO('(no file)')
            self.fn = ''

        if not self.error:
            self.doResults()
        else:
            self.showError()
Beispiel #36
0
    def _parse_input(self):
        self._post = MultiDict()
        self._files = MultiDict()

        fp = None

        if self.method == 'POST':
            ctype = self.content_type.split(';')[0]

            if self.content_length:
                fp = self.META.get('wsgi.input', None)

            if fp and ctype in ('application/x-www-form-urlencoded', 'multipart/form-data'):
                environ = {
                    'REQUEST_METHOD': 'POST',
                    'CONTENT_TYPE': self.content_type,
                    'CONTENT_LENGTH': str(self.content_length),
                }
                fields = FieldStorage(fp=fp, environ=environ, keep_blank_values=True)

                for key in fields.keys():
                    if not key:
                        continue

                    values = fields[key]
                    if not isinstance(values, list):
                        values = [values]

                    for value in values:
                        if value.file:
                            print 'Files not yet supported. Filename: "%s" Field name: "%s" Content-type: "%s"' % \
                                    (value.filename, key, value.type)
                        else:
                            self._post.add(key, value.value)
                fp = None

        self._raw_fp = fp or StringIO()
Beispiel #37
0
def __parse_post_body(environ, ignore_get=False):
    post_data = {}

    content_type = environ[
        "CONTENT_TYPE"] if "CONTENT_TYPE" in environ else None
    if content_type is not None:
        mimetype, options = cgi.parse_header(content_type)
        # accept post json
        if mimetype == "application/json" and environ[
                "REQUEST_METHOD"] == "POST":
            storage = environ['wsgi.input'].read()
            if storage:
                return json.loads(storage)

    storage = FieldStorage(environ['wsgi.input'],
                           environ=environ,
                           keep_blank_values=True)

    # accept get querystring
    if not ignore_get:
        for k in storage.keys():
            post_data[k] = storage.getvalue(k)

    return post_data
Beispiel #38
0
    def __init__(self, environ):
        self.flag = None

        # Field: headers
        " Get all `HTTP_{HEADER_NAME}` environ keys "
        self.headers = {}
        for k, v in environ.iteritems():
            if k.startswith("HTTP_"):
                name = k[5:].lower().replace("_", "-")
                self.headers[name] = v

        # Field: params
        self.params = parse_qs(environ["QUERY_STRING"], keep_blank_values=1)

        content_type = environ.get("HTTP_CONTENT_TYPE", "")
        content_type = content_type or environ.get("CONTENT_TYPE", "")
        if "wsgi.input" in environ:
            wsgi_input = environ["wsgi.input"]
            if content_type.startswith("multipart/form-data"):
                form = FieldStorage(fp=wsgi_input, environ=environ)
                for k in form.keys():
                    if isinstance(form[k], list):
                        field = form[k][0]  # only first item
                    else:
                        field = form[k]

                    if not field.filename:
                        self.params[k] = field.value
                    else:
                        self.params[k] = field
            else:
                params = parse_qs(wsgi_input.read(), keep_blank_values=1)
                self.params.update(params)

        # Field: method
        self.method = environ["REQUEST_METHOD"].upper()

        if self.method == "POST" and ":method" in self.params:
            method = self.params.get(":method")
            if isinstance(method, list):
                self.method = method[0].upper()
            else:
                self.method = method.upper()

        # Field: cookies
        cookie = Cookie.SimpleCookie()
        for c in environ.get("HTTP_COOKIE", "").split(";"):
            try:
                cookie.load(c.strip())
            except Cookie.CookieError:
                info("Invalid cookie: %s" % c)
        self.cookies = dict(cookie.items())

        # Field: is_xhr
        if environ.get("HTTP_X_REQUESTED_WITH", "") == "XMLHttpRequest":
            self.is_xhr = True
        else:
            self.is_xhr = False

        # Field: remote_addr
        self.remote_addr = environ.get("REMOTE_ADDR", None)
        # endfold

        " Example: http://foo.example.com:8000/path/page.html?x=y&z "
        # Field: scheme     | http
        self.scheme = environ.get("wsgi.url_scheme", "http")

        # Field: host       | foo.example.com:8000
        self.host = ensure_unicode(environ.get("HTTP_HOST", ""))

        # Field: domain     | foo.example.com
        self.domain = ensure_unicode(self.host.split(":", 1)[0])

        # Field: port       | 8000
        if ":" in self.host:
            self.port = int(self.host.split(":")[1])
        else:
            self.port = 80

        # Field: query      | x=y&z
        self.query = ensure_unicode(environ["QUERY_STRING"])

        # Field: path       | /path/page.html
        self.path = ensure_unicode(environ["PATH_INFO"])

        # Field: path_query | /path/page.html?x=y&z
        self.path_query = self.path
        if self.query:
            self.path_query += "?%s" % self.query

        # Field: host_url   | http://foo.example.com:8000/
        self.host_url = u"%s://%s/" % (self.scheme, self.host)

        # Field: path_url   | http://foo.example.com:8000/path/page.html
        self.path_url = u"%s://%s%s" % (self.scheme, self.host, self.path)

        # Field: url        | http://foo.example.com:8000/path/page.html?x=y&z
        self.url = self.path_url
        if self.query:
            self.url += "?%s" % self.query
Beispiel #39
0
    def __init__(self, environ):
        # Field: headers
        " Get all `HTTP_{HEADER_NAME}` environ keys "
        self.headers = {}
        for k, v in environ.iteritems():
            if k.startswith("HTTP_"):
                name = k[5:].lower().replace("_", "-")
                self.headers[name] = v

        # Field: params
        self.params = parse_qs(environ["QUERY_STRING"], keep_blank_values=1)

        content_type = environ.get("HTTP_CONTENT_TYPE", "") or environ.get(
            "CONTENT_TYPE", "")
        if "wsgi.input" in environ:
            wsgi_input = environ["wsgi.input"]
            if content_type.startswith("multipart/form-data"):
                form = FieldStorage(fp=wsgi_input, environ=environ)
                for k in form.keys():
                    if isinstance(form[k], list):
                        field = form[k][0]  # only first item
                    else:
                        field = form[k]

                    if not field.filename:
                        self.params[k] = field.value
                    else:
                        self.params[k] = field
            else:
                params = parse_qs(wsgi_input.read(), keep_blank_values=1)
                self.params.update(params)

        # Field: method
        self.method = environ["REQUEST_METHOD"].upper()

        if self.method == "POST" and ":method" in self.params:
            method = self.params.get(":method")
            if isinstance(method, list):
                self.method = method[0].upper()
            else:
                self.method = method.upper()

        # Field: cookies
        cookie = Cookie.SimpleCookie()
        for c in environ.get("HTTP_COOKIE", "").split(";"):
            try:
                cookie.load(c.strip())
            except Cookie.CookieError:
                info("Invalid cookie: %s" % c)
        self.cookies = dict(cookie.items())

        # Field: is_xhr
        if environ.get("HTTP_X_REQUESTED_WITH", "") == "XMLHttpRequest":
            self.is_xhr = True
        else:
            self.is_xhr = False

        # Field: remote_addr
        self.remote_addr = environ.get("REMOTE_ADDR", None)
        # endfold

        " Example: http://foo.example.com:8000/path/page.html?x=y&z "
        # Field: scheme     | http
        self.scheme = environ.get("wsgi.url_scheme", "http")

        # Field: host       | foo.example.com:8000
        self.host = ensure_unicode(environ.get("HTTP_HOST", ""))

        # Field: domain     | foo.example.com
        self.domain = ensure_unicode(self.host.split(":", 1)[0])

        # Field: port       | 8000
        if ":" in self.host:
            self.port = int(self.host.split(":")[1])
        else:
            self.port = 80

        # Field: query      | x=y&z
        self.query = ensure_unicode(environ["QUERY_STRING"])

        # Field: path       | /path/page.html
        self.path = ensure_unicode(environ["PATH_INFO"])

        # Field: path_query | /path/page.html?x=y&z
        self.path_query = self.path
        if self.query:
            self.path_query += "?%s" % self.query

        # Field: host_url   | http://foo.example.com:8000/
        self.host_url = u"%s://%s/" % (self.scheme, self.host)

        # Field: path_url   | http://foo.example.com:8000/path/page.html
        self.path_url = u"%s://%s%s" % (self.scheme, self.host, self.path)

        # Field: url        | http://foo.example.com:8000/path/page.html?x=y&z
        self.url = self.path_url
        if self.query:
            self.url += "?%s" % self.query
Beispiel #40
0
#!/usr/bin/python
from cgi import FieldStorage
import sys
import os

root = os.environ("HOME")
sys.path.insert(0, root + "/python")

from pages.settings import Settings
Settings.setRootDirectory(root)

from pages.pageloader import PageLoader

import cgitb
cgitb.enable()

print("Content-Type: text/html\n")

parms = FieldStorage()
paramDict = {}
for k in parms.keys():
    paramDict[k] = parms.getvalue(k)

print(PageLoader().getPage(paramDict))
Beispiel #41
0
    def render_pure(self, environ):
        """
        renders this view with pure http-abilities. no script needed
        """
        frame = """
        <!DOCTYPE html>
        <html>
          <head>
            <title>%(title)s</title>
            <link href="/static/%(page_css)s" rel="stylesheet" type="text/css">
            <link href="%(scv_css)s" rel="stylesheet" type="text/css">
            %(head)s
          </head>
          <body>
            %(body)s
          </body>
        </html>
        """
        page_manager = self._core.get_page_manager()
        page = page_manager.get_page(self._page) 

        head = page.get_html_head()
        body = page.get_html_body()

        module_manager = self._core.get_module_manager()
        # Find placeholders to substitute
        
        space_name_map = page.get_space_names()
        for space, widget_id in self._space_widget_mapping.items():
            space_name = space_name_map[space]
            widget = module_manager.get_widget(widget_id)

            args = {} 
            if self._widget_param_mapping.has_key(widget_id):
                args.update(self._widget_param_mapping[widget_id])
            elif self._widget_param_mapping.has_key(str(widget_id)):
                args.update(self._widget_param_mapping[str(widget_id)])
            
            if self._post_widget_id == widget_id:
                # Check whether the viewjson-string is included here, too:
                # if so, eliminate it.
                post_args = FieldStorage(fp=environ['wsgi.input'],environ=environ)
                for key in post_args.keys():
                    args[key] = post_args[key].value

            widget_html = widget.render_pure_html(args)
            body = re.sub(r"<%%\s?space:%s\s?%%>"%space_name,widget_html,body)

        for box, boxcontent in self._box_mapping.items():
            box_orientation, box_name = self.get_box_info(box)
            box_html = StringIO.StringIO()
            for widget_id in boxcontent:
                widget = module_manager.get_widget(widget_id)

                args = {} 
                if self._widget_param_mapping.has_key(widget_id):
                    args.update(self._widget_param_mapping[widget_id])
                elif self._widget_param_mapping.has_key(str(widget_id)):
                    args.update(self._widget_param_mapping[str(widget_id)])

                if self._post_widget_id == widget_id:
                    # Check whether the viewjson-string is included here, too:
                    # if so, eliminate it.
                    post_args = FieldStorage(fp=environ['wsgi.input'],environ=environ)
                    for key in post_args.keys():
                        args[key] = post_args[key].value
            
                widget_html = widget.render_pure_html(args)
                box_html.write(widget_html)
                if box_orientation == BoxOrientation.VERTICAL:
                    box_html.write("<br>")

            if box_orientation == BoxOrientation.HORIZONTAL:
                body = re.sub(r"<%%\s?hbox:%s\s?%%>"%box_name,box_html.getvalue(),body)
            elif box_orientation == BoxOrientation.VERTICAL:
                body = re.sub(r"<%%\s?vbox:%s\s?%%>"%box_name,box_html.getvalue(),body)

        body = re.sub(r"<%[^%>]+%>","",body) #Replace all unused spaces with emptystring

        css_manager = self._core.get_css_manager()
        css_url = css_manager.get_css_url()

        configuration = self._core.get_configuration()
        title = configuration.get_entry("core.name")

        page_css = page.get_css_filename()

        return frame%{'title':title,
                      'scv_css':css_url,
                      'page_css':page_css,
                      'head':head,
                      'body':body}
Beispiel #42
0
def wsgi_handle_request(environ, start_response):
    '''
   handle one WSGI request
   '''

    global METADATA_FIELD_NAME
    global DATA_FIELD_NAME

    required_post_fields = [METADATA_FIELD_NAME, DATA_FIELD_NAME]
    required_delete_fields = [METADATA_FIELD_NAME]

    if environ['REQUEST_METHOD'] == 'GET':
        # GET request
        url_path = environ['PATH_INFO']
        outfile = StringIO()

        rc, msg = get(url_path, outfile)

        if rc == 200:
            size = outfile.len
            outfile.seek(0)
            headers = [('Content-Type', 'application/octet-stream'),
                       ('Content-Length', str(size))]
            start_response('200 %s' % msg, headers)

            return FileWrapper(outfile)

        else:
            return invalid_request(start_response, status="%s %s" % (rc, msg))

    elif environ['REQUEST_METHOD'] == 'POST':
        # POST request.
        # get POST'ed fields
        post_fields = FieldStorage(fp=environ['wsgi.input'], environ=environ)

        # validate
        for f in required_post_fields:
            if f not in post_fields.keys():
                return invalid_request(start_response)

        metadata_field = post_fields[METADATA_FIELD_NAME].value
        infile = post_fields[DATA_FIELD_NAME].file

        # if no file was given, then make a stringIO wrapper around the given string
        if infile == None:
            infile = StringIO(post_fields[DATA_FIELD_NAME].value)

        rc, msg = post(metadata_field, infile)

        if rc == 200:
            return valid_request(start_response)
        else:
            return invalid_request(start_response,
                                   status="%s %s" % (rc, msg),
                                   resp="error code %s\n" % str(rc))

    elif environ['REQUEST_METHOD'] == 'DELETE':
        # DELETE request
        post_fields = FieldStorage(fp=environ['wsgi.input'], environ=environ)

        # validate
        if not post_fields.has_key(METADATA_FIELD_NAME):
            return invalid_request(start_response)

        metadata_field = post_fields[METADATA_FIELD_NAME].value

        rc, msg = delete(metadata_field)

        if rc == 200:
            return valid_request(start_response)

        else:
            return invalid_request(start_response,
                                   status="%s %s" % (rc, msg),
                                   resp="error code %s\n" % str(rc))

    else:
        # not supported
        return invalid_request(start_response,
                               status="501 No Such Method",
                               resp="Method not supported\n")
Beispiel #43
0
def wsgi_handle_request( environ, start_response ):
   '''
   handle one WSGI request
   '''
   
   global METADATA_FIELD_NAME
   global DATA_FIELD_NAME
   
   required_post_fields = [METADATA_FIELD_NAME, DATA_FIELD_NAME]
   required_delete_fields = [METADATA_FIELD_NAME]
   
   if environ['REQUEST_METHOD'] == 'GET':
      # GET request
      url_path = environ['PATH_INFO']
      outfile = StringIO()
      
      rc, msg = get( url_path, outfile )
      
      if rc == 200:
         size = outfile.len
         outfile.seek(0)
         headers = [('Content-Type', 'application/octet-stream'), ('Content-Length', str(size))]
         start_response( '200 %s' % msg, headers )
         
         return FileWrapper( outfile )
      
      else:
         return invalid_request( start_response, status="%s %s" % (rc, msg) )
      
   elif environ['REQUEST_METHOD'] == 'POST':
      # POST request.
      # get POST'ed fields
      post_fields = FieldStorage( fp=environ['wsgi.input'], environ=environ )
      
      # validate
      for f in required_post_fields:
         if f not in post_fields.keys():
            return invalid_request( start_response )
      
      metadata_field = post_fields[METADATA_FIELD_NAME].value
      infile = post_fields[DATA_FIELD_NAME].file
      
      # if no file was given, then make a stringIO wrapper around the given string
      if infile == None:
         infile = StringIO( post_fields[DATA_FIELD_NAME].value )
      
      rc, msg = post( metadata_field, infile )
      
      if rc == 200:
         return valid_request( start_response )
      else:
         return invalid_request( start_response, status="%s %s" % (rc, msg), resp="error code %s\n" % str(rc))

   elif environ['REQUEST_METHOD'] == 'DELETE':
      # DELETE request
      post_fields = FieldStorage( fp=environ['wsgi.input'], environ=environ )
      
      # validate
      if not post_fields.has_key(METADATA_FIELD_NAME):
         return invalid_request( start_response )
      
      metadata_field = post_fields[METADATA_FIELD_NAME].value
      
      rc, msg = delete( metadata_field )
      
      if rc == 200:
         return valid_request( start_response )
      
      else:
         return invalid_request( start_response, status="%s %s" % (rc, msg), resp="error code %s\n" % str(rc))
         
   else:
      # not supported
      return invalid_request( start_response, status="501 No Such Method", resp="Method not supported\n" )
Beispiel #44
0
#!/usr/bin/env python
from cgi import FieldStorage

args = FieldStorage(fp=None, headers=None,environ=dict(key="value"))
print args.keys()
for a in args.keys():
    print args[i].name,args[i].value
Beispiel #45
0
import sys
import os
from cgi import FieldStorage

root = os.getcwd() + "/../.."
sys.path.insert(0, root + "/python")

from pages.settings import Settings
Settings.setRootDirectory(root)

html = """
<html>
<body>
<p>{version}<p>
<p>{syspath}<p>
<p>{cwd}<p>
<p>{params}</p>
<p>{dataDir}</p>
</body>
</html>
""" 

parms = FieldStorage()
paramDict = {} 
for k in parms.keys():
    paramDict[k] = parms.getvalue(k)

print ("Content-Type: text/html\n")
print (html.format(version=sys.version, syspath=sys.path, cwd=os.getcwd(), params=paramDict, dataDir=Settings.dataDirectory))

Beispiel #46
0
    def render_pure(self, environ):
        """
        renders this view with pure http-abilities. no script needed
        """
        frame = """
        <!DOCTYPE html>
        <html>
          <head>
            <title>%(title)s</title>
            <link href="/static/%(page_css)s" rel="stylesheet" type="text/css">
            <link href="%(scv_css)s" rel="stylesheet" type="text/css">
            %(head)s
          </head>
          <body>
            %(body)s
          </body>
        </html>
        """
        page_manager = self._core.get_page_manager()
        page = page_manager.get_page(self._page)

        head = page.get_html_head()
        body = page.get_html_body()

        module_manager = self._core.get_module_manager()
        # Find placeholders to substitute

        space_name_map = page.get_space_names()
        for space, widget_id in self._space_widget_mapping.items():
            space_name = space_name_map[space]
            widget = module_manager.get_widget(widget_id)

            args = {}
            if self._widget_param_mapping.has_key(widget_id):
                args.update(self._widget_param_mapping[widget_id])
            elif self._widget_param_mapping.has_key(str(widget_id)):
                args.update(self._widget_param_mapping[str(widget_id)])

            if self._post_widget_id == widget_id:
                # Check whether the viewjson-string is included here, too:
                # if so, eliminate it.
                post_args = FieldStorage(fp=environ['wsgi.input'],
                                         environ=environ)
                for key in post_args.keys():
                    args[key] = post_args[key].value

            widget_html = widget.render_pure_html(args)
            body = re.sub(r"<%%\s?space:%s\s?%%>" % space_name, widget_html,
                          body)

        for box, boxcontent in self._box_mapping.items():
            box_orientation, box_name = self.get_box_info(box)
            box_html = StringIO.StringIO()
            for widget_id in boxcontent:
                widget = module_manager.get_widget(widget_id)

                args = {}
                if self._widget_param_mapping.has_key(widget_id):
                    args.update(self._widget_param_mapping[widget_id])
                elif self._widget_param_mapping.has_key(str(widget_id)):
                    args.update(self._widget_param_mapping[str(widget_id)])

                if self._post_widget_id == widget_id:
                    # Check whether the viewjson-string is included here, too:
                    # if so, eliminate it.
                    post_args = FieldStorage(fp=environ['wsgi.input'],
                                             environ=environ)
                    for key in post_args.keys():
                        args[key] = post_args[key].value

                widget_html = widget.render_pure_html(args)
                box_html.write(widget_html)
                if box_orientation == BoxOrientation.VERTICAL:
                    box_html.write("<br>")

            if box_orientation == BoxOrientation.HORIZONTAL:
                body = re.sub(r"<%%\s?hbox:%s\s?%%>" % box_name,
                              box_html.getvalue(), body)
            elif box_orientation == BoxOrientation.VERTICAL:
                body = re.sub(r"<%%\s?vbox:%s\s?%%>" % box_name,
                              box_html.getvalue(), body)

        body = re.sub(r"<%[^%>]+%>", "",
                      body)  #Replace all unused spaces with emptystring

        css_manager = self._core.get_css_manager()
        css_url = css_manager.get_css_url()

        configuration = self._core.get_configuration()
        title = configuration.get_entry("core.name")

        page_css = page.get_css_filename()

        return frame % {
            'title': title,
            'scv_css': css_url,
            'page_css': page_css,
            'head': head,
            'body': body
        }
Beispiel #47
0
def StoredHandler(environ, start_response):
    from cgi import FieldStorage
    import cgitb
    cgitb.enable(display=0, logdir="/tmp")
    form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
    print(form.keys())

    start_response('200 Ok', [('Content-type', 'text/javascript')])

    if "oper" not in form:
        #print("Bad Request")
        return [json.dumps([False, 'Bad Request'])]

    method = environ['REQUEST_METHOD'].upper()
    if method == 'GET' or method == 'HEAD':
        return [json.dumps([False, 'bad request'])]
    oper = form['oper']
    print(oper)
    section = form.getfirst('roof', 'imsto')
    # section = form['section'] if form.has_key('section') else 'imsto'

    imsto = load_imsto(section)
    if oper.value == 'delete':
        id = form['id']
        r = imsto.delete(id.value)
        print r
        return [json.dumps(r)]
    if oper.value == 'add':

        if "new_file" not in form:
            return [json.dumps([False, 'please select a file'])]

        new_file = form['new_file']
        if new_file is None:
            return [json.dumps([False, 'invalid upload field'])]
        # print(type(new_file))
        result = []
        if type(new_file) == type([]):
            for f in new_file:
                print('%r %r %r %r %r %r' % (f.name, f.filename, f.type,
                                             f.disposition, f.file, f.length))
                r = imsto.store(f.file, ctype=f.type, name=f.filename)
                print 'store: %r, result %r' % (f.name, r)
                if type(r) == type([]):
                    result.append(r)
                else:
                    result.append(False)
        else:
            f = new_file
            print('single file %r %r' % (f.name, f.filename))
            try:
                result = imsto.store(f.file, ctype=f.type, name=f.filename)
                print 'store: %r, result %r' % (f.name, result)
            except Exception, e:
                result = [False, e.message]
                print "\n".join(get_traceback()) + "\n"

        if hasattr(imsto, 'close'):
            imsto.close()

        return [json.dumps(result)]
Beispiel #48
0
    def do_POST_api_files(self, ser):
        error_answer = "%s"

        if "/api/login" in self.path:
            self.send_response(200)
            self.send_header('Content-type', 'application/json; charset=utf-8')
            self.end_headers()
            self.wfile.write(bytes('{"name":"denis"}', 'utf8'))
            return

        if ser.isOpen():
            ser.flushInput()  #flush input buffer, discarding all its contents
            ser.flushOutput()  #flush output buffer, aborting current output
            #and discard all that is in buffer

        ser.ser_write('M27 C')  #Get SD print status

        if ser.wait_ok(error='SD printing'):
            if not Octohandler.printer_mountpoint in self.get_mounts():
                ser.ser_write('M22')  #umount sd card on printer
                if ser.wait_ok():
                    print("M22 ok")

                print("waiting for printer flash drive, up to 60 seconds")

                for i in range(0, 60):  #wait up to 60 seconds
                    if Octohandler.printer_mountpoint in self.get_mounts():
                        break
                    print(i)
                    time.sleep(1)  #wait for mount

                if not Octohandler.printer_mountpoint in self.get_mounts():
                    self.send_response(404)
                    self.send_header('Content-type',
                                     'application/json; charset=utf-8')
                    self.end_headers()
                    self.wfile.write(
                        bytes(error_answer % ("printer is not mounted"),
                              'utf8'))
                    return
        else:
            self.send_response(404)
            self.send_header('Content-type', 'application/json; charset=utf-8')
            self.end_headers()
            self.wfile.write(
                bytes(
                    error_answer %
                    ("unable to upload while printer is printing"), 'utf8'))
            return

        if "/api/files/local" in self.path or "/api/files/sdcard" in self.path:

            form = FieldStorage(fp=self.rfile,
                                headers=self.headers,
                                environ={
                                    'REQUEST_METHOD': 'POST',
                                    'CONTENT_TYPE':
                                    self.headers['content-type']
                                })

            filecontent = form['file'].value
            filename = form['file'].filename

            start_printing = False

            print("receive %s" % filename)
            #print(form.keys())

            if 'print' in form.keys():
                start_printing = (form['print'].value.lower() == "true")

            print("Start to print? ", start_printing)

            if filecontent:
                #tm = datetime.now().strftime("%Y%m%d%H%M%S.%f")
                file_save = "%s/%s" % (Octohandler.printer_mountpoint,
                                       os.path.basename(filename))
                binary_file = open(file_save, "w+b")
                binary_file.write(filecontent)
                binary_file.close()

                print("File %s was successfully received" % file_save)

                if start_printing:

                    fat_parser = FATParser(Octohandler.printer_mountpoint)
                    f83 = fat_parser.get83(filename)
                    print("name83=%s" % f83)
                    if f83:
                        if ser.isOpen():
                            ser.flushInput(
                            )  #flush input buffer, discarding all its contents
                            ser.flushOutput(
                            )  #flush output buffer, aborting current output
                        os.popen('/bin/umount %s' %
                                 Octohandler.printer_mountpoint)
                        time.sleep(5)
                        if Octohandler.printer_mountpoint in self.get_mounts():
                            self.send_response(404)
                            self.send_header(
                                'Content-type',
                                'application/json; charset=utf-8')
                            self.end_headers()
                            self.wfile.write(
                                bytes(error_answer % ("unable to umount"),
                                      'utf8'))
                            return

                        ser.ser_write('M21')  #mount sd card on printer
                        if ser.wait_ok(
                                ok="SD card ok") == True and ser.wait_ok():
                            print("M21 ok")

                            ser.ser_write('M20')  #listfiles
                            ser.wait_ok(ok="End file list")
                            ser.wait_ok()  #skip ok

                            ser.ser_write('M23 /%s' % f83)  #select
                            if ser.wait_ok(ok="File selected",
                                           error="open failed"
                                           ) == True and ser.wait_ok():
                                print("M23 ok")
                                ser.ser_write('M24')  #start
                                if ser.wait_ok():
                                    print("M24 ok")
                                    print("print was started!!!")
                            else:
                                print("M23 open filed")
                                self.send_response(404)
                                self.send_header(
                                    'Content-type',
                                    'application/json; charset=utf-8')
                                self.end_headers()
                                self.wfile.write(
                                    bytes(
                                        error_answer %
                                        ("unable start printing"), 'utf8'))
                                return

                self.send_response(200)
                self.send_header('Content-type', 'text/html; charset=UTF-8')
                self.end_headers()
                self.wfile.write(bytes("OK", 'utf8'))
                return

        self.send_response(404)
        self.send_header('Content-type', 'application/json; charset=utf-8')
        self.end_headers()
        self.wfile.write(
            bytes(error_answer % ("path not found!!! " + self.path), 'utf8'))
        return
import cgi
import os

# Setup
passphrase_key = 'submission.passphrase'  # page.name
passphrase_value = 'foo'

# Variables
data = {}

print("Content-Type: text/html, charset=\"utf-8\"")
print()  # very important whitespace

# Get data from form
form = FieldStorage(encoding='utf-8', keep_blank_values=True)
if len(form.keys()) <= 0:  # check for non-empty form
    exit()

# Check passphrase
if not form.getfirst(passphrase_key, '') == passphrase_value:
    print(
        "Incorrect passphrase, try <a href='/?page=-1'>again</a>! Your data is still entered."
    )
    exit()

# Store data from form in dict
data['form'] = {}
form_data = data['form']
for key in form.keys():
    if not key == passphrase_key:
        form_data[key] = form.getfirst(key, '').replace('\r\n', '\n')
Beispiel #50
0
def simple_app(environ, start_response):

    # Use urlparse module to create args dictionary from environ
    args = dict()
    qs = parse_qs(environ["QUERY_STRING"])
    for key, value in qs.iteritems():
        args[key] = value
    args["path"] = environ["PATH_INFO"]

    # POST args are more complicated
    if environ['REQUEST_METHOD'] == 'POST':
        # Create request headers dictionary out of environ data
        # This will be used by the cgi module to update args
        headers = dict()
        for key, value in environ.iteritems():
            if key.startswith("HTTP"):
                environ_key_string = key[5:]
                # environ keys look like "CONTENT_TYPE", while header keys look
                # like "content-type", hence this reformatting
                lowercase_key_string = environ_key_string.lower()
                header_key_string = lowercase_key_string.replace("_","-")
                headers[header_key_string] = value

        # These values don't start with HTTP, but we always need them
        headers['content-type'] = environ['CONTENT_TYPE']
        headers['content-length'] = environ['CONTENT_LENGTH']
        
        fp = environ["wsgi.input"]
        
        # In POST, overwrite what parse_qs put into args with values from
        # the cgi module's FieldStorage
        field_storage = FieldStorage(fp=fp, headers=headers, environ=environ)
        for key in field_storage.keys():
            args.update({key:field_storage[key].value})

    

    # Create a jinja2 environment pointing at the templates folder
    loader = FileSystemLoader("./templates")
    j_environ = Environment(loader=loader)
    
    # Pass jinja2 environment and args dictionary to the relevant function based
    # on the request path
    page = args["path"]
    if page == "/":
        status, content, response_headers = handle_index_get(j_environ, args)
    elif page == "/content":
        status, content, response_headers = handle_content_get(j_environ, args)
    elif page == "/file":
        status, content, response_headers = handle_file_get(j_environ, args)
    elif page == "/image":
        status, content, response_headers = handle_image_get(j_environ, args)
    elif page == "/form":
        status, content, response_headers = handle_form_get(j_environ, args)
    elif page == "/submit":
        status, content, response_headers = handle_submit(j_environ, args)
    else:
        status, content, response_headers = handle_404(j_environ, args)

    # Call start_reponse function (which was passed in as a parameter) with
    # the status and response headers returned by handling function
    start_response(status, response_headers)

    # Return content returned by handling function
    return content