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


Python cgi.FieldStorage方法代码示例

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


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

示例1: main

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def main():
  """Runs the login and logout CGI script."""
  form = cgi.FieldStorage(environ=os.environ)
  login_url = os.environ['PATH_INFO']
  email = os.environ.get('USER_EMAIL', '')
  admin = os.environ.get('USER_IS_ADMIN', '0') == '1'

  action = form.getfirst(ACTION_PARAM)
  set_email = form.getfirst(EMAIL_PARAM, '')
  set_admin = form.getfirst(ADMIN_PARAM, '') == 'True'
  continue_url = form.getfirst(CONTINUE_PARAM, '')

  LoginCGI(login_url,
           email,
           admin,
           action,
           set_email,
           set_admin,
           continue_url,
           sys.stdout)
  return 0 
开发者ID:elsigh,项目名称:browserscope,代码行数:23,代码来源:dev_appserver_login.py

示例2: get_post_form

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def get_post_form(environ):
    assert is_post_request(environ)
    input = environ['wsgi.input']
    post_form = environ.get('wsgi.post_form')
    if (post_form is not None
        and post_form[0] is input):
        return post_form[2]
    # This must be done to avoid a bug in cgi.FieldStorage
    environ.setdefault('QUERY_STRING', '')
    fs = cgi.FieldStorage(fp=input,
                          environ=environ,
                          keep_blank_values=1)

    return fs

# from https://github.com/pallets/werkzeug/blob/master/werkzeug/utils.py 
开发者ID:mme,项目名称:vergeml,代码行数:18,代码来源:wsgi.py

示例3: _decode_value

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def _decode_value(self, value):
        """
        Decode the specified value to unicode. Assumes value is a ``str`` or
        `FieldStorage`` object.

        ``FieldStorage`` objects are specially handled.
        """
        if isinstance(value, cgi.FieldStorage):
            # decode FieldStorage's field name and filename
            value = copy.copy(value)
            if self.decode_keys:
                value.name = value.name.decode(self.encoding, self.errors)
            value.filename = value.filename.decode(self.encoding, self.errors)
        else:
            try:
                value = value.decode(self.encoding, self.errors)
            except AttributeError:
                pass
        return value 
开发者ID:linuxscout,项目名称:mishkal,代码行数:21,代码来源:multidict.py

示例4: transcode_fs

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def transcode_fs(self, fs, content_type):
        # transcode FieldStorage
        if PY3: # pragma: no cover
            decode = lambda b: b
        else:
            decode = lambda b: b.decode(self.charset, self.errors)
        data = []
        for field in fs.list or ():
            field.name = decode(field.name)
            if field.filename:
                field.filename = decode(field.filename)
                data.append((field.name, field))
            else:
                data.append((field.name, decode(field.value)))

        # TODO: transcode big requests to temp file
        content_type, fout = _encode_multipart(
            data,
            content_type,
            fout=io.BytesIO()
        )
        return fout

# TODO: remove in 1.4 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:26,代码来源:request.py

示例5: __parse_post_body

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

示例6: do_POST

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def do_POST(self):
		if self.path=="/send":
			form = cgi.FieldStorage(
				fp=self.rfile, 
				headers=self.headers,
				environ={'REQUEST_METHOD':'POST',
		                 'CONTENT_TYPE':self.headers['Content-Type'],
			})

			self.nsa_queue.put(form["le_texte"].value[::-1])
			print "Le texte en clair: %s" % form["le_texte"].value
			self.send_response(200)
			self.end_headers()
			self.wfile.write(form["le_texte"].value[::-1])
			return			

		if self.path=="/decrypt":
			le_texte = self.nsa_queue.get()
			print "Le texte en encode: %s" % le_texte
			self.send_response(200)
			self.end_headers()
			self.wfile.write("Le texte intercepte: %s." % le_texte)
			self.wfile.write(" Le texte decode: %s" % le_texte[::-1])
			return 
开发者ID:UPB-FILS,项目名称:Archive-SE,代码行数:26,代码来源:simple_web_server.py

示例7: do_POST

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def do_POST(self):
        if self.path == "/play":
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD': 'POST',
                         'CONTENT_TYPE': self.headers['Content-Type'],})

            print "Client -> Le tableau: %s" % form["le_tableau"].value
            i = random.randint(1, 9)
            while form["le_tableau"].value[i] != "0":
               # print "index ", i, " value ", form["le_tableau"].value[i]
               i = random.randint(1, 9)
            print "Server played %s ->" % i
            self.send_response(200)
            self.end_headers()
            self.wfile.write(i-1)
            return 
开发者ID:UPB-FILS,项目名称:Archive-SE,代码行数:20,代码来源:simple_web_server.py

示例8: files

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def files(self):
        """ File uploads parsed from an `url-encoded` or `multipart/form-data`
            encoded POST or PUT request body. The values are instances of
            :class:`cgi.FieldStorage`. The most important attributes are:

            filename
                The filename, if specified; otherwise None; this is the client
                side filename, *not* the file name on which it is stored (that's
                a temporary file you don't deal with)
            file
                The file(-like) object from which you can read the data.
            value
                The value as a *string*; for file uploads, this transparently
                reads the file every time you request the value. Do not do this
                on big files.
        """
        files = FormsDict()
        for name, item in self.POST.iterallitems():
            if hasattr(item, 'filename'):
                files[name] = item
        return files 
