예제 #1
0
파일: suggest.py 프로젝트: phra/progettoTW
def index(req):
    req.content_type = 'text/plain; charset="UTF-8"'
    req.headers_out.add("Access-Control-Allow-Origin","*")
    if req.method != 'GET':
        req.status = A.HTTP_METHOD_NOT_ALLOWED
        req.write('405: METHOD NOT ALLOWED\r\n')
        req.write('metodo %s non permesso.\r\n' % req.method)
        raise A.SERVER_RETURN, A.DONE

    try:
        parms = util.FieldStorage(req)
        msg = smart_str(parms.getfirst('msg'))
        category = smart_str(parms.getfirst('category'))
        email = smart_str(parms.getfirst('email'))
    except:
        req.status = A.HTTP_NOT_ACCEPTABLE
        req.write('406: NOT ACCEPTABLE\r\n')
        req.write('parametri errati.')
        raise A.SERVER_RETURN, A.DONE

    conn = psycopg2.connect("dbname='trovatutto' user='******' password='******'")
    cur = conn.cursor()
    cur.execute("INSERT INTO suggest(msg,category,email) VALUES (%s,%s,%s);", (msg,category,email))
    conn.commit()
    cur.close()
    conn.close()
    req.write('Richiesta ricevuta, verrà valutata nelle prossime ore. GRAZIE per la segnalazione!')
    req.status = A.OK
    raise A.SERVER_RETURN, A.DONE
예제 #2
0
파일: http.py 프로젝트: MechanisM/gmapi
def urlquote(url, safe='/'):
    """
    A version of Python's urllib.quote() function that can operate on unicode
    strings. The url is first UTF-8 encoded before quoting. The returned string
    can safely be used as part of an argument to a subsequent iri_to_uri() call
    without double-quoting occurring.
    """
    return force_unicode(urllib.quote(smart_str(url), smart_str(safe)))
예제 #3
0
 def ident_attr(self,field,attr,v):
     field=smart_str(field)
     attr=smart_str(attr)
     v=smart_str(v)
     xml_field = self.xml.createElement(field)
     xml_field.setAttribute(attr, v)
     self.levelnode=self.levelnode.appendChild(xml_field) 
     self.level=self.level+1
예제 #4
0
파일: aggrcsv.py 프로젝트: phra/progettoTW
def handler(req):

	if not (('text/csv' in req.headers_in['Accept']) or ('text/x-python' in req.headers_in['Accept'])):
		req.content_type = 'text/plain; charset="UTF-8"'
		req.headers_out.add("Access-Control-Allow-Origin","*")
		req.status = A.HTTP_NOT_ACCEPTABLE
		req.write('406: NOT ACCEPTABLE\r\n')
		req.write('intersezione tra content-type vuota.\r\n')
		raise A.SERVER_RETURN, A.DONE
	
	req.content_type = 'text/plain; charset=utf-8'
	req.headers_out.add("Access-Control-Allow-Origin","*")
	if req.method != 'GET':
		req.status = A.HTTP_METHOD_NOT_ALLOWED
		req.write('405: METHOD NOT ALLOWED\r\n')
		req.write('metodo %s non permesso.\r\n' % req.method)
		raise A.SERVER_RETURN, A.DONE

	#req.write("let's try!\r\n")
	try:
		path = '/var/www/progettoTW/cgi-bin/aggregatore/csv/scuolematerneBO2011.csv'
		enc = 'utf-8'
		fd = codecs.open(path,'r',enc)
		attrs = ["id","category","name","address","lat","long","subcategory","note","opening","closing","creator","created","valid","version","source"]
		fd.readline()
		dump = csv.DictReader(fd, attrs, lineterminator='\n')
	except IOError:
		req.status = A.HTTP_INTERNAL_SERVER_ERROR
		req.write('500: INTERNAL SERVER ERROR\r\n')
		req.write('%s non trovato\r\n' % path)
		raise A.SERVER_RETURN, A.DONE	
	s = ''.join('id,category,name,address,lat,long,subcategory,note,opening,closing,creator,created,valid,version,source\n')

	try:
		parms = util.FieldStorage(req)		
		KEY = smart_str(parms.getfirst('key')).lower()
		COMP = smart_str(parms.getfirst('comp')).lower()
		VALUE = smart_str(parms.getfirst('value')).lower()
		if KEY == 'none' and COMP == 'none' and VALUE == 'none':
			raise Exception('foo')
		if KEY == 'none' or COMP == 'none' or VALUE == 'none':
			raise Exception('bar')
	except Exception, what:
		if what.args[0] == 'bar':
			req.status = A.HTTP_NOT_ACCEPTABLE
			req.write('406: NOT ACCEPTABLE\r\n')
			req.write('parametri insufficienti.\r\n')
			req.write('i parametri sono: %s %s %s\r\n\r\n' % (KEY, COMP, VALUE))
			raise A.SERVER_RETURN, A.DONE
		if what.args[0] == 'foo':
			req.content_type = 'text/csv'
			for line in dump:
				s += line['id']+','+line['category']+','+line['name']+',"'+line['address']+'",'+line['lat']+','+line['long']+','+line['subcategory']+','+line['note']+',"'+line['opening']+'","'+line['closing']+'",'+line['creator']+','+line['created']+','+line['valid']+','+line['version']+','+line['source']+'\n'
							
			req.write(smart_str(s))
			fd.close()
			req.status = A.OK
			raise A.SERVER_RETURN, A.DONE 
