本文整理汇总了Python中cgi.FieldStorage类的典型用法代码示例。如果您正苦于以下问题:Python FieldStorage类的具体用法?Python FieldStorage怎么用?Python FieldStorage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FieldStorage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: do_POST
def do_POST(self):
if self.path != '/connect':
self.finish_up(404)
return
form = FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': self.headers['Content-Type']}
)
them = form.getvalue('them')
if them is None:
self.finish_up(500)
return
# only connect people we have not recently connected
# silently swallow requests for reconnections
status_code = 200
if them not in self.previous:
self.previous.append(them)
status_code = send_connection_message(them)
print("Emailed %s. MG code: %i", them, status_code)
else:
print("We recently emailed %s so skipping them.", them)
self.finish_up(status_code)
示例2: test_export_with_attachments
def test_export_with_attachments(self):
project = M.Project.query.get(shortname='test')
discussion = project.app_instance('discussion')
post = Forum.query.get(shortname='general').sorted_threads[0].first_post
test_file1 = FieldStorage()
test_file1.name = 'file_info'
test_file1.filename = 'test_file'
test_file1.file = StringIO('test file1\n')
post.add_attachment(test_file1)
ThreadLocalORMSession.flush_all()
f = tempfile.TemporaryFile()
temp_dir = tempfile.mkdtemp()
discussion.bulk_export(f, temp_dir, True)
f.seek(0)
discussion = json.loads(f.read())
forums = sorted(discussion['forums'], key=lambda x: x['name'])
threads = sorted(forums[0]['threads'], key=lambda x: x['subject'])
file_path = os.path.join(
'discussion',
str(post.discussion_id),
str(post.thread_id),
post.slug,
'test_file'
)
assert_equal(threads[0]['posts'][0]['attachments'][0]['path'], file_path)
os.path.exists(file_path)
示例3: repo_application
def repo_application(environ, start_response):
"""
The repositories WSGI application. If the incoming request's type is POST then it
will be delegated to a protocol handler, otherwise the default template will be returned.
"""
response_body = []
response_headers = []
status = '200 OK'
if environ['REQUEST_METHOD'] == 'POST':
try:
size = int(environ.get('CONTENT_LENGTH', 0))
except ValueError, e:
size = 0
args = FieldStorage(fp=environ['wsgi.input'], environ=environ)
jsonstr = args.getvalue('j')
logger.info('POST from %s: %s' % (environ['REMOTE_ADDR'], jsonstr))
try:
repository = Repository()
handler = ProtocolHandler(repository, jsonstr)
response_body = [handler.execute(environ)]
except DatabaseException, e:
logger.warning('database exception: %s' % str(e))
response_body = ['{"error":{"c":%d,"args":["errorstr":"%s"]}}' %
(RepositoryErrorCode.DATABASE_ERROR, str(e))]
示例4: test_upload_release_with_spaces
def test_upload_release_with_spaces(self):
from papaye.models import Root, Package, Release, ReleaseFile
from papaye.views.simple import UploadView
# Create a fake test file
uploaded_file = io.BytesIO(b"content")
storage = FieldStorage()
storage.filename = "foo.tar.gz"
storage.file = uploaded_file
self.request.POST = {
"content": storage,
"some_metadata": "Fake Metadata",
"version": "1.0",
"name": "my package",
":action": "file_upload",
"md5_digest": "Fake MD5",
}
root = Root()
self.request.root = root
view = UploadView(root, self.request)
result = view()
self.assertIsInstance(result, Response)
self.assertEqual(result.status_int, 200)
self.assertTrue("my-package" in root)
self.assertIsInstance(root["my-package"], Package)
self.assertTrue(root["my-package"].releases.get("1.0", False))
self.assertIsInstance(root["my-package"]["1.0"], Release)
self.assertTrue(root["my-package"]["1.0"].release_files.get("foo.tar.gz", b""))
self.assertIsInstance(root["my-package"]["1.0"]["foo.tar.gz"], ReleaseFile)
self.assertEqual(root["my-package"]["1.0"]["foo.tar.gz"].md5_digest, "Fake MD5")
self.assertIsNotNone(root["my-package"]["1.0"].metadata)
self.assertIsInstance(root["my-package"]["1.0"].metadata, dict)
self.assertEqual(root["my-package"]["1.0"].release_files.get("foo.tar.gz", b"").size, 7)
示例5: __init__
def __init__(self, session):
self.consumer = oauth.Consumer(key = OSMOAuth.CONSUMER_KEY, secret = OSMOAuth.SHARED_SECRET)
self.client = oauth.Client(self.consumer)
data = session.data
self.data = data
args = FieldStorage()
if args.list != None and args.has_key('reset'):
data['oauth_token'] = None
data['oauth_token_secret'] = None
if data.get('oauth_token') != None:
self.is_authorized = data['oauth_authorized'] == '1'
else:
self.request_token()
if not self.is_authorized:
token = self.request_access_token()
if not 'oauth_token' in token:
self.request_token()
else:
data['oauth_token'] = token['oauth_token']
data['oauth_token_secret'] = token['oauth_token_secret']
data['oauth_authorized'] = '1'
print session.cookie
self.access_with()
示例6: test_attachment_methods
def test_attachment_methods():
d = M.Discussion(shortname="test", name="test")
t = M.Thread.new(discussion_id=d._id, subject="Test Thread")
p = t.post("This is a post")
p_att = p.attach("foo.text", StringIO("Hello, world!"), discussion_id=d._id, thread_id=t._id, post_id=p._id)
t_att = p.attach("foo2.text", StringIO("Hello, thread!"), discussion_id=d._id, thread_id=t._id)
d_att = p.attach("foo3.text", StringIO("Hello, discussion!"), discussion_id=d._id)
ThreadLocalORMSession.flush_all()
assert p_att.post == p
assert p_att.thread == t
assert p_att.discussion == d
for att in (p_att, t_att, d_att):
assert "wiki/_discuss" in att.url()
assert "attachment/" in att.url()
# Test notification in mail
t = M.Thread.new(discussion_id=d._id, subject="Test comment notification")
fs = FieldStorage()
fs.name = "file_info"
fs.filename = "fake.txt"
fs.type = "text/plain"
fs.file = StringIO("this is the content of the fake file\n")
p = t.post(text=u"test message", forum=None, subject="", file_info=fs)
ThreadLocalORMSession.flush_all()
n = M.Notification.query.get(subject=u"[test:wiki] Test comment notification")
assert "\nAttachment: fake.txt (37 Bytes; text/plain)" in n.text
示例7: test_ms_data_as_file
def test_ms_data_as_file(self):
import tempfile
from cgi import FieldStorage
msfile = tempfile.TemporaryFile()
msfile.write('foo')
msfile.flush()
msfield = FieldStorage()
msfield.file = msfile
params = {'ms_data_format': 'mzxml',
'ms_data_file': msfield,
'max_ms_level': 3,
'abs_peak_cutoff': 1000,
'precursor_mz_precision': 0.005,
'mz_precision': 5.0,
'mz_precision_abs': 0.001,
'ionisation_mode': 1,
}
query = self.jobquery.add_ms_data(params)
script = "{magma} read_ms_data --ms_data_format 'mzxml'"
script += " -i '1' -m '3' -a '1000.0'"
script += " -p '5.0' -q '0.001' --precursor_mz_precision '0.005'"
script += " --call_back_url '/' ms_data.dat {db}\n"
expected_query = JobQuery(directory=self.jobdir,
prestaged=['ms_data.dat'],
script=script,
status_callback_url='/',
)
self.assertEqual(query, expected_query)
self.assertMultiLineEqual('foo', self.fetch_file('ms_data.dat'))
示例8: test_attachment_methods
def test_attachment_methods():
d = M.Discussion(shortname='test', name='test')
t = M.Thread.new(discussion_id=d._id, subject='Test Thread')
p = t.post('This is a post')
p_att = p.attach('foo.text', StringIO('Hello, world!'),
discussion_id=d._id,
thread_id=t._id,
post_id=p._id)
t_att = p.attach('foo2.text', StringIO('Hello, thread!'),
discussion_id=d._id,
thread_id=t._id)
d_att = p.attach('foo3.text', StringIO('Hello, discussion!'),
discussion_id=d._id)
ThreadLocalORMSession.flush_all()
assert p_att.post == p
assert p_att.thread == t
assert p_att.discussion == d
for att in (p_att, t_att, d_att):
assert 'wiki/_discuss' in att.url()
assert 'attachment/' in att.url()
# Test notification in mail
t = M.Thread.new(discussion_id=d._id, subject='Test comment notification')
fs = FieldStorage()
fs.name = 'file_info'
fs.filename = 'fake.txt'
fs.type = 'text/plain'
fs.file = StringIO('this is the content of the fake file\n')
p = t.post(text=u'test message', forum=None, subject='', file_info=fs)
ThreadLocalORMSession.flush_all()
n = M.Notification.query.get(
subject=u'[test:wiki] Test comment notification')
assert '\nAttachment: fake.txt (37 Bytes; text/plain)' in n.text
示例9: test_export_with_attachments
def test_export_with_attachments(self):
project = M.Project.query.get(shortname='test')
blog = project.app_instance('blog')
with h.push_context('test', 'blog', neighborhood='Projects'):
post = BM.BlogPost.new(
title='Test title',
text='test post',
labels=['the firstlabel', 'the second label'],
delete=None
)
ThreadLocalORMSession.flush_all()
test_file1 = FieldStorage()
test_file1.name = 'file_info'
test_file1.filename = 'test_file'
test_file1.file = StringIO('test file1\n')
p = post.discussion_thread.add_post(text='test comment')
p.add_multiple_attachments(test_file1)
ThreadLocalORMSession.flush_all()
f = tempfile.TemporaryFile()
temp_dir = tempfile.mkdtemp()
blog.bulk_export(f, temp_dir, True)
f.seek(0)
blog = json.loads(f.read())
blog['posts'] = sorted(
blog['posts'], key=lambda x: x['title'], reverse=True)
file_path = 'blog/{}/{}/{}/test_file'.format(
post._id,
post.discussion_thread._id,
list(post.discussion_thread.post_class().query.find())[0].slug
)
assert_equal(blog['posts'][0]['discussion_thread']['posts'][0]
['attachments'][0]['path'], file_path)
assert os.path.exists(os.path.join(temp_dir, file_path))
示例10: application
def application(environ, start_response):
start_response('200 OK', [('Content-type', 'text/html')])
form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
input = form.getvalue('eingabe')
auswahl = form.getvalue('auswahl')
if input:
filter= re.match('[0-9]+', input)
if filter:
eingabe = int(filter.group())
else:
eingabe= 0
if auswahl == 'Rekursiv':
try:
ausgabe = fibboRecursive(eingabe)
except:
ausgabe = 0
eingabe = 'Zahl zu gross'
else:
try:
ausgabe = fibboBinet(eingabe)
except:
ausgabe = 0
eingabe = 'Zahl zu gross'
else:
eingabe = ausgabe = ''
return [html_template % (eingabe, ausgabe)]
示例11: test
def test(self):
field = FieldStorage()
field.filename = 'aaa'
field.file = StringIO('abc')
field = WebpyFileField(field)
self.assertEqual('aaa', field.filename)
self.assertEqual(['abc'], list(field.chunks()))
示例12: test_upload_release_already_exists
def test_upload_release_already_exists(self):
from papaye.models import Root, Package, Release, ReleaseFile
from papaye.views.simple import UploadView
# Create a fake test file
uploaded_file = io.BytesIO(b"content")
storage = FieldStorage()
storage.filename = "foo.tar.gz"
storage.file = uploaded_file
self.request.POST = {
"content": storage,
"some_metadata": "Fake Metadata",
"version": "1.0",
"name": "my_package",
":action": "file_upload",
}
root = Root()
# Create initial release
package = Package("my_package")
package["1.0"] = Release("1.0", "1.0", metadata={})
package["1.0"]["foo.tar.gz"] = ReleaseFile("foo.tar.gz", b"")
root["my-package"] = package
view = UploadView(root, self.request)
result = view()
self.assertIsInstance(result, Response)
self.assertEqual(result.status_int, 409)
示例13: test_binary_create
def test_binary_create(self):
from io import BytesIO
fs = FieldStorage()
fs.file = BytesIO(b'fake_content')
values = {'data':fs}
self.provider.create(File, values)
示例14: StoredHandler
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)]
示例15: test_without_metabolize
def test_without_metabolize(self):
self.maxDiff = 100000
import tempfile
from cgi import FieldStorage
ms_data_file = tempfile.NamedTemporaryFile()
ms_data_file.write('foo')
ms_data_file.flush()
msfield = FieldStorage()
msfield.file = ms_data_file
params = MultiDict(ionisation_mode=1,
ms_intensity_cutoff=200000,
msms_intensity_cutoff=10,
abs_peak_cutoff=1000,
precursor_mz_precision=0.005,
max_broken_bonds=4,
max_water_losses=1,
mz_precision=5.0,
mz_precision_abs=0.001,
scenario=[{'type': 'phase1', 'steps': '2'},
{'type': 'phase2', 'steps': '1'}],
max_ms_level=3,
structures='C1CCCC1 comp1',
ms_data_file=msfield,
structure_format='smiles',
ms_data_format='mzxml',
structure_database='',
min_refscore=1,
max_mz=9999,
)
query = self.jobquery.allinone(params)
expected_script = "{magma} read_ms_data --ms_data_format 'mzxml'"
expected_script += " -i '1' -m '3' -a '1000.0'"
expected_script += " -p '5.0' -q '0.001'"
expected_script += " --precursor_mz_precision '0.005'"
expected_script += " --call_back_url '/'"
expected_script += " ms_data.dat {db}\n"
expected_script += "{magma} add_structures -g -t 'smiles'"
expected_script += " structures.dat {db}\n"
expected_script += "{magma} annotate -c '200000.0'"
expected_script += " -d '10.0'"
expected_script += " -b '4'"
expected_script += " --max_water_losses '1' --ncpus '1' --call_back_url '/'"
expected_script += " --fast {db}\n"
expected_query = JobQuery(directory=self.jobdir,
prestaged=['ms_data.dat', 'structures.dat'],
script=expected_script,
status_callback_url='/',
)
self.assertEqual(query, expected_query)
self.assertMultiLineEqual(params['structures'],
self.fetch_file('structures.dat'))
self.assertMultiLineEqual('foo', self.fetch_file('ms_data.dat'))