Exemplo n.º 1
1
    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)
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
Exemplo n.º 3
0
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
Exemplo n.º 4
0
    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()
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    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)
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
    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)
Exemplo n.º 9
0
    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'))
Exemplo n.º 10
0
    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))
Exemplo n.º 11
0
 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()))
Exemplo n.º 12
0
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)]
Exemplo n.º 13
0
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))]
Exemplo n.º 14
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)]
Exemplo n.º 15
0
    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'))
Exemplo n.º 16
0
    def test_binary_update(self):
        fs = FieldStorage()
        fs.file = BytesIO(b'fake_content')

        values = {'data':fs}
        entity = self.provider.create(File, values)

        values = {'data':fs, 'file_id':entity.file_id}
        self.provider.update(File, values)
Exemplo n.º 17
0
 def test_accept_multipart_content(self, result_request, tool_definition):
     field_storage = FieldStorage()
     field_storage.filename = 'x.txt'
     field_storage.file = StringIO('whee')
     tool_definition['argument_names'] = ('x_path',)
     raw_arguments = {'x': field_storage}
     result = result_request.prepare_arguments(
         tool_definition, raw_arguments)
     assert open(result.arguments['x_path']).read() == 'whee'
Exemplo n.º 18
0
def main():

    args = parse_qs(environ['QUERY_STRING'])
    form = FormPost()
    if form.has_key('FLUSH'):
        flush_all()

    if 'update' in args:
        stat()
        return
    
    ats = ['items', 'bytes', 'oldest_item_age', 'hits', 'byte_hits', 'misses']
    samples = mget('sample-times', namespace=NS)
    if not samples:
        stat()
        samples = mget('sample-times', namespace=NS) or []

    s = mmget([str(i) for i in samples], namespace=NS)
    a = []
    if s:
        a = dict([(k, [int(s[d][k]) for d in s]) for k in ats]) # attr -> vals
        a = dict([(k, (max(a[k]), min(a[k]), a[k])) for k in a]) # attrs -> (max, min, vals)
        #a = dict([(k, [61*(v+1-a[k][1])/(a[k][0]+1-a[k][1]) for v in a[k][2]]) for k in a]) # attrs -> norml-vals
        a = dict([(k, ([61*(v+1-a[k][1])/(a[k][0]+1-a[k][1]) for v in a[k][2]], a[k][1], a[k][0])) for k in a]) # attrs -> norml-vals

    print "Content-type: text/html"
    print ""
    #l = ["rend('"+k+"', %s);"%str([int(s[d][k]) for d in s]) for k in ats]
    #l = ["rend('"+k+"', %s);"%str([int(d) for d in a[k]]) for k in a]
    print """<html><head><script type="text/javascript" src="http://www.solutoire.com/download/gchart/gchart-0.2alpha_uncompressed.js"></script>
<script>
// Using: http://solutoire.com/gchart/
// x = """+repr(a)+"""
function rend(t, d, mx, mn) {
GChart.render({'renderTo': 'stats', 'size': '800x200', colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF', legend:'"""+'|'.join([k for k in a])+"""',  title: t, 'data': d});
}
function main() {
"""
    def rnd(name, data, mxmn, colors, legend):
        print "GChart.render({'size': '480x200&chg=0,20', axistype: 'x,y,r'," # colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF',"
        print "     renderTo: '"+name+"',"
        if len(data) == 2:
            print "     axisrange: '1,"+','.join([str(i) for i in mxmn[0]])+"|2,"+','.join([str(i) for i in mxmn[1]])+"',"
        elif len(data) == 1:
            print "     axisrange: '1,"+','.join([str(i) for i in mxmn[0]])+"', axistype: 'x,y',"
        print "     colors: '"+','.join(colors)+"',"
        print "     legend:'"+'|'.join([l for l in legend])+"',"
        print "     data: "+str([[int(d) for d in dd] for dd in data])
        print "});"

    #print "rend('stats', %s);"%str([[int(d) for d in a[k][0]] for k in a])
    if a:
        rnd('stats', [a['hits'][0], a['byte_hits'][0]], [a['hits'][1:3], a['byte_hits'][1:3]], ['FF0088', '0077cc'], ["Hits", "Hit Bytes"])
        rnd('stats', [a['items'][0], a['bytes'][0]], [a['items'][1:3], a['bytes'][1:3]], ['FF0088', '0077cc'], ["Items", "Bytes"])
        rnd('stats', [a['misses'][0]], [a['misses'][1:3]], ['FF0088'], ["Miss"])
        rnd('stats', [a['oldest_item_age'][0]], [[x/60 for x in a['oldest_item_age'][1:3]]], ['0077cc'], ["Max Age"])
    print """
Exemplo n.º 19
0
def to_fieldstorage(f):
    fs = FieldStorage()
    fs.file = f
    fs.type = f.mimetype
    opt = f.mimetype_params
    opt['filename'] = f.filename
    fs.disposition_options = opt
    fs.type_options = opt
    return fs
Exemplo n.º 20
0
 def test_valid_imagefile_upload(self):
     from adhocracy.forms.common import ValidImageFileUpload
     from formencode import Invalid
     from cgi import FieldStorage
     from io import BytesIO
     value = FieldStorage()
     value.file = BytesIO(b"binarydata")
     value.filename = u"test.png"
     value.name = u"thumbs"
     self.assertRaises(Invalid, ValidImageFileUpload.to_python, value)
Exemplo n.º 21
0
def reply():

    from cgi import FieldStorage

    kwargs = FieldStorage()

    if kwargs.has_key('addr') or kwargs.has_key('elseaddr'):
        return whereyoulive_sum.reply(kwargs)
    else:
        return survey()
Exemplo n.º 22
0
 def upload_request(self, files: dict, metadata=None, user=None):
     if metadata is None:
         metadata = '{}'
     fields = MultiDict({'metadata': metadata})
     for name, content in files.items():
         fs = FieldStorage()
         fs.file = BytesIO(content)
         fs.filename = name
         fields.add('file', fs)
     return self.generic_request(post=fields, user=user)
Exemplo n.º 23
0
def web_loader(environ, start_response):
    headers = [('Content-type', 'application/json; charset=UTF-8'), ("Access-Control-Allow-Origin", "*")]
    start_response('200 OK', headers)

    form = FieldStorage()
    pid = os.fork()
    if pid == 0:  # new process
        os.system("philoload4 %s %s &" % (form.getvalue("dbname"), form.getvalue("files")))
        exit()

    yield dumps({"success": True})
    def import_stage(self, harvest_object):
        package_dict = json.loads(harvest_object.content)
        
        if not self._should_import_local(package_dict):
            package_dict['state'] = 'deleted'
        else:
            package_dict = self._apply_package_extras_white_list(package_dict)
            package_dict = self._apply_package_resource_extras_black_list(package_dict)
            package_dict = self._fix_date_in_fields(package_dict)
            package_dict = self._set_license(package_dict)
        
        package_dict = self._pop_black_list_resources_by_type(package_dict)
        harvest_object.content = json.dumps(package_dict)
        upload_resources = self._pop_upload_resources(package_dict)
        
        import_stage_result = super(GuiaHarvesterPlugin, self).import_stage(harvest_object)

        if import_stage_result:
            package_dict = json.loads(harvest_object.content)
            harvested_rels = package_dict.get('relationships', [])
            try:
                this_package = model.Package.get(package_dict['name'])
                if not this_package: raise logic.NotFound()
            except logic.NotFound as nf:
                log.info('import_stage(): could not find package "{0}"; relationships not updated: {1}'.format(package_dict['name'], nf))
                return import_stage_result

            existing_rels = this_package.get_relationships()
            self._update_relationships(existing_rels, harvested_rels)

            for resource_dict in upload_resources:
                resource_url = resource_dict['url']
                resource_filename = resource_url.split('/')[-1]

                try:
                    response = requests.get(resource_url)
                    resource_file = StringIO(response.content)
                except Exception,e:
                    self._save_object_error('Resource not harvested for package "{0}". Unable to fetch resource from "{1}": {2}'.format(package_dict['name'], resource_url, e), harvest_object, 'Import')
                    continue

                cfs = FieldStorage()
                cfs.file = resource_file
                cfs.filename = resource_filename
                resource_dict['upload'] = cfs
                if 'created' in resource_dict: del resource_dict['created']
                if 'last_modified' in resource_dict: del resource_dict['last_modified']
                if 'api' in resource_dict: del resource_dict['api']

                try:
                    the_resource = toolkit.get_action('resource_create')(data_dict=resource_dict)
                except Exception,e:
                    self._save_object_error('Resource not harvested for package "{0}". Unable to import the resource originally from "{1}": {2}'.format(package_dict['name'], resource_url, e), harvest_object, 'Import')
                    continue
Exemplo n.º 25
0
def GetQuery(QueryString, BlankIfMissing =0 ):
    if not InGlobals("FormFieldStorage"):
        from cgi import FieldStorage
        global FormFieldStorage
        FormFieldStorage = FieldStorage()

    if FormFieldStorage.has_key(QueryString):
        retVal = FormFieldStorage[QueryString].value
    else:
        retVal = iif(BlankIfMissing,"",None)

    return retVal
Exemplo n.º 26
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()
Exemplo n.º 27
0
 def test_create(self):
     view = self.get_view()
     content = FieldStorage()
     content.file = pkg_resources.resource_stream(
         'velo',
         'static/img/trollface.png'
         )
     view.request.POST.update({
         'longitude': 12.3,
         'latitude': -45.4,
         'content': content,
         })
     view.create()
Exemplo n.º 28
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()])]
Exemplo n.º 29
0
def main():
    # parse query string
    arguments = FieldStorage(keep_blank_values=True)

    json = arguments.getvalue('payload')
    content = loads(json)
    if 'commits' in content:
        repo = content['repository']['name']

        if repo in VALID_UPDATE_REPOSITORIES:
            handle_repository_update(repo)

        process_commit_mails(content)
Exemplo n.º 30
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]
Exemplo n.º 31
0
            def render(self, request):
                if self.server != "":
                    request.responseHeaders.removeHeader("Server")
                    request.responseHeaders.addRawHeader("Server", self.server)

                if request.method == "GET":
                    _q_s.logs.info([
                        "servers", {
                            'server': 'http_server',
                            'action': 'get',
                            'ip': request.getClientIP()
                        }
                    ])
                    if request.uri == "/login.html":
                        if _q_s.username != '' and _q_s.password != '':
                            request.responseHeaders.addRawHeader(
                                "Content-Type", "text/html; charset=utf-8")
                            return self.login_file

                    request.responseHeaders.addRawHeader(
                        "Content-Type", "text/html; charset=utf-8")
                    return self.home_file

                elif request.method == "POST":
                    self.headers = request.getAllHeaders()
                    _q_s.logs.info([
                        "servers", {
                            'server': 'http_server',
                            'action': 'post',
                            'ip': request.getClientIP()
                        }
                    ])
                    if _q_s.username != '' and _q_s.password != '':
                        form = FieldStorage(fp=request.content,
                                            headers=self.headers,
                                            environ={
                                                'REQUEST_METHOD':
                                                'POST',
                                                'CONTENT_TYPE':
                                                self.headers['content-type'],
                                            })
                        if 'username' in form and 'password' in form:
                            if form['username'].value == _q_s.username and form[
                                    'password'].value == _q_s.password:
                                _q_s.logs.info([
                                    "servers", {
                                        'server': 'http_server',
                                        'action': 'login',
                                        'status': 'success',
                                        'ip': request.getClientIP(),
                                        'username': _q_s.username,
                                        'password': _q_s.password
                                    }
                                ])
                            else:
                                _q_s.logs.info([
                                    "servers", {
                                        'server': 'http_server',
                                        'action': 'login',
                                        'status': 'failed',
                                        'ip': request.getClientIP(),
                                        'username': form['username'].value,
                                        'password': form['password'].value
                                    }
                                ])

                    request.responseHeaders.addRawHeader(
                        "Content-Type", "text/html; charset=utf-8")
                    return self.home_file
                else:
                    request.responseHeaders.addRawHeader(
                        "Content-Type", "text/html; charset=utf-8")
                    return self.home_file
Exemplo n.º 32
0
 def __init__(self, *args, **kw):
   self._ok_max_files_count=-1
   FieldStorage.__init__(self, *args, **kw)
Exemplo n.º 33
0
def containsNum(s):
    return any(char.isdigit() for char in s)


#from cgitb import enable
#enable()

from cgi import FieldStorage, escape
from hashlib import sha256
from time import time
from shelve import open
from http.cookies import SimpleCookie
import pymysql as db
redirBool = False
form_data = FieldStorage()
username = ''
result = ''
if len(form_data) != 0:
    username = escape(form_data.getfirst('username', '').strip())
    password = escape(form_data.getfirst('password', '').strip())
    passwordConf = escape(form_data.getfirst('passwordConf', '').strip())
    if not username or not password or not passwordConf:
        result = '<p class=pwInf>Please fill the required fields</p>'
    elif password.islower() or password.isupper() or not containsNum(password):
        result = '<p class=pwInf>Your password is invalid. Passwords must contain a mixture of lowercase letters, uppercase letters and numbers.</p>'
    elif password != passwordConf:
        result = '<p class=pwInf>Please enter matching passwords</p>'
    else:
        try:
            connection = db.connect('localhost', 'doh2', 'eipuohag',
Exemplo n.º 34
0
from cgitb import enable
enable()

from os import environ
from shelve import open
from http.cookies import SimpleCookie
import pymysql as db
from cgi import FieldStorage,escape
from datetime import datetime
cookie=SimpleCookie()
http_cookie_header=environ.get('HTTP_COOKIE')
curdate= (str(datetime.now()).split('.'))[0]


message=''
form_data= FieldStorage()
forum=escape(form_data.getfirst('forum',''))
post=escape(form_data.getfirst('post',''))
logedin=False
logedin=False
if http_cookie_header:
    cookie.load(http_cookie_header)
    if 'sid' in cookie:
        sessionId = cookie['sid'].value
        sessionStore = open('../session_stores/session-' + sessionId, writeback=False)
        if sessionStore.get('authenticated'):
            logedin =True

if logedin==True:
    logout="<form action='logout.py'><input type='submit' value='Log Out'></form>"
Exemplo n.º 35
0
#!/usr/local/bin/python3

from cgi import FieldStorage
from html import escape
from cgitb import enable
enable()

print('Content-Type: text/html')
print()

form_data = FieldStorage()
length = escape(form_data.getfirst('length', '')).strip()
units = escape(form_data.getfirst('units', '')).strip()

output = ''
inches = 0.0
yards = 0.0
feet = 0.0

if units in ['feet', 'inches', 'yards']:
    try:
        if units == 'feet':
            feet = float(length)
            inches = feet * 12
            yards = feet / 3
        elif units == 'inches':
            inches = float(length)
            feet = inches / 12
            yards = inches / 36
        else:
            yards = float(length)
Exemplo n.º 36
0
print("Content-Type: text/html")
print()


def dict_rows(cur):
    return [{k: v for k, v in zip(cur.description, row)} for row in cur]


def dict_row(cur):
    return {k[0]: v for k, v in zip(cur.description, cur.fetchone())}


form, node_type, x, y, pathway = None, None, None, None, None
try:
    form = FieldStorage()
    node_type = form.getvalue('type')
    x = form.getvalue('x')
    y = form.getvalue('y')
    pathway = form.getvalue("pathway")

except:
    print(-1)
    exit()

if type(x) is not str or type(y) is not str or type(
        pathway) is not str or node_type not in [
            "pathway", "protein", "metabolite", "label", "membrane", "image",
            "invisible"
        ]:
    print(-2)
Exemplo n.º 37
0
from os import environ
from http.cookies import SimpleCookie
from cgi import FieldStorage, escape
from Player import *
from GameController import *
from getGameController import *

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

#Takes the Name, Colour and Avatar values sent from the previous page
#and assigns them to variables
name = ""
avatar = ""
colour = ""
form_data = FieldStorage()
if len(form_data) != 0:
    name = escape(form_data.getfirst("name","").strip())
    avatar = escape(form_data.getfirst("avatar", "").strip())
    colour = escape(form_data.getfirst("colour","").strip())

#note for when using the game controller setGameController must
#be called at the end with the game controller in the parameter

#gets the users cookie from their browsers
cookie = SimpleCookie()
http_cookie_header = environ.get('HTTP_COOKIE')
#if there's no cookie return an error
if not http_cookie_header:
    print("Error! Cookie header")
    exit()
 def vars(self):
     return FieldStorage()
Exemplo n.º 39
0
def application(environ, start_response):
    output = ''
    content_type = "text/html"
    prefix = 'http://grey.colorado.edu:8080'
    finished = False

    form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
    query = form.getfirst('q')
    url = form.getfirst('url')
    proxy = form.getfirst('proxy')

    # A query is a search, for example, for "void Blah::Blerg"
    if query is not None and url is None:
        """
        First we will try with +"query"
        """
        try:
            # Try the full signature, e.g., void BaseSpec::UpdateSubSpecs
            url = prefix + '/source/search?q=' + quote_plus('+"' + query + '"')
            soup = BeautifulSoup(urlopen(url).read())
            url = soup.find('tt', {'class': 'con'}).a['href']
            if '#' in url:
                output = redirect(url)
            else:
                soup = BeautifulSoup(urlopen(prefix + url).read())
                url = soup.find('a', {'class': 's'})['href']
                output = redirect(url)
        except:
            try:
                """
                Then we will try to find an exact match by searching for the query without quotes but
                getting an exact string match
                """
                url = prefix + '/source/search?q=' + quote_plus(query)
                soup = BeautifulSoup(urlopen(url).read())
                results = soup.findAll('tt', {'class': 'con'})
                if results is not None:
                    for result in results:
                        if finished:
                            break
                        this_url = prefix + result.a['href']
                        this_soup = BeautifulSoup(urlopen(this_url).read())
                        possible_results = this_soup.findAll(
                            'a', {'class': 's'})
                        for this_result in possible_results:
                            this_sig = str(this_result).replace('<b>','').\
                                       replace('</b>','').split('</span>')[1].split('</a>')[0].strip()
                            #print this_soup.findAll('a',{'class':'s'})[0]
                            #print query, '\t', this_sig
                            print this_sig
                            if query in this_sig:
                                output = redirect(this_result['href'])
                                finished = True
                                break
                if not finished:
                    # hack to get it to try the next exception code
                    raise
            except:
                try:
                    """
                    Now we will try within quotes but without the return type
                    """
                    query = query.split(' ')[1]
                    url = prefix + '/source/search?q=' + quote_plus('+"' +
                                                                    query +
                                                                    '"')
                    soup = BeautifulSoup(urlopen(url).read())
                    url = soup.find('tt', {'class': 'con'}).a['href']
                    if '#' in url:
                        output = redirect(url)
                    else:
                        soup = BeautifulSoup(urlopen(prefix + url).read())
                        url = soup.find('a', {'class': 's'})['href']
                        output = redirect(url)
                except:
                    try:
                        """
                        Finally, just the method name
                        """
                        query = query.split('::')[-1]
                        url = prefix + '/source/search?q=' + quote_plus('+"' +
                                                                        query +
                                                                        '"')
                        soup = BeautifulSoup(urlopen(url).read())
                        url = soup.find('tt', {'class': 'con'}).a['href']
                        if '#' in url:
                            print 'if guy'
                            output = redirect(url)
                        else:
                            soup = BeautifulSoup(urlopen(prefix + url).read())
                            url = soup.find('a', {'class': 's'})['href']
                            output = redirect(url)
                    except:
                        output = 'Sorry, I was unable to find the source code for this guy'

    # This gets called recursively so we can take the user directly to the line
    if url is not None and query is None:
        output = intercept(url, prefix)

    # Intercepting proxy mode
    if proxy is not None and query is None and url is None:
        url = proxy.replace('QUESTION_MARK', '?')

        if '#' in url:
            output = redirect(url)
        else:
            if 'png' in url:
                content_type = "image/png"
            elif 'css' in url:
                content_type = "text/css"
            if not 'source' in url:
                url = '/source/' + url

            output = intercept(url, prefix)

    status = '200 OK'
    response_headers = [('Content-type', content_type),
                        ('Content-Length', str(len(output)))]

    start_response(status, response_headers)
    return [str(output)]
Exemplo n.º 40
0
def test_multiple_attachments():
    test_file1 = FieldStorage()
    test_file1.name = 'file_info'
    test_file1.filename = 'test1.txt'
    test_file1.type = 'text/plain'
    test_file1.file = StringIO('test file1\n')
    test_file2 = FieldStorage()
    test_file2.name = 'file_info'
    test_file2.filename = 'test2.txt'
    test_file2.type = 'text/plain'
    test_file2.file = StringIO('test file2\n')
    d = M.Discussion(shortname='test', name='test')
    t = M.Thread.new(discussion_id=d._id, subject='Test Thread')
    test_post = t.post('test post')
    test_post.add_multiple_attachments([test_file1, test_file2])
    ThreadLocalORMSession.flush_all()
    assert_equals(len(test_post.attachments), 2)
    attaches = test_post.attachments
    assert 'test1.txt' in [attaches[0].filename, attaches[1].filename]
    assert 'test2.txt' in [attaches[0].filename, attaches[1].filename]
Exemplo n.º 41
0
#!/usr/local/bin/python3

from cgitb import enable
enable()

from cgi import FieldStorage, escape
import pymysql as db
username = ""
score = ""

print('Content-Type: text/plain')
print()

form_data = FieldStorage()
username = form_data.getfirst('username')
score = int(form_data.getfirst('score'))

try:
    connection = db.connect('cs1dev.ucc.ie', 'ajbod1', 'eimaidae',
                            'users_ajbod1')
    cursor = connection.cursor(db.cursors.DictCursor)

    cursor.execute(
        """SELECT score
                        FROM breakoutstats
                        WHERE username=%s;""", (username))
    old_score = cursor.fetchall()
    print(old_score)

    if int(old_score[0]['score']) < score:
        cursor.execute(
Exemplo n.º 42
0
<body>
<form action=”/cgi-bin/uploadfile.py” method=”POST”
enctype=”multipart/form-data”>
<input type=”file” name=”file_name” size=”50”>
<input type=”submit”>
</form>
</body>
</html>”””
shtml = ‘’’<HTML><HEAD><TITLE>
</TITLE></HEAD>
<BODY>
<H3>Contents: %s</H3>
<PRE>%s
</PRE>
</BODY></HTML>’’’
form=FieldStorage()
if not form:
    print (header+dynhtml)
elif form.has_key(“file_name”):
    fileupload=form[“file_name”]
    data=’ ‘
    if fileupload.file:
        count=0
        while 1:
            line=fileupload.file.readline()
            data=data+line
            if not line:
                break
            count=count+1
        print (header+shtml % (fileupload.filename,data))
else:
Exemplo n.º 43
0
    def _generate_resources_from_folder(self, dataset):
        '''
        Given a dataset folder, it'll return a list of resource metadata
        '''
        resources = []
        file_list = [
            f for f
            in os.listdir(os.path.join(
                self.config['data_path'],
                dataset,
                self.config['metafile_dir']
            ))
            if os.path.isfile(os.path.join(
                self.config['data_path'],
                dataset,
                self.config['metafile_dir'],
                f
            ))
        ]
        resource_files = self._remove_hidden_files(file_list)
        log.debug(resource_files)

        # for resource_file in resource_files:
        for resource_file in (x for x in resource_files if x != 'meta.xml'):
            resource_path = os.path.join(
                self.config['data_path'],
                dataset,
                self.config['metafile_dir'],
                resource_file
            )
            if resource_file == 'link.xml':
                with retry_open_file(resource_path, 'r') as links_xml:
                    links = (
                        etree.parse(links_xml)
                        .findall('link')
                    )

                    for link in links:
                        url = self._get(link, 'url')
                        if url:
                            # generate hash for URL
                            md5 = hashlib.md5()
                            md5.update(url)
                            resources.append({
                                'url': url,
                                'zh_hash': md5.hexdigest(),
                                'name': self._get(link, 'lable'),
                                'description': self._get(link, 'description'),
                                'format': self._get(link, 'type'),
                                'resource_type': 'api',
                            })
            else:
                resource_file = self._validate_filename(resource_file)
                if resource_file:
                    resource_dict = {
                        'name': resource_file,
                        'url': '',
                        'format': resource_file.split('.')[-1],
                        'resource_type': 'file'
                    }

                    # calculate the hash of this file
                    BUF_SIZE = 65536  # lets read stuff in 64kb chunks!
                    md5 = hashlib.md5()
                    with retry_open_file(resource_path, 'rb') as f:
                        while True:
                            data = f.read(BUF_SIZE)
                            if not data:
                                break
                            md5.update(data)
                        resource_dict['zh_hash'] = md5.hexdigest()

                    # add file to FieldStorage
                    with retry_open_file(resource_path, 'r', close=False) as f:  # noqa
                        field_storage = FieldStorage()
                        field_storage.file = f
                        field_storage.filename = f.name
                        resource_dict['upload'] = field_storage

                    resources.append(resource_dict)

        sorted_resources = sorted(
            resources,
            cmp=lambda x, y: self._sort_resource(x, y)
        )
        return sorted_resources
Exemplo n.º 44
0
                setOfRatedMovieNames.add(output['name'])
            #get all names from movies
            cursor.execute("""SELECT name FROM movies""")
            table = cursor.fetchall()
            setOfAllMovieNames = set()
            for row in table:
                setOfAllMovieNames.add(row['name'])
            #take one from the other and put it in movieList
            setOfUnratedMovieNames = setOfAllMovieNames - setOfRatedMovieNames
            movieList = "<p>Here's a list of all of the movies you have not yet rated:"
            for movieName in setOfUnratedMovieNames:
                movieList = movieList + str(movieName) + "</br>"
            movieList = movieList + "</p>"

            ##############################################################
            form_data = FieldStorage()
            movie = ''
            score = ''
            if len(form_data) != 0:
                movie = escape(form_data.getfirst('movie', '').strip())
                score = escape(form_data.getfirst('score', '').strip())
                if not movie or not score:
                    error = '<p>Error: movie and score are required</p>'
                elif not score.isdigit():
                    error = '<p>Error: score must be a digit</p>'
                elif int(score) > 5 or int(score) < 0:
                    error = '<p>Error: score must be above 0 and equal to or below 5</p>'
                elif movie not in setOfUnratedMovieNames:
                    error = '<p>Error: movie must be in the list that is below</p>'
                else:
                    try:
Exemplo n.º 45
0
def test_notification_two_attaches():
    d = M.Discussion(shortname='test', name='test')
    t = M.Thread.new(discussion_id=d._id, subject='Test comment notification')
    fs1 = FieldStorage()
    fs1.name = 'file_info'
    fs1.filename = 'fake.txt'
    fs1.type = 'text/plain'
    fs1.file = StringIO('this is the content of the fake file\n')
    fs2 = FieldStorage()
    fs2.name = 'file_info'
    fs2.filename = 'fake2.txt'
    fs2.type = 'text/plain'
    fs2.file = StringIO('this is the content of the fake file\n')
    p = t.post(text=u'test message',
               forum=None,
               subject='',
               file_info=[fs1, fs2])
    ThreadLocalORMSession.flush_all()
    n = M.Notification.query.get(
        subject=u'[test:wiki] Test comment notification')
    base_url = h.absurl('{}attachment/'.format(p.url()))
    assert_in(
        '\nAttachments:\n\n'
        '- [fake.txt]({0}fake.txt) (37 Bytes; text/plain)\n'
        '- [fake2.txt]({0}fake2.txt) (37 Bytes; text/plain)'.format(base_url),
        n.text)
Exemplo n.º 46
0
from unittest import TestCase

import pretend
import pytest

from pyramid.httpexceptions import HTTPNotFound
from sqlalchemy.orm.exc import NoResultFound
from webob.multidict import MultiDict

from warehouse.admin.interfaces import ISponsorLogoStorage
from warehouse.admin.views import sponsors as views
from warehouse.sponsors.models import Sponsor

from ....common.db.sponsors import SponsorFactory

COLOR_LOGO_FILE = FieldStorage()
COLOR_LOGO_FILE.filename = "colorlogo.png"
COLOR_LOGO_FILE.file = io.BytesIO((
    b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06"
    b"\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\xdac\xfc\xcf\xc0P\x0f\x00"
    b"\x04\x85\x01\x80\x84\xa9\x8c!\x00\x00\x00\x00IEND\xaeB`\x82"))
COLOR_LOGO_FILE.type = "image/png"

WHITE_LOGO_FILE = FieldStorage()
WHITE_LOGO_FILE.filename = "whitelogo.png"
WHITE_LOGO_FILE.file = io.BytesIO((
    b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06"
    b"\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\xdac\xfc\xcf\xc0P\x0f\x00"
    b"\x04\x85\x01\x80\x84\xa9\x8c!\x00\x00\x00\x00IEND\xaeB`\x82"))
WHITE_LOGO_FILE.type = "image/png"
Exemplo n.º 47
0
    http_cookie_header = environ.get('HTTP_COOKIE')
    if not http_cookie_header:
        sid = sha256(repr(time()).encode()).hexdigest()
        cookie['sid'] = sid
    else:
        cookie.load(http_cookie_header)
        if 'sid' not in cookie:
            sid = sha256(repr(time()).encode()).hexdigest()
            cookie['sid'] = sid
        else:
            sid = cookie['sid'].value

    session_store = open('sess_' + sid, writeback=True)

    # Get the id of the item being added to the cart
    form_data = FieldStorage()
    book_number = form_data.getfirst('book_number')

    # If this item is not in the cart already, then quantity is 1; otherwise, increment the quantity.
    qty = session_store.get(book_number)
    if not qty:
        qty = 1
    else:
        qty +=1
    session_store[book_number] = qty
    session_store.close()

    print(cookie)
    result = '<p>Item successfully added to your cart.</p>'
except IOError:
    result = '<p>Sorry! We are experiencing problems at the moment. Please call back later.</p>'
Exemplo n.º 48
0
def prepare_field_storage(name, x):
    field_storage = FieldStorage()
    field_storage.filename = name
    field_storage.file = prepare_file(x)
    return field_storage
Exemplo n.º 49
0
restricted = "restricted"
sys.path.append(os.path.abspath(restricted))


from cgi import FieldStorage
from html import escape
import pymysql as db
import passwords
import funcs
from os import environ
from http.cookies import SimpleCookie
from time import time
import hashlib

form_data = FieldStorage()

result = ""
check = False

uname = form_data.getfirst("uname")
pwd = form_data.getfirst("pwd")


if uname:
    uname = escape(uname, quote=False)
else:
    uname = ""

if pwd:
    pwd = escape(pwd, quote=False)
Exemplo n.º 50
0
#!/usr/local/bin/python3

from cgi import FieldStorage
import pymysql as db
from cgitb import enable
enable()

print('Content-Type: text/html')
print()

form_data = FieldStorage()

country = ''
output = ''

if len(form_data) != 0:
    try:
        country = form_data.getfirst('country', '')
        connection = db.connect('localhost', 'cf26', 'pecah',
                                'cs6503_cs1106_cf26')
        cursor = connection.cursor(db.cursors.DictCursor)
        cursor.execute("""SELECT * FROM winners WHERE country = %s""",
                       (country))
        if len(cursor.fetchall()) != 0:
            output = """<table>
                <tr><th colspan="4">Eurovision Winners</th></tr>
                <tr><th>Year</th><th>Song</th><th>Performer</th><th>Points</th></tr>"""
            for row in cursor.fetchall():
                print(len(row))
                output += """<tr>
                                <td>%s</td>