예제 #5
0
파일: aggrxml.py 프로젝트: phra/progettoTW
def handler(req):

	if not (('application/xml' in req.headers_in['Accept']) or ('text/x-python' in req.headers_in['Accept'])):
		req.content_type = 'text/plain; charset="UTF-8"'
		req.headers_out.add("Access-Control-Allow-Origin","*")
		req.status = A.HTTP_NOT_ACCEPTABLE
		req.write('406: NOT ACCEPTABLE\r\n')
		req.write('intersezione tra content-type vuota.\r\n')
		raise A.SERVER_RETURN, A.DONE
	
	req.content_type = 'text/plain; charset=utf-8'
	req.headers_out.add("Access-Control-Allow-Origin","*")
	
	if req.method != 'GET':
		req.status = A.HTTP_METHOD_NOT_ALLOWED
		req.write('405: METHOD NOT ALLOWED\r\n')
		req.write('metodo %s non permesso.\r\n' % req.method)
		raise A.SERVER_RETURN, A.DONE

	#req.write("let's try!\r\n")
	
	try:
		path = '/var/www/progettoTW/cgi-bin/aggregatore/xml/farma.xml'
		enc = 'utf-8'
		fd = codecs.open(path,'r',enc)
		file = fd.read()
		fd.close()
		dom = parseString(file.encode('utf-8'))
		root = dom.getElementsByTagName('locations')[0]
		metadata = root.getElementsByTagName('metadata')[0]
		locations = dom.getElementsByTagName('location')
	except IOError:
		req.status = A.HTTP_INTERNAL_SERVER_ERROR
		req.write('500: INTERNAL SERVER ERROR\r\n')
		req.write('%s non trovato\r\n' % path)
		raise A.SERVER_RETURN, A.DONE

	try:
		parms = util.FieldStorage(req)		
		KEY = smart_str(parms.getfirst('key')).lower()
		COMP = smart_str(parms.getfirst('comp')).lower()
		VALUE = smart_str(parms.getfirst('value')).lower()
		if KEY == 'none' and COMP == 'none' and VALUE == 'none':
			raise Exception('foo')
		if KEY == 'none' or COMP == 'none' or VALUE == 'none':
			raise Exception('bar')
	except Exception, what:
		if what.args[0] == 'bar':
			req.status = A.HTTP_NOT_ACCEPTABLE
			req.write('406: NOT ACCEPTABLE\r\n')
			req.write('parametri insufficienti.\r\n')
			req.write('i parametri sono: %s %s %s\r\n\r\n' % (KEY, COMP, VALUE))
			raise A.SERVER_RETURN, A.DONE
		if what.args[0] == 'foo':
			req.content_type = 'application/xml'
			req.write(smart_str(dom.toxml()))
			req.status = A.OK
			raise A.SERVER_RETURN, A.DONE
예제 #6
0
파일: http.py 프로젝트: crtr0/Twitter2FF
def urlencode(query, doseq=0):
    """
    A version of Python's urllib.urlencode() function that can operate on
    unicode strings. The parameters are first case to UTF-8 encoded strings and
    then encoded as per normal.
    """
    if hasattr(query, 'items'):
        query = query.items()
    return urllib.urlencode([(smart_str(k), smart_str(v)) for k,
        v in query], doseq)
예제 #7
0
def handler(req):
	
	if not (('application/json' in req.content_type) or ('application/xml' in req.content_type) or ('text/csv' in req.content_type) or ('text/turtle' in req.content_type) or ('text/x-python' in req.content_type)):
		req.content_type = 'text/plain'
		req.status = A.HTTP_NOT_ACCEPTABLE
		req.write('406: NOT ACCEPTABLE\r\n')
		req.write('intersezione tra content-type vuota.\r\n')
		raise A.SERVER_RETURN, A.DONE
	
	content_type = ''.join(req.content_type)
	req.content_type = 'text/plain'
	
	if req.method != 'GET':
		req.status = A.HTTP_METHOD_NOT_ALLOWED
		req.write('405: METHOD NOT ALLOWED\r\n')
		req.write('metodo %s non permesso.\r\n' % req.method)
		raise A.SERVER_RETURN, A.DONE

	#req.write("let's try!\r\n")+
	try:
		parms = util.FieldStorage(req)
		AGGR = parms.getlist('aggr')
		latA = float(parms.getfirst('lat'))
		lonA = float(parms.getfirst('long'))
		MAX = smart_str(parms.getfirst('max')).lower()
		DISTANZA = smart_str(parms.getfirst('distance')).lower()
	except:
		req.status = A.HTTP_NOT_ACCEPTABLE
		req.write('406: NOT ACCEPTABLE\r\n')
		req.write('parametri errati.')
		req.write('i parametri sono: %s %s %s\r\n\r\n' % (parms.getfirst('lat'), parms.getfirst('long'), latA))
		raise A.SERVER_RETURN, A.DONE
	#req.write(AGGR)
	listout = []
	
	RT = 6372795.477598
	radlatA = latA * (math.pi / 180.0)
	radlonA = lonA * (math.pi / 180.0)
	hosts = ['http://fattanza.no-ip.org/progettoTW/aggregatore/json/aggrjson.py','http://fattanza.no-ip.org/progettoTW/aggregatore/xml/aggrxml.py']
	
	for host in hosts:
		reqq = urllib2.Request(host)
		reqq.add_header('Accept', 'text/plain application/json application/xml text/turtle text/csv text/comma-separated-values')
		try:
			r = urllib2.urlopen(reqq)
		except urllib2.HTTPError, e:
			req.status = A.HTTP_INTERNAL_SERVER_ERROR
			req.write('500: INTERNAL SERVER ERROR\r\n')
			req.write('%s non raggiungibile. (errore: %d)\r\n' % (host,e.code))
			raise A.SERVER_RETURN, A.DONE
		except urllib2.URLError, e:
			req.status = A.HTTP_INTERNAL_SERVER_ERROR
			req.write('500: INTERNAL SERVER ERROR\r\n')
			req.write('%s non raggiungibile. (errore: %d)\r\n' % (host,e.args))
			raise A.SERVER_RETURN, A.DONE
