当前位置: 首页>>代码示例>>Python>>正文


Python FieldStorage.keys方法代码示例

本文整理汇总了Python中cgi.FieldStorage.keys方法的典型用法代码示例。如果您正苦于以下问题:Python FieldStorage.keys方法的具体用法?Python FieldStorage.keys怎么用?Python FieldStorage.keys使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cgi.FieldStorage的用法示例。


在下文中一共展示了FieldStorage.keys方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: StoredHandler

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
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)]
开发者ID:EricDoug,项目名称:imsto,代码行数:61,代码来源:handlers.py

示例2: handle_action

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
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))
开发者ID:martinohmann,项目名称:ctplot,代码行数:58,代码来源:wsgi.py

示例3: go

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
    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()
开发者ID:OraCheung,项目名称:Yagra,代码行数:57,代码来源:advcgi.py

示例4: print_env

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
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()])]
开发者ID:lyhiving,项目名称:imsto,代码行数:15,代码来源:_respond.py

示例5: do_POST

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
    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()
开发者ID:EikeKre,项目名称:pyload,代码行数:15,代码来源:CNLServer.py

示例6: go

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
        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()
开发者ID:EnTeQuAk,项目名称:pydanny-event-notes,代码行数:53,代码来源:advcgi2.py

示例7: stored_process

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
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'])]
开发者ID:gnemoug,项目名称:imsto,代码行数:52,代码来源:managehandle.py

示例8: parse_body

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
 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]
开发者ID:zweifisch,项目名称:klar,代码行数:16,代码来源:klar.py

示例9: do_POST

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
    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()
开发者ID:pyload,项目名称:pyload,代码行数:17,代码来源:clicknload_thread.py

示例10: extractParam

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
    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
开发者ID:jasongrout,项目名称:FunkLoad,代码行数:48,代码来源:Recorder.py

示例11: __call__

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
    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()
开发者ID:sandy98,项目名称:silver-age-comics,代码行数:19,代码来源:wsgiapp.py

示例12: _process_multipartform

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
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
开发者ID:24king,项目名称:tiddlyweb,代码行数:22,代码来源:query.py

示例13: GetCGIdata

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
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
开发者ID:Aaron1011,项目名称:python-code-snippets,代码行数:22,代码来源:consoleOLD1.py

示例14: extract_post_data

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
    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
开发者ID:klette,项目名称:pyroutes,代码行数:22,代码来源:request.py

示例15: go

# 需要导入模块: from cgi import FieldStorage [as 别名]
# 或者: from cgi.FieldStorage import keys [as 别名]
    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()
开发者ID:pathcl,项目名称:Core_Python_Applictions_Programming,代码行数:42,代码来源:advcgi.py


注:本文中的cgi.FieldStorage.keys方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。