Exemplo n.º 51
0
#!/usr/local/bin/python3

from cgitb import enable

enable()

from cgi import FieldStorage
from html import escape
from hashlib import sha256
from time import time
from shelve import open
from http.cookies import SimpleCookie

form_data = FieldStorage()
attempt = ''
attempt2 = ''
result = ''
javascript = ''
colour_button = ''
paragraph = ""
score = 0
if len(form_data) != 0:
    attempt = escape(form_data.getfirst('guess', '').strip())
    attempt2 = escape(form_data.getfirst('guess2', '').strip())
    attempt3 = escape(form_data.getfirst('guess3', '').strip())
    attempt4 = escape(form_data.getfirst('guess4', '').strip())
    attempt5 = escape(form_data.getfirst('guess5', '').strip())
    try:
        if attempt == "A":
            score += 1
        if attempt2 == "10":
Exemplo n.º 52
0
            dataID, sampleID)
        cursor.execute(statement)
        for row in cursor.fetchall():
            return (row['sampleData'])
    except (db.Error, IOError) as e:
        print("Database error in getData code.py")
        print(e)


url = ""
body = ""
print('Content-Type: text/html')
print()

cursor = getCursor()
form = FieldStorage()


def databaseForm(cursor):

    selectDB = """<h1>Select Database: </h1> <select name="dbID">"""
    try:
        cursor.execute("""select distinct dataID from fypDB""")
        # lst = []
        for row in cursor.fetchall():
            # lst+=[row['dataID']]
            selectDB += """<option value="%s">%s</option>""" % (row['dataID'],
                                                                row['dataID'])

        selectDB += "</select>"
        formCode = (
Exemplo n.º 53
0
    msg = email.MIMEMultipart.MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = email.Utils.COMMASPACE.join(tolist)
    msg['Subject'] = subject
    msg.attach(MIMEText(message))
    msg.attach(MIMEText('\nSent from saas.mit.edu', 'plain'))
    server.sendmail(user, tolist, msg.as_string())


def verify_email(email):
    if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
        return False
    return True


f = FieldStorage()
fromaddr = message = subject = None
error_msg = "Looks like you have a missing field or two!"
if "from" in f:
    fromaddr = f["from"].value
    if not verify_email(fromaddr):
        fromaddr = None
        error_msg = "Looks like the email you entered has a typo!"
if "message" in f:
    message = f["message"].value
if "subject" in f:
    subject = f["subject"].value

if fromaddr and message and subject:
    # Success page
    send_email(fromaddr, subject, message)
Exemplo n.º 54
0
#!/usr/bin/python3

# Get available and valid places according to tile rotation
from cgitb import enable

enable()

from getGameController import *

print('Content-Type: text/plain')
print()
from cgi import FieldStorage, escape

gC = getGameController()

form_data = FieldStorage()
if len(form_data) != 0:
    rotate = form_data.getfirst("rotate")
    if rotate == "True":
        validPlaces = gC.rotateTile()
    else:
        validPlaces = gC.getValidTilePlacements()
setGameController(gC)
ret_str = ""
for cell in validPlaces:
    ret_str += "%s,%s " % (cell[0], cell[1])
print(ret_str)
Exemplo n.º 55
0
#!/usr/local/bin/python3
from cgitb import enable
enable()
from cgi import FieldStorage
from html import escape
from time import strptime
import pymysql as db
print('Content-Type: text/html')
print()

form_data =FieldStorage()
bandname =''
gig_date =''
result =''
if len(form_data) > 0:
    try:
        bandname = escape(form_data.getfirst('bandname', '').strip())
        gig_date = escape(form_data.getfirst('gig_date', '').strip())
        if bandname or gig_date:
            connection = db.connect('cs1.ucc.ie', 'sv6', 'oguri', 'cs6503_cs1106_sv6')
            cursor = connection.cursor(db.cursors.DictCursor)
            if bandname:
                cursor.execute("""SELECT * FROM gigs
                                  WHERE bandname = %s""", (bandname))
                if cursor.rowcount == 0:
                    result = """<p>Unknown band name</p>"""
            if gig_date:
                try:
                    valid_date = strptime(gig_date, '%Y-%m-%d')
                except ValueError:
                    result+= """<p>Illegal date </p>"""
Exemplo n.º 56
0
      <label>
        <input type="checkbox" value="remember-me"> Remember me
      </label>
    </div>
    <button class="landing btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
  </form>

  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>"""

cookie = SimpleCookie()
http_cookie_header = environ.get('HTTP_COOKIE')

form_data = FieldStorage()
email = escape(form_data.getfirst('email', "").strip())
password = escape(form_data.getfirst('password', "").strip())

if email != '':
    connection = db.connect('cs1.ucc.ie', 'rjf1', 'ahf1Aeho', '2021_rjf1')
    cursor = connection.cursor(db.cursors.DictCursor)
    search_result = cursor.execute(
        """SELECT * FROM users WHERE email = %s AND password = %s""",
        (email, password))
    fetched = cursor.fetchone()
    name = fetched['first_name'] + ' ' + fetched['last_name']
    id = fetched['id']
    account_type = fetched['account_type']
    current_class = str(fetched['class'])
                    <li><a href="streaming.py">Browse</a></li>
                    <li><a href="login.py">Login</a></li>
                    <li><a href="register.py">Register</a></li>
                  </ul>
                </nav>
            </header>'''
page = """
<main>
   <p>You do not have permission to access this page.</p>
   <ul>
       <li><a href="register.py">Register</a></li>
       <li><a href="login.py">Login</a></li>
   </ul>
</main>
   """
form_data = FieldStorage()
song_id = ''
playlist = ''
username = ''

try:
    cookie = SimpleCookie()
    http_cookie_header = environ.get('HTTP_COOKIE')
    if http_cookie_header:
        cookie.load(http_cookie_header)
        if 'sid' in cookie:
            sid = cookie['sid'].value
            session_store = open('sess_' + sid, writeback=False)
            if session_store.get('authenticated'):
                username = (session_store.get('username'))
                playlist = escape(form_data.getfirst('playlist', ''))
Exemplo n.º 58
0
#!/usr/local/bin/python3

from cgitb import enable 
enable()

from os import environ
from cgi import FieldStorage, escape
from hashlib import sha256            # Secure Hash Algorithm is a cryptographic hash function designed by the United States National Security Agency and is a U.S. Federal Information Processing Standard 
from time import time
from shelve import open                # A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects
from http.cookies import SimpleCookie   
import pymysql as db                   

form_data = FieldStorage()
username=''
password=''
result = ''
result2=''

loggedIn=False

try:
    cookie = SimpleCookie()
    http_cookie_header = environ.get('HTTP_COOKIE')
    if not http_cookie_header:
        toy = sha256(repr(time()).encode()).hexdigest()
        cookie['toy'] = toy
    else:
        cookie.load(http_cookie_header)
        if 'toy' not in cookie:
            toy = sha256(repr(time()).encode()).hexdigest()
Exemplo n.º 59
0
def setup():
  from base64 import urlsafe_b64encode, urlsafe_b64decode
  from http.cookies import CookieError, SimpleCookie
  from cgi import FieldStorage
  from datetime import datetime
  from decimal import Decimal
  from json import JSONEncoder
  from os import environ, path
  from pickle import dumps, loads, UnpicklingError
  from .pypp import preprocess
  from sys import exit

  class DecimalEncoder(JSONEncoder):
    def default(self, obj):
      nonlocal Decimal, JSONEncoder
      if isinstance(obj, Decimal):
        return str(obj)
      return JSONEncoder.default(self, obj)
  
  global toJSON, toHiddenJSON
  def toJSON(obj):
    nonlocal DecimalEncoder
    return DecimalEncoder().encode(obj)
  def toHiddenJSON(obj):
    nonlocal DecimalEncoder
    return toJSON(obj).replace("&", "&#38;").replace("'", "&39;")

  new_cookies = SimpleCookie()
  form = FieldStorage()
  fields = {}
  moon = datetime(1969, 7, 21, 2, 56)

  try:
    old_cookies = SimpleCookie(environ['HTTP_COOKIE'])
  except (CookieError, KeyError):
    old_cookies = {}
  
  global getCookie, setCookie, deleteCookie
  def getCookie(name):
    nonlocal old_cookies
    try:
        return old_cookies[name].value
    except KeyError:
        return None
  def setCookie(name, value):
    nonlocal new_cookies
    new_cookies[name] = value
    new_cookies[name]['expires'] = '0'
  def deleteCookie(name):
    nonlocal new_cookies, moon
    new_cookies[name] = 'expiring'
    new_cookies[name]['expires'] = moon.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
  
  global getField, containsField, setField, saveFields, loadFields
  def getField(name, one = True):
    nonlocal form, fields
    fields[name] = fields.get(name, form.getfirst(name) if one else form.getlist(name))
    return fields[name]
  def containsField(name):
    nonlocal form, fields
    return name in fields or name in form
  def setField(name, value):
    nonlocal fields
    fields[name] = value
  def saveFields():
    nonlocal fields, urlsafe_b64encode, dumps
    return str(urlsafe_b64encode(dumps(fields,-1)))[2:-1]
  def loadFields(dictionary):
    nonlocal fields, loads, urlsafe_b64decode, UnpicklingError
    try:
      if dictionary:
        fields = loads(urlsafe_b64decode(bytes(dictionary, 'utf-8')))
    except UnpicklingError:
      pass
    
  global redirect, serve, AJAX, error
  def redirect(loc):
    nonlocal new_cookies
    print("Location: %s" % loc)
    print(new_cookies.output(sep = '\n'))
    print()
    exit(0)
  def AJAX(doc):
    global toJSON
    print("Content-type: text/plain")
    print()
    print(toJSON(doc))
    exit(0)
  def serve(name):
    global values
    nonlocal preprocess, new_cookies, path
    values['__COOKIES__'] = new_cookies.output(sep = '\n')
    folder = name.rsplit(".", 1)[1]
    try:
      preprocess(path.join(folder, name), values, None, "html")
    except IOError as e:
      if e.errno == 2:
        error(name, 404)
      else:
        raise
    preprocess(path.join(folder, name), values, root="html")
    exit(0)
  
  errmessages = {
    404 : 'Not Found'
  }
  def error(name, errno):
    global values
    nonlocal errmessages
    values['__ERRFILE__'] = name
    values['__ERRNO__'] = errno
    values['__ERRMESSAGE__'] = errmessages[errno]
    preprocess(path.join('html', '%d.html' % str(errno)), values)
    exit(0)
  try:
    setField('query_string', '?%s' % environ['QUERY_STRING'])
  except KeyError:
    setField('query_string', '')
  
  global values
  values = {
    'query_string' : getField('query_string'),
    'redirect' : ''
  }
  values['site_path'] = path.dirname(environ['SCRIPT_NAME'])
  values['file_path'] = environ['REDIRECT_URL'][len(values['site_path']):]
  if not path.splitext(values['file_path'])[1]:
    values['file_path'] = path.join(values['file_path'], '')
  values['file_dir'], values['file_name'] = path.split(values['file_path'])
  if not values['file_name']:
    values['file_name'] = 'index.html'
    values['file_path'] = path.join(values['file_dir'],values['file_name'])
Exemplo n.º 60
0
#!/usr/bin/python3
from cgi import FieldStorage
from json import dumps, loads
import os

args = FieldStorage()

error = 'Status: 200 OK\n'
content = 'Content-Type: text/html\n\n'

output = None
if 'SSL_CLIENT_S_DN_Email' in os.environ:
    output = {"kerb": os.environ['SSL_CLIENT_S_DN_Email']}
    # add to database or something more fancy, probably create a password, do fancy checks and stuff
else:
    error = 'Status: 401 Unauthorized\n'
    # click this link -- whatever you're at now plus https and :444
    # e.g. res.send("no certificate, please visit https://minecraft.scripts.mit.edu:444");

print(error + content)
print(dumps(output))