예제 #8
0
    def message(self):
        encoding = self.encoding or DEFAULT_CHARSET
        msg = SafeMIMEText(smart_str(self.body, encoding),
                           self.content_subtype, encoding)
        msg = self._create_message(msg)
        msg['Subject'] = self.subject
        msg['From'] = self.extra_headers.get('From', self.from_email)
        if self.reply_to:
        	msg['Reply-To'] = self.reply_to
        msg['To'] = ', '.join(self.to)
        if self.cc:
            msg['Cc'] = ', '.join(self.cc)

        # Email header names are case-insensitive (RFC 2045), so we have to
        # accommodate that when doing comparisons.
        header_names = [key.lower() for key in self.extra_headers]
        if 'date' not in header_names:
            msg['Date'] = formatdate()
        if 'message-id' not in header_names:
            msg['Message-ID'] = make_msgid()
        for name, value in self.extra_headers.items():
            if name.lower() == 'from':  # From is already handled
                continue
            msg[name] = value
        return msg
예제 #9
0
    def run(self):
        try:
            self.mutex.lock()
            self.state = RunnableState.RUNNING
            s = SCSBucket(self.bucketName)
            if self.key.rfind('/') == len(self.key)-1 :
                m = (("prefix", smart_str(self.key)),
                     ("delimiter", '/'),
                     ("max-keys", 5),
                     ("formatter","json"))
                args = dict((str(k), str(v)) for (k, v) in m if v is not None)
                response = s.send(s.request(key='', args=args))
                files_generator = SCSListing.parse(response)
                
                if files_generator.contents_quantity > 0 or files_generator.common_prefixes_quantity > 0 :
                    for item in files_generator:
                        if cmp(item[0],self.key) != 0:
                            self.emitter.emit(QtCore.SIGNAL("DeleteObjectForbidden(PyQt_PyObject,PyQt_PyObject)"), self, u'不能删除非空目录(前缀) ')
                            return
            
#             s = SCSBucket(self.bucketName)
            self.response = s.send(s.request(method="DELETE", key=self.key))
        except SCSError, e:
            self.state = RunnableState.DID_FAILED
            self.response = SCSResponse(e.urllib2Request, e.urllib2Response)
            self.response._responseBody = e.data
            self.emitter.emit(QtCore.SIGNAL("DeleteObjectDidFailed(PyQt_PyObject,PyQt_PyObject)"), self, e.msg)
            return
예제 #10
0
파일: base_old.py 프로젝트: kitanata/Potion
    def execute(self, *args, **options):
        """
        Try to execute this command, performing model validation if
        needed (as controlled by the attribute
        ``self.requires_model_validation``). If the command raises a
        ``CommandError``, intercept it and print it sensibly to
        stderr.
        """
        show_traceback = options.get('traceback', False)

        # Switch to English, because django-admin.py creates database content
        # like permissions, and those shouldn't contain any translations.
        # But only do this if we can assume we have a working settings file,
        # because django.utils.translation requires settings.
        saved_lang = None
        if self.can_import_settings:
            try:
                from django.utils import translation
                saved_lang = translation.get_language()
                translation.activate('en-us')
            except ImportError, e:
                # If settings should be available, but aren't,
                # raise the error and quit.
                if show_traceback:
                    traceback.print_exc()
                else:
                    sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
                sys.exit(1)
예제 #11
0
    def message(self):
        encoding = self.encoding or DEFAULT_CHARSET
        msg = SafeMIMEText(smart_str(self.body, encoding),
                           self.content_subtype, encoding)
        msg = self._create_message(msg)
        msg['Subject'] = self.subject
        msg['From'] = self.extra_headers.get('From', self.from_email)
        if self.reply_to:
            msg['Reply-To'] = self.reply_to
        msg['To'] = ', '.join(self.to)
        if self.cc:
            msg['Cc'] = ', '.join(self.cc)

        # Email header names are case-insensitive (RFC 2045), so we have to
        # accommodate that when doing comparisons.
        header_names = [key.lower() for key in self.extra_headers]
        if 'date' not in header_names:
            msg['Date'] = formatdate()
        if 'message-id' not in header_names:
            msg['Message-ID'] = make_msgid()
        for name, value in self.extra_headers.items():
            if name.lower() == 'from':  # From is already handled
                continue
            msg[name] = value
        return msg
예제 #12
0
파일: lxml_tools.py 프로젝트: GrIvA/NB
def sanitize_html(html, encoding='utf-8', return_unicode=False):
    html = smart_str(html, encoding=encoding)
    if RE_TAG_START.search(html):
        html = render_html(parse_html(html))
    if return_unicode:
        return html.decode('utf-8')
    else:
        return html