开发者ID:zhangzhengde0225,项目名称:VaspCZ,代码行数:23,代码来源:bottle.py

示例9: POST

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def POST(self):
        """ The values of :attr:`forms` and :attr:`files` combined into a single
            :class:`FormsDict`. Values are either strings (form values) or
            instances of :class:`cgi.FieldStorage` (file uploads).
        """
        post = FormsDict()
        safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi
        for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
            if key in self.environ: safe_env[key] = self.environ[key]
        if NCTextIOWrapper:
            fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n')
        else:
            fb = self.body
        data = cgi.FieldStorage(fp=fb, environ=safe_env, keep_blank_values=True)
        for item in (data.list or [])[:self.MAX_PARAMS]:
            post[item.name] = item if item.filename else item.value
        return post 
开发者ID:zhangzhengde0225,项目名称:VaspCZ,代码行数:19,代码来源:bottle.py

示例10: extract_data_from_multipart_request

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def extract_data_from_multipart_request(self, environ: dict) -> Any:
        try:
            form = FieldStorage(
                fp=environ["wsgi.input"], environ=environ, keep_blank_values=True
            )
        except (TypeError, ValueError):
            raise HttpBadRequestError("Malformed request data")

        try:
            operations = json.loads(form.getvalue("operations"))
        except (TypeError, ValueError):
            raise HttpBadRequestError(
                "Request 'operations' multipart field is not a valid JSON"
            )
        try:
            files_map = json.loads(form.getvalue("map"))
        except (TypeError, ValueError):
            raise HttpBadRequestError(
                "Request 'map' multipart field is not a valid JSON"
            )

        return combine_multipart_data(operations, files_map, form) 
开发者ID:mirumee,项目名称:ariadne,代码行数:24,代码来源:wsgi.py

示例11: test_app

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n' 
开发者ID:kdart,项目名称:pycopia,代码行数:27,代码来源:fcgi.py

示例12: do_test

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def do_test(buf, method):
    env = {}
    if method == "GET":
        fp = None
        env['REQUEST_METHOD'] = 'GET'
        env['QUERY_STRING'] = buf
    elif method == "POST":
        fp = BytesIO(buf.encode('latin-1')) # FieldStorage expects bytes
        env['REQUEST_METHOD'] = 'POST'
        env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        env['CONTENT_LENGTH'] = str(len(buf))
    else:
        raise ValueError("unknown method: %s" % method)
    try:
        return cgi.parse(fp, env, strict_parsing=1)
    except Exception as err:
        return ComparableException(err) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:test_cgi.py

示例13: test_strict

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def test_strict(self):
        for orig, expect in parse_strict_test_cases:
            # Test basic parsing
            d = do_test(orig, "GET")
            self.assertEqual(d, expect, "Error parsing %s method GET" % repr(orig))
            d = do_test(orig, "POST")
            self.assertEqual(d, expect, "Error parsing %s method POST" % repr(orig))

            env = {'QUERY_STRING': orig}
            fs = cgi.FieldStorage(environ=env)
            if isinstance(expect, dict):
                # test dict interface
                self.assertEqual(len(expect), len(fs))
                self.assertCountEqual(expect.keys(), fs.keys())
                ##self.assertEqual(norm(expect.values()), norm(fs.values()))
                ##self.assertEqual(norm(expect.items()), norm(fs.items()))
                self.assertEqual(fs.getvalue("nonexistent field", "default"), "default")
                # test individual fields
                for key in expect.keys():
                    expect_val = expect[key]
                    self.assertIn(key, fs)
                    if len(expect_val) > 1:
                        self.assertEqual(fs.getvalue(key), expect_val)
                    else:
                        self.assertEqual(fs.getvalue(key), expect_val[0]) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:27,代码来源:test_cgi.py

示例14: test_fieldstorage_multipart

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def test_fieldstorage_multipart(self):
        #Test basic FieldStorage multipart parsing
        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
            'CONTENT_LENGTH': '558'}
        fp = BytesIO(POSTDATA.encode('latin-1'))
        fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
        self.assertEqual(len(fs.list), 4)
        expect = [{'name':'id', 'filename':None, 'value':'1234'},
                  {'name':'title', 'filename':None, 'value':''},
                  {'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'},
                  {'name':'submit', 'filename':None, 'value':' Add '}]
        for x in range(len(fs.list)):
            for k, exp in expect[x].items():
                got = getattr(fs.list[x], k)
                self.assertEqual(got, exp) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:test_cgi.py

示例15: test_fieldstorage_multipart_leading_whitespace

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def test_fieldstorage_multipart_leading_whitespace(self):
        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
            'CONTENT_LENGTH': '560'}
        # Add some leading whitespace to our post data that will cause the
        # first line to not be the innerboundary.
        fp = BytesIO(b"\r\n" + POSTDATA.encode('latin-1'))
        fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
        self.assertEqual(len(fs.list), 4)
        expect = [{'name':'id', 'filename':None, 'value':'1234'},
                  {'name':'title', 'filename':None, 'value':''},
                  {'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'},
                  {'name':'submit', 'filename':None, 'value':' Add '}]
        for x in range(len(fs.list)):
            for k, exp in expect[x].items():
                got = getattr(fs.list[x], k)
                self.assertEqual(got, exp) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:test_cgi.py


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