예제 #13
0
파일: vicinoa.py 프로젝트: phra/progettoTW
def index(req):
    listout = []
    if not (('application/json' in req.headers_in['Accept']) or ('application/xml' in req.headers_in['Accept']) or ('text/csv' in req.headers_in['Accept']) or ('text/turtle' in req.headers_in['Accept']) or ('text/x-python' in req.headers_in['Accept'])):
        req.content_type = 'text/plain; charset="UTF-8"'
        req.headers_out.add("Access-Control-Allow-Origin","*")
        req.status = A.HTTP_NOT_ACCEPTABLE
        req.write('406: NOT ACCEPTABLE\r\n')
        req.write('intersezione tra content-type vuota.\r\n')
        raise A.SERVER_RETURN, A.DONE

    content_type = req.headers_in['Accept']
    req.content_type = 'text/plain; charset="UTF-8"'
    req.headers_out.add("Access-Control-Allow-Origin","*")
    if req.method != 'GET':
        req.status = A.HTTP_METHOD_NOT_ALLOWED
        req.write('405: METHOD NOT ALLOWED\r\n')
        req.write('metodo %s non permesso.\r\n' % req.method)
        raise A.SERVER_RETURN, A.DONE

    try:
        parms = util.FieldStorage(req)
        AGGRs = smart_str(parms.getfirst('aggr')).split('/')
        latA = float(parms.getfirst('lat'))
        lonA = float(parms.getfirst('long'))
        MAX = smart_str(parms.getfirst('max')).lower()
        DISTANZA = smart_str(parms.getfirst('distance')).lower()
        CATEGORY = smart_str(parms.getfirst('category')).lower()
    except:
        req.status = A.HTTP_NOT_ACCEPTABLE
        req.write('406: NOT ACCEPTABLE\r\n')
        req.write('parametri errati.')
        req.write('i parametri sono: lat: %s, long: %s[, max: %s, distance: %s]\r\nex: http://fattanza.no-ip.org/progettoTW/vicinoa/ltw1130-farmacie/params/44.500456/11.277643/10/5000\r\n' % (smart_str(parms.getfirst('lat')), smart_str(parms.getfirst('long')), smart_str(parms.getfirst('max')), smart_str(parms.getfirst('distance'))))
        raise A.SERVER_RETURN, A.DONE
    hosts = []
    host = 'http://fattanza.no-ip.org/progettoTW/metacatalogo'
    reqq = urllib2.Request(host)
    reqq.add_header('Accept', 'application/xml')
    try:
        r = urllib2.urlopen(reqq)
    except urllib2.HTTPError, e:
        req.status = A.HTTP_INTERNAL_SERVER_ERROR
        req.write('500: INTERNAL SERVER ERROR\r\n')
        req.write('%s non raggiungibile. (errore: %d)\r\n' % (host,e.code))
        raise A.SERVER_RETURN, A.DONE
예제 #14
0
    def add(self,field,value):
        field=smart_str(field)
        if value==None:
            value=""
        value=smart_str(value)
        if (self.xml == None) :
            self.xml=Document()
            xml_field = self.xml.createElement(field)
            if value != None :
                xml_value = self.xml.createTextNode(str(value))
                xml_field.appendChild(xml_value)
            self.levelnode=self.xml.appendChild(xml_field)
        else:
            xml_field = self.xml.createElement(field)
            if value != None :
                xml_value = self.xml.createTextNode(str(value))
                xml_field.appendChild(xml_value)
#            self.xml.childNodes[int(self.level-1)].appendChild(xml_field)
            self.levelnode.appendChild(xml_field)
예제 #15
0
파일: select.py 프로젝트: phra/progettoTW
def tojson(listout):
    dictoutjson = {}
    dictout = {}
    meta = [('creator', 'phra'), ('created', '20/12/2011'), ('version', '1.1')]
    metadata = dict(meta)
    for t in listout:
        dictout[t[0]] = {'lat': t[4], 'long': t[5], 'category': smart_str(t[2]), 'name': t[1], 'opening': t[7], 'closing': t[8], 'address': t[6], 'tel': t[9], 'subcategory': t[3], 'note': t[10]}
    dictoutjson['metadata'] = metadata
    dictoutjson['locations'] = dictout
    return json.dumps(dictoutjson)
예제 #16
0
파일: vicinoa.py 프로젝트: phra/progettoTW
def tojson(listout):
	dictoutjson = {}
	dictout = {}
	meta = [('creator', 'Working Group LTW 2011/2012'), ('created', '20/12/2011'), ('version', '1.1'), ('source', 'http://vitali.web.cs.unibo.it/TechWeb12/Formati'),('valid', '31/12/2011')]
	metadata = dict(meta)
	for t in listout:
		dictout[t[0]] = {'lat': t[1], 'long': t[2], 'category': smart_str(t[3]), 'name': t[4], 'opening': t[5], 'closing': t[6], 'address': t[7], 'tel': t[8], 'subcategory': t[9], 'note': t[10], 'distance': t[11]}
	dictoutjson['metadata'] = metadata
	dictoutjson['locations'] = dictout
	return json.dumps(dictoutjson)
예제 #17
0
파일: id.py 프로젝트: phra/progettoTW
def index(req):

	if not (('application/json' in req.headers_in['Accept']) or ('application/xml' in req.headers_in['Accept']) or ('text/csv' in req.headers_in['Accept']) or ('text/turtle' in req.headers_in['Accept']) or ('text/html' in req.headers_in['Accept'])):
		req.content_type = 'text/plain; charset="UTF-8"'
		req.status = A.HTTP_NOT_ACCEPTABLE
		req.write('406: NOT ACCEPTABLE\r\n')
		req.write('intersezione tra content-type vuota.\r\n')
		raise A.SERVER_RETURN, A.DONE

	accept = req.headers_in['Accept']
	req.content_type = 'text/plain; charset="UTF-8"'
	req.headers_out.add("Access-Control-Allow-Origin","*")

	if req.method != 'GET':
		req.status = A.HTTP_METHOD_NOT_ALLOWED
		req.write('405: METHOD NOT ALLOWED\r\n')
		req.write('metodo %s non permesso.\r\n' % req.method)
		raise A.SERVER_RETURN, A.DONE

	#req.write("let's try!\r\n")+
	try:
		parms = util.FieldStorage(req)
		AGGRs = smart_str(parms.getfirst('aggr')).split('/')
		IDs = smart_str(parms.getfirst('id')).split('/')
	except:
		req.status = A.HTTP_NOT_ACCEPTABLE
		req.write('406: NOT ACCEPTABLE\r\n')
		req.write('parametri errati.')
		raise A.SERVER_RETURN, A.DONE
	#req.write(AGGR)
	dictout = {}
	hosts = []
	host = 'http://fattanza.no-ip.org/progettoTW/metacatalogo'
	reqq = urllib2.Request(host)
	reqq.add_header('Accept', 'application/xml')
	try:
		r = urllib2.urlopen(reqq)
	except urllib2.HTTPError, e:
		req.status = A.HTTP_INTERNAL_SERVER_ERROR
		req.write('500: INTERNAL SERVER ERROR\r\n')
		req.write('%s non raggiungibile. (errore: %d)\r\n' % (host,e.code))
		raise A.SERVER_RETURN, A.DONE
예제 #18
0
파일: utils.py 프로젝트: malstor/crawtext
def encodeValue(value):
    if value is None:
        return u''
    string_org = value
    try:
        value = encoding.smart_unicode(value)
    except (UnicodeEncodeError, encoding.DjangoUnicodeDecodeError):
        value = encoding.smart_str(value)
    except:
        value = string_org
    return value.strip()
예제 #19
0
    def __repr__(self):
        if self.fen_name == None:
            xml = dbXML("FENOTIPO", "No Fenotipo Loaded")
            return str(xml)
        else:

            xml = dbXML("FENOTIPO")
            xml.add("COLNUM", self.fen_name)
            xml.add("W", smart_str(self.fen_w))
            xml.add("N", smart_str(self.fen_n))
            xml.add("COUNTRY", self.fen_country)
            xml.add("WINEREGION", self.fen_wineregion)
            xml.add("VINEYARD", self.fen_vineyard)
            xml.add("SAMPLINGSITE", self.fen_samplingsite)
            xml.add("GRAPEVAR", self.fen_grapevar)
            xml.add("SCAAT1-1", self.fen_ScAAT1_1)
            xml.add("SCAAT1-2", self.fen_ScAAT1_2)
            xml.add("SCAAT2-1", self.fen_ScAAT2_1)
            xml.add("SCAAT2-2", self.fen_ScAAT2_2)
            xml.add("SCAAT3-1", self.fen_ScAAT3_1)
            xml.add("SCAAT3-2", self.fen_ScAAT3_2)
            xml.add("SCAAT4-1", self.fen_ScAAT4_1)
            xml.add("SCAAT4-2", self.fen_ScAAT4_2)
            xml.add("SCAAT5-1", self.fen_ScAAT5_1)
            xml.add("SCAAT5-2", self.fen_ScAAT5_2)
            xml.add("SCAAT6-1", self.fen_ScAAT6_1)
            xml.add("SCAAT6-2", self.fen_ScAAT6_2)
            xml.add("C4-1", self.fen_C4_1)
            xml.add("C4-2", self.fen_C4_2)
            xml.add("C5-1", self.fen_C5_1)
            xml.add("C5-2", self.fen_C5_2)
            xml.add("C11-1", self.fen_C11_2)
            xml.add("C11-2", self.fen_C11_1)
            xml.add("YPL009C-1", self.fen_YPL009c_1)
            xml.add("YPL009C-2", self.fen_YPL009c_2)
            xml.add("YOR267C-1", self.fen_YOR267c_1)
            xml.add("YOR267C-2", self.fen_YOR267c_2)

            return str(xml)
예제 #20
0
파일: select.py 프로젝트: phra/progettoTW
def toxml(listout):
    s = '''<?xml version="1.0" encoding="UTF-8"?>
<locations>
    <metadata>
        <creator>phra</creator>
        <created>12/20/2011</created>
        <version>1.2</version>
        <note>Le date sono in formato americano: MM/GG/AAAA</note>
    </metadata>
'''
    for t in listout:
        s += '''<location id="%s" lat="%s" long="%s">
        <category> %s </category>
        <subcategory> %s </subcategory>
        <name> %s </name>
        <address> %s </address>
        <tel> %s </tel>
        <opening> %s </opening>
        <closing> %s </closing>
        <note> %s </note>
        </location>''' % (smart_str(t[0]),smart_str(t[4]),smart_str(t[5]),smart_str(t[2]),smart_str(t[3]),smart_str(t[1]),smart_str(t[6]),smart_str(t[9]),smart_str(t[7]),smart_str(t[8]),smart_str(t[10]))
    s += '</locations>'
    return s
예제 #21
0
 def _create_mime_attachment(self, content, mimetype):
     """
     Converts the content, mimetype pair into a MIME attachment object.
     """
     basetype, subtype = mimetype.split('/', 1)
     if basetype == 'text':
         encoding = self.encoding or DEFAULT_CHARSET
         attachment = SafeMIMEText(smart_str(content, encoding), subtype, encoding)
     else:
         # Encode non-text attachments with base64.
         attachment = MIMEBase(basetype, subtype)
         attachment.set_payload(content)
         Encoders.encode_base64(attachment)
     return attachment
예제 #22
0
파일: vicinoa.py 프로젝트: phra/progettoTW
def toxml(listout):
	s = '''<?xml version="1.0" encoding="UTF-8"?>
<locations>
	<metadata>
		<creator>Working Group LTW 2011/2012</creator>
		<created>12/20/2011</created>
		<version>1.2</version>
		<source>http://vitali.web.cs.unibo.it/TechWeb12/Formati</source>
		<valid>02/21/2011</valid>
		<note>Le date sono in formato americano: MM/GG/AAAA</note>
	</metadata>
'''
	for t in listout:
		s += '''<location id="%s" lat="%s" long="%s">
		<category> %s </category>
		<subcategory> %s </subcategory>
		<name> %s </name>
		<address> %s </address>
		<tel> %s </tel>
		<opening> %s </opening>
		<closing> %s </closing>
		</location>''' % (smart_str(t[0]),smart_str(t[1]),smart_str(t[2]),smart_str(t[3]),smart_str(t[9]),smart_str(t[4]),smart_str(t[7]),smart_str(t[8]),smart_str(t[5]),smart_str(t[6]))
	s += '</locations>'
	return s
예제 #23
0
 def _create_mime_attachment(self, content, mimetype):
     """
     Converts the content, mimetype pair into a MIME attachment object.
     """
     basetype, subtype = mimetype.split('/', 1)
     if basetype == 'text':
         encoding = self.encoding or DEFAULT_CHARSET
         attachment = SafeMIMEText(smart_str(content, encoding), subtype,
                                   encoding)
     else:
         # Encode non-text attachments with base64.
         attachment = MIMEBase(basetype, subtype)
         attachment.set_payload(content)
         Encoders.encode_base64(attachment)
     return attachment
예제 #24
0
 def to_python(self, value):
     """
     Validates that the input is a decimal number. Returns a Decimal
     instance. Returns None for empty values. Ensures that there are no more
     than max_digits in the number, and no more than decimal_places digits
     after the decimal point.
     """
     if value in validators.EMPTY_VALUES:
         return None
     #value = formats.sanitize_separators(value)
     value = smart_str(value).strip()
     try:
         value = Decimal(value)
     except DecimalException:
         raise ValidationError(self.error_messages['invalid'])
     return value
예제 #25
0
    def run(self):
        try:
            self.mutex.lock()
            self.state = RunnableState.RUNNING
            s = SCSBucket(self.bucketName)
            #             if self.key.rfind('/') == len(self.key)-1 :
            #                 m = (("prefix", smart_str(self.key)),
            #                      ("delimiter", '/'),
            #                      ("max-keys", 5),
            #                      ("formatter","json"))
            #                 args = dict((str(k), str(v)) for (k, v) in m if v is not None)
            #                 response = s.send(s.request(key='', args=args))
            #                 files_generator = SCSListing.parse(response)
            #
            #                 if files_generator.contents_quantity > 0 or files_generator.common_prefixes_quantity > 0 :
            #                     for item in files_generator:
            #                         if cmp(item[0],self.key) != 0:
            #                             self.emitter.emit(QtCore.SIGNAL("DeleteObjectForbidden(PyQt_PyObject,PyQt_PyObject)"), self, u'不能删除非空目录(前缀) ')
            #                             return

            #             s = SCSBucket(self.bucketName)

            if self.key.endswith('/') is not True:  #文件
                self.response = s.send(s.request(method="DELETE",
                                                 key=self.key))
            else:  #目录
                m = (("prefix", smart_str(self.key)), ("formatter", "json"))
                args = dict((str(k), str(v)) for (k, v) in m if v is not None)
                response = s.send(s.request(key='', args=args))
                files_generator = SCSListing.parse(response)
                ''' 根据bucketName获取bucket下得所有文件 '''
                #name, isPrefix, sha1, expiration_time, modify, owner, md5, content_type, size
                for item in files_generator:
                    fileNameStr = item[0]
                    if not item[1]:
                        self.response = s.send(
                            s.request(method="DELETE", key=fileNameStr))

        except SCSError, e:
            self.state = RunnableState.DID_FAILED
            self.response = SCSResponse(e.urllib2Request, e.urllib2Response)
            self.response._responseBody = e.data
            self.emitter.emit(
                QtCore.SIGNAL(
                    "DeleteObjectDidFailed(PyQt_PyObject,PyQt_PyObject)"),
                self, e.msg)
            return
예제 #26
0
 def run(self):
     try:
         self.mutex.lock()
         self.state = RunnableState.RUNNING
         s = SCSBucket(self.bucketName)
         m = (("prefix", smart_str(self.prefix)),
              ("marker", self.marker),
              ("max-keys", self.limit),
              ("delimiter", self.delimiter),
              ("formatter","json"))
         args = dict((str(k), str(v)) for (k, v) in m if v is not None)
         self.response = s.send(s.request(key='', args=args))
         self.files_generator = SCSListing.parse(self.response)
     except SCSError, e:
         self.state = RunnableState.DID_FAILED
         self.response = SCSResponse(e.urllib2Request, e.urllib2Response)
         self.response._responseBody = e.data
         self.emitter.emit(QtCore.SIGNAL("ListDirDidFailed(PyQt_PyObject,PyQt_PyObject)"), self, e.msg)
         return
예제 #27
0
 def run(self):
     try:
         self.mutex.lock()
         self.state = RunnableState.RUNNING
         s = SCSBucket(self.bucketName)
         m = (("prefix", smart_str(self.prefix)), ("marker", self.marker),
              ("max-keys", self.limit), ("delimiter", self.delimiter),
              ("formatter", "json"))
         args = dict((str(k), str(v)) for (k, v) in m if v is not None)
         self.response = s.send(s.request(key='', args=args))
         self.files_generator = SCSListing.parse(self.response)
     except SCSError, e:
         self.state = RunnableState.DID_FAILED
         self.response = SCSResponse(e.urllib2Request, e.urllib2Response)
         self.response._responseBody = e.data
         self.emitter.emit(
             QtCore.SIGNAL("ListDirDidFailed(PyQt_PyObject,PyQt_PyObject)"),
             self, e.msg)
         return
예제 #28
0
파일: add.py 프로젝트: phra/progettoTW
def index(req):
    req.content_type = 'text/plain; charset="UTF-8"'
    req.headers_out.add("Access-Control-Allow-Origin","*")
    if req.method != 'GET':
        req.status = A.HTTP_METHOD_NOT_ALLOWED
        req.write('405: METHOD NOT ALLOWED\r\n')
        req.write('metodo %s non permesso.\r\n' % req.method)
        raise A.SERVER_RETURN, A.DONE

    try:
        parms = util.FieldStorage(req)
        category = smart_str(parms.getfirst('category'))
        lat = float(parms.getfirst('lat'))
        long = float(parms.getfirst('long'))
        name = smart_str(parms.getfirst('name'))
        address = smart_str(parms.getfirst('address'))
        subcategory = smart_str(parms.getfirst('subcategory'))
        opening = smart_str(parms.getfirst('opening'))
        note = smart_str(parms.getfirst('note'))
        tel = smart_str(parms.getfirst('tel'))
        closing = smart_str(parms.getfirst('closing'))
    except:
        req.status = A.HTTP_NOT_ACCEPTABLE
        req.write('406: NOT ACCEPTABLE\r\n')
        req.write('parametri errati.')
        raise A.SERVER_RETURN, A.DONE

    conn = psycopg2.connect("dbname='trovatutto' user='******' password='******'")
    cur = conn.cursor()
    cur.execute("INSERT INTO waiting(name,category,address,latitude,longitude,opening,closing,tel,note,subcategory) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);\n", (name,category,address,lat,long,opening,closing,tel,note,subcategory))
    conn.commit()
    cur.close()
    conn.close()
    req.write('Richiesta ricevuta, verrà valutata nelle prossime ore. GRAZIE per la segnalazione!')
    req.status = A.OK
    raise A.SERVER_RETURN, A.DONE
예제 #29
0
파일: select.py 프로젝트: phra/progettoTW
def index(req):
    listout = []
    if not (('application/json' in req.headers_in['Accept']) or ('application/xml' in req.headers_in['Accept']) or ('text/csv' in req.headers_in['Accept'])):
        req.content_type = 'text/plain; charset="UTF-8"'
        req.headers_out.add("Access-Control-Allow-Origin","*")
        req.status = A.HTTP_NOT_ACCEPTABLE
        req.write('406: NOT ACCEPTABLE\r\n')
        req.write('intersezione tra content-type vuota.\r\n')
        raise A.SERVER_RETURN, A.DONE

    content_type = req.headers_in['Accept']
    req.content_type = 'text/plain; charset="UTF-8"'
    req.headers_out.add("Access-Control-Allow-Origin","*")
    if req.method != 'GET':
        req.status = A.HTTP_METHOD_NOT_ALLOWED
        req.write('405: METHOD NOT ALLOWED\r\n')
        req.write('metodo %s non permesso.\r\n' % req.method)
        raise A.SERVER_RETURN, A.DONE
    parms = util.FieldStorage(req)
    name = smart_str(parms.getfirst('name')).lower()
    id = smart_str(parms.getfirst('id')).lower()
    category = smart_str(parms.getfirst('category')).lower()
    address = smart_str(parms.getfirst('address')).lower()
    conn = psycopg2.connect("dbname='trovatutto' user='******' password='******'")
    cur = conn.cursor()
    if id != 'none':
        cur.execute("SELECT * FROM locations a WHERE a.id = %s;", (id,))
    elif name != 'none':
        if category != 'none':
            if address != 'none':
                cur.execute("SELECT * FROM locations WHERE POSITION(%s IN LOWER(name)) > 0 AND category = %s AND POSITION(%s IN LOWER(address)) > 0 UNION ALL SELECT * FROM waiting WHERE POSITION(%s IN LOWER(name)) > 0 AND category = %s AND POSITION(%s IN LOWER(address)) > 0 ;",(name,category,address,name,category,address))
            else:
                cur.execute("SELECT * FROM locations WHERE POSITION(%s IN LOWER(name)) > 0 AND category = %s UNION ALL SELECT * FROM waiting WHERE POSITION(%s IN LOWER(name)) > 0 AND category = %s;",(name,category,name,category))
        else:
            if address != 'none':
                cur.execute("SELECT * FROM locations WHERE POSITION(%s IN LOWER(name)) > 0 AND POSITION(%s IN LOWER(address)) > 0 UNION ALL SELECT * FROM waiting WHERE POSITION(%s IN LOWER(name)) > 0 AND POSITION(%s IN LOWER(address)) > 0;",(name,address,name,address))
            else:
                cur.execute("SELECT * FROM locations WHERE POSITION(%s IN LOWER(name)) > 0 UNION ALL SELECT * FROM waiting WHERE POSITION(%s IN LOWER(name)) > 0;",(name,name))
    else:
        if category != 'none':
            if address != 'none':
                cur.execute("SELECT * FROM locations WHERE category = %s AND POSITION(%s IN LOWER(address)) > 0 UNION ALL SELECT * FROM waiting WHERE category = %s AND POSITION(%s IN LOWER(address)) > 0;",(category,address,category,address))
            else:
                cur.execute("SELECT * FROM locations WHERE category = %s UNION ALL SELECT * FROM waiting WHERE category = %s;",(category,category))
        else:
            if address != 'none':
                cur.execute("SELECT * FROM locations WHERE POSITION(%s in LOWER(address)) > 0 UNION ALL SELECT * FROM waiting WHERE POSITION(%s in LOWER(address)) > 0;",(address,address))
            else:
                cur.execute("SELECT * FROM locations UNION ALL SELECT * FROM waiting;")
    results = cur.fetchall()
    conn.commit()
    cur.close()
    conn.close()

    if 'application/json' in content_type:
        req.content_type = 'application/json; charset=utf-8'
        req.write(tojson(results))
    elif 'application/xml' in content_type:
        req.content_type = 'application/xml; charset=utf-8'
        req.write(toxml(results))
    elif 'text/csv' in content_type:
        req.content_type = 'text/cvs; charset=utf-8'
        req.write(tocsv(results))
    else:
        req.content_type = 'text/plain; charset=utf-8'
        req.write(toplain(results))

    req.status = A.OK
    raise A.SERVER_RETURN, A.DONE
예제 #30
0
파일: select.py 프로젝트: phra/progettoTW
def toplain(listout):
    s = '\n'.join('RESULT|||V') + '\n'
    for tupla in listout:
        s += 'ID: ' + smart_str(tupla[0]) + ', NAME: ' + smart_str(tupla[1]) + ', LAT: ' + smart_str(tupla[4]) + ', LONG: ' + smart_str(tupla[5]) + '.\n'
    return s
예제 #31
0
파일: aggrjson.py 프로젝트: phra/progettoTW
		if what.args[0] == 'bar':
			req.status = A.HTTP_NOT_ACCEPTABLE
			req.write('406: NOT ACCEPTABLE\r\n')
			req.write('parametri insufficienti.\r\n')
			req.write('i parametri sono: %s %s %s\r\n\r\n' % (KEY, COMP, VALUE))
			raise A.SERVER_RETURN, A.DONE
		if what.args[0] == 'foo':
			req.content_type = 'application/json'
			req.write(json.dumps(dump))
			req.status = A.OK
			raise A.SERVER_RETURN, A.DONE

	if (KEY == 'id'):
		if (COMP == 'eq'):
			for id,value in locations.items():
				if not smart_str(id).lower() == VALUE:
					#req.write('ID OK -> %s \r\n' % id)
					del(locations[id])
		elif (COMP == 'ne'):
			for id,value in locations.items():
				if not smart_str(id).lower() != VALUE:
					#req.write('ID OK -> %s \r\n' % id)
					del(locations[id])
		elif (COMP == 'contains'):
			for id,value in locations.items():
				if not VALUE in smart_str(id).lower():
					#req.write('ID OK -> %s \r\n' % id)
					del(locations[id])
		else:
			req.status = A.HTTP_NOT_ACCEPTABLE
			req.write('406: NOT ACCEPTABLE\r\n')
예제 #32
0
파일: id.py 프로젝트: phra/progettoTW
	reqq = urllib2.Request(host)
	reqq.add_header('Accept', 'text/plain application/json application/xml text/turtle text/csv text/comma-separated-values')
	try:
		r = urllib2.urlopen(reqq)
	except urllib2.HTTPError, e:
		req.status = A.HTTP_INTERNAL_SERVER_ERROR
		req.write('500: INTERNAL SERVER ERROR\r\n')
		req.write('%s non raggiungibile. (errore: %d)\r\n' % (host,e.code))
		raise A.SERVER_RETURN, A.DONE
	except urllib2.URLError, e:
		req.status = A.HTTP_INTERNAL_SERVER_ERROR
		req.write('500: INTERNAL SERVER ERROR\r\n')
		req.write('%s non raggiungibile. (errore: %d)\r\n' % (host,e.args[0]))
		raise A.SERVER_RETURN, A.DONE

	if 'application/json' in smart_str(r.info().getheader('Content-Type')):
		data = smart_str(r.read())
		dump = json.loads(data)
		locations = dump['locations']
		metadata = dump['metadata']

		for id, value in locations.items():
			for ID in IDs:
				if smart_str(id).lower() == smart_str(ID).lower():
					lat = smart_str(value['lat'])
					long = smart_str(value['long'])
					category = smart_str(value['category'])
					name = smart_str(value['name'])
					opening = smart_str(value['opening'])
					closing = smart_str(value['closing'])
					tel = smart_str(value['tel'])
예제 #33
0
파일: vicinoa.py 프로젝트: phra/progettoTW
def toplain(listout):
	s = '\n'.join('RESULT|||V') + '\n'
	for tupla in listout:
		s += 'ID: ' + smart_str(tupla[0]) + ', LAT: ' + smart_str(tupla[1]) + ', LONG: ' + smart_str(tupla[2]) + ', DISTANZA: ' + smart_str(tupla[11]) + '.\n'
	return s
예제 #34
0
파일: vicinoa.py 프로젝트: phra/progettoTW
	reqq = urllib2.Request(host)
	reqq.add_header('Accept', 'text/plain application/json application/xml text/turtle text/csv text/comma-separated-values')
	try:
		r = urllib2.urlopen(reqq)
	except urllib2.HTTPError, e:
		req.status = A.HTTP_INTERNAL_SERVER_ERROR
		req.write('500: INTERNAL SERVER ERROR\r\n')
		req.write('%s non raggiungibile. (errore: %d)\r\n' % (host,e.code))
		raise A.SERVER_RETURN, A.DONE
	except urllib2.URLError, e:
		req.status = A.HTTP_INTERNAL_SERVER_ERROR
		req.write('500: INTERNAL SERVER ERROR\r\n')
		req.write('%s non raggiungibile. (errore: %d)\r\n' % (host,e.args[0]))
		raise A.SERVER_RETURN, A.DONE

	if 'application/json' in smart_str(r.info().getheader('Content-Type')):
		data = smart_str(r.read())
		dump = json.loads(data)
		locations = dump['locations']
		metadata = dump['metadata']
		for id, value in locations.items():
			latB = float(value['lat'])
			lonB = float(value['long'])
			category = smart_str(value['category']).lower()
			radlatB = latB * (math.pi / 180.0)
			radlonB = lonB * (math.pi / 180.0)
			a = RT * math.acos(math.sin(radlatA) * math.sin(radlatB) + math.cos(radlatA) * math.cos(radlatB) * math.cos(radlonA - radlonB))
			if (DISTANZA == 'none') or (a < float(DISTANZA)):
				if category == CATEGORY or CATEGORY == '*' or CATEGORY == 'none':
					lat = smart_str(value['lat'])
					long = smart_str(value['long'])