示例#1
0
文件: webctx.py 项目: wunderlins/ha
    def GET(self):

        conn, cursor = oraconn()

        today = datetime.datetime.now()  # + datetime.timedelta(days=1)
        yesterday = datetime.datetime.now() - datetime.timedelta(days=1)

        sql = """SELECT o.ID, o.STMNAME, o.STMVORNAME, substr(o.OPTEXT, 0, 50)
		FROM DATO_OP o
		WHERE (o.OPDATUM = '""" + str(today.strftime("%Y%m%d")) + """' OR 
			o.OPDATUM = '""" + str(yesterday.strftime("%Y%m%d")) + """' )
			AND o.TSCANCEL IS NULL AND (o.DEL IS NULL OR o.DEL = 'N')
		ORDER BY o.STMNAME, o.STMVORNAME"""

        #web.debug(sql)
        #web.debug(conn)
        #web.debug(cursor)

        res = []

        try:
            cursor.execute(sql)
        except Exception, e:
            web.debug(e)
            return "database error"
示例#2
0
    def parse_action_impl(self, action, table, db):
        if action == 'set_user':
            username = self.qs_dict.get('username')
            if not username:
                set_status_code(web, 400)
                return result_template('''Illegal parameters: no "username"''')
            username = ''.join(username)

            data = web.data()
            # TODO

            if debug:
                web.debug('DB action=set_user, username=%s' % username)
            username = db.set_user(username, {'data': data})
            return username
        if action == 'get_user':
            username = self.qs_dict.get('username')
            if not username:
                set_status_code(web, 400)
                return result_template('''Illegal parameters: no "username"''')
            username = ''.join(username)

            if debug:
                web.debug('DB action=get_user, username=%s' % username)
            data = db.load_user(username)
            return username_data_template(username, data['data'], data['_id'])
示例#3
0
    def GET(self):
        params = web.input()
        username = params.username
        password = params.password
        domain = params.ddns
        if domain is None:
            raise web.HTTPError("422 Unprocessable Entity",
                                {'content-type': 'text/html'},
                                "Error: ddns not in right form")
        user = validate_user(username, password)
        if user is None:
            raise web.HTTPError("401 Unauthorized",
                                {'content-type': 'text/html'}, "Error: login")
        userid = user.ID
        results = db.query(
            'SELECT * FROM DDNS WHERE domain=$domain AND user_id=$user_id',
            vars={
                'domain': domain,
                'user_id': userid
            })

        domains = [dom['domain'] for dom in results]
        if domain in domains:
            return 'Error: already authorized.'

        try:
            db_result = db.insert('DDNS', user_id=userid, domain=domain)
            web.debug('db.delete: %s' % db_result)
            return 'OK'
        except Exception as e:
            web.debug(traceback.print_exc())
            raise web.HTTPError("400 Bad Request",
                                {'content-type': 'text/html'},
                                traceback.print_exc())
示例#4
0
	def POST(self):
		x = web.input(myfile={})
		name = web.debug(x['myfile'].filename) # This is the filename
		web.debug(x['myfile'].value) # This is the file contents
		web.debug(x['myfile'].file.read()) # Or use a filline object
		form = web.input(contents=None)
		return render.uploaded(name = str(name), contents = form.contents) 		
示例#5
0
    def parse_action(self, web, db):

        web.header('Content-Type', 'text/json')
        cookie = web.cookies()
        login, user, token = check_login(cookie)
        if not login:
            set_status_code(web, 401)
            return not_login_template()

        qs = web.ctx.env.get('QUERY_STRING')
        if not qs:
            set_status_code(web, 400)
            return result_template('''No parameters''')
        self.qs_dict = urlparse.parse_qs(qs)

        action = self.qs_dict.get('action')
        table = self.qs_dict.get('table')
        if not action or not table:
            set_status_code(web, 400)
            return result_template('''Illegal parameters: no "action" nor "table"''')
        action = ''.join(action)
        table = ''.join(table)
        if action in self.actions:
            try:
                return self.parse_action_impl(action, table, db)
            except Exception, e:
                web.debug(str(e))
                set_status_code(web, 500)
                return exception_template(e)
示例#6
0
        def db_body(db):

            srow = DatabaseSessionStateProvider.set_msg_context(self, manager, context, sessionids, db)

            if srow:
                # set oauth-related extensions on context
                context.session.token_type = srow.token_type
                context.session.secret = srow.secret
                context.session.client_secret = srow.client_secret

                if srow.aux_json != None:
                    aux = jsonReader(srow.aux_json)
                else:
                    aux = None

                context.session.aux = aux

                data_store = Oauth1aDataStore(context.session)
                oauth_server = oauth.oauth.OAuthServer(data_store)
                oauth_server.add_signature_method(oauth.oauth.OAuthSignatureMethod_HMAC_SHA1())
    
                try:
                    oauth_server.verify_request(context.oauth_request)
                except oauth.oauth.OAuthError, te:
                    if hasattr(te, 'message'):
                        web.debug(te.message)
                    # clear session-related state on invalid signature
                    context.oauth_request = None
                    context.client = None
                    context.attributes = set()
                    context.session = None
示例#7
0
    def POST(self):
        x = web.input(myfile={})
        web.debug(x['myfile'].filename)
        #web.debug(x['myfile'].value)
        web.debug(x['myfile'].file.read())

        raise web.seeother('/upload')
示例#8
0
def modify_userName(userId, newUserName):
    try:
        db.query("update users set userName=$nun where userId=$uId", vars={"uId": userId, "nun": newUserName})
        return get_user(userId)
    except Exception, e:
        web.debug("users.modify_userName: failed in modify database", e)
        return None
示例#9
0
 def publish(self, obj):
     web.debug("publishing")
     Feed.publish(
         self,
         '<script type="text/javascript">window.parent.%s(%s)</script>'
         % (self.callback, json.dumps(obj) + " " * 2048),
     )
示例#10
0
    def GET(self):
        if 'facebook_access_token' in web.ctx.session:
            raise web.found(web.ctx.path_url + '/authorized')

        data = web.input(error=None, code=None)

        if data.error:
            # The client denied permissions to the app
            # XXX flash some message here
            raise web.found('/')

        if data.code is None:
            raise web.found(AUTHORIZE_URL + '?' + urllib.urlencode(
                dict(client_id=web.config.FACEBOOK_APP_ID,
                     redirect_uri=web.ctx.path_url,
                     response_type='code',
                     scope='')))

        consumer = oauth2.Consumer(web.config.FACEBOOK_APP_ID,
                                   web.config.FACEBOOK_APP_SECRET)
        client = oauth2.Client(consumer)
        (resp, content) = client.request(
            ACCESS_TOKEN_URL + '?' + urllib.urlencode(
                dict(code=data.code,
                     client_id=web.config.FACEBOOK_APP_ID,
                     client_secret=web.config.FACEBOOK_APP_SECRET,
                     redirect_uri=web.ctx.path_url)), 'GET')
        if resp['status'] != '200':
            # XXX flash some message here
            web.debug(content)
            raise web.found('/')

        access_token = urlparse.parse_qs(content)
        web.ctx.session['facebook_access_token'] = access_token
        raise web.found(web.ctx.path_url + '/authorized')
示例#11
0
文件: webctx.py 项目: wunderlins/ha
    def POST(self):
        raw_data = web.data()
        conn, cursor = oraconn()

        web.header('Content-Type', 'application/json')

        try:
            data = json.loads(raw_data)
        except:
            return '{"success": false, "message": "Failed to decode json string"}'

        try:
            data["ma"]["datum"] = datetime.datetime.strptime(
                data["ma"]["datum"], '%d.%m.%Y')
        except:
            return "Failed to parse input date"

        #web.debug(data["ma"])

        # update metadata

        sql = "SELECT DATUM FROM DATO_HOLDINGAREA_STAFF WHERE DATUM = TO_DATE('%s', 'YYYYMMDD')" % \
               data["ma"]["datum"].strftime('%Y%m%d')
        web.debug(sql)
        try:
            cursor.execute(sql)
        except Exception, e:
            #web.debug(e)
            return '{"success": false, "message": "Failed to query metadata in database"}'
示例#12
0
文件: table.py 项目: ytfqj/ermrest
 def execute_if(sql):
     if sql:
         try:
             cur.execute(sql)
         except:
             web.debug('Got error executing SQL: %s' % sql)
             raise
示例#13
0
文件: model.py 项目: kim0051/yaf_auc
def table_def(meta, delkey):
    clear_mappers()
    web.debug('calling table_def')
    check_items = Table(
        'check_items',
        meta,
        Column('id', String(255), primary_key=True),
        Column('AuctionID',
               String(255),
               index=True,
               default=u"",
               nullable=False),
        Column('SellerId',
               String(255),
               index=True,
               default=u"",
               nullable=False),
        Column('Title', Unicode(255), index=True, default=u"", nullable=False),
        Column('CreatedAt', DateTime, default=func.now(), nullable=False),
        Column('EndTime', DateTime, default=func.now(), nullable=False),
        Column('Bids', Integer, index=True, nullable=False),
        Column('CategoryId', Integer, index=True, nullable=False),
        Column('CurrentPrice', Integer, index=True, nullable=False),
        Column('BidOrBuy', Integer, index=True, nullable=True),
        Column('CategoryIdPath', String(255), index=True, nullable=False),
        Column('ItemUrl', String(255), index=True, nullable=False),
        Column('AuctionItemUrl', String(255), index=True, nullable=False),
        Column('InsertedAt', DateTime, default=func.now(), nullable=False),
    )
    mapper(CheckItem, check_items)

    #Index('tag_order',tag.c.date,tag.c.tag_name_id)
    #Index('tag_count',tag.c.date,tag.c.tagcount)

    def isDel(attr):
        if attr in delkey and delkey[attr] == True:
            return True
        else:
            return False

    def tbl_delete(delk, tbl):
        if isDel(delk) and tbl.exists():
            tbl.drop()

    def tbl_create(tbl):
        if not tbl.exists():
            tbl.create()

    tbllist = [
        ('delcheck_items', check_items),
    ]
    '''
    テーブルの作成と、削除で依存関係のため順序が逆なので、
    createとdeleteで、順序を逆順にする。
    '''
    for (k, tbl) in tbllist:
        tbl_delete(k, tbl)
    tbllist.reverse()
    for (k, tbl) in tbllist:
        tbl_create(tbl)
示例#14
0
    def GET(self):
        params = web.input()
        ErrorCode = 2
        ErrorMessage = "initialized"
        DownloadURL = ""
        qvod_url = ""
        hash_code = ""
        if params.has_key("qvod_url"):
            qvod_url = params["qvod_url"]
            hash_code = qvod_url.split('|')[1]
        if params.has_key("hash_code"):
            hash_code = params["hash_code"]
        if len(qvod_url) == 0 or len(hash_code) == 0:
            ErrorCode = 100
            ErrorMesage = "input error"

        res = None
        try:
            conn = db_conn()
            sql = "select status,download_url from qvod_tasks where hash_code = '%s'" % hash_code
            print sql
            res = conn.get(sql)
            conn.close()
        except Exception, err:
            ErrorCode = -1
            ErrorMessage = "server error"
            web.debug("error: %s", str(traceback.format_exc()))
示例#15
0
    def find_firmware_folder(self, current_version, mac_address):
        v = re.search("(\d+)\.(\d+)", current_version)
        current_major = int(v.group(1))
        current_minor = int(v.group(2))

        device_specific_subfolder = None

        # If there is a dedicated folder for this device, search there; if not, use the default firmware_images_folder
        subdirs = get_immediate_subdirectories(firmware_images_folder)

        for subdir in subdirs:
            print(subdir)
            # Folders will have a name matching the pattern SOME_READABLE_PREFIX + underscore + MAC_ADDRESS
            if re.match(".*_" + mac_address.upper(), subdir):
                if device_specific_subfolder is not None:
                    web.debug(
                        "Error: found multiple folders for mac address " +
                        mac_address)
                    return None
                device_specific_subfolder = subdir

        if device_specific_subfolder is None:
            folder = firmware_images_folder
        else:
            folder = os.path.join(firmware_images_folder,
                                  device_specific_subfolder)

        print("Using firmware folder " + folder)

        if not os.path.isdir(folder):
            print("Error>>> " + folder + " is not a folder!")
            return

        return get_path_of_latest_firmware(folder, current_major,
                                           current_minor)
示例#16
0
def addNewUser():
    # Add the user to the user database
    dbPath = "/srv/www/trackr.scottjackson.org/db/users.db"
    if DEBUG:
        dbPath = "/Users/scottjacksonx/Documents/dev/git/trackr/db/users.db"

    userID = 0
    conn = sqlite3.connect(dbPath)
    c = conn.cursor()
    c.execute("select MAX(id) from users")
    for row in c:
        userID = int(row[0])
        userID += 1
        web.debug("userID = " + str(userID))
        thirtyOneDays = 2678400
        web.setcookie("userid", userID, thirtyOneDays)
    c.execute("insert into users values(?)", (userID, ))
    conn.commit()
    c.close()

    # Add a new table in the likes database for the user's likes
    dbPath = "/srv/www/trackr.scottjackson.org/db/likes.db"
    if DEBUG:
        dbPath = "/Users/scottjacksonx/Documents/dev/git/trackr/db/likes.db"
    conn = sqlite3.connect(dbPath)
    c = conn.cursor()
    values = (userID, )
    c.execute("create table ? (id INTEGER PRIMARY KEY)", values)
    conn.commit()
    c.close()
示例#17
0
    def POST(self, name):
        x = web.input(rate={})
        if x.rate == {}:
            return render.wrong('You did not choose a rate.')
        print x.rate
        num = int(x.rate)
        db = SQL.SQLtools()
        rate = float(db.lookup(table='videos', which='rate', A='key', name=name)[0][0])
        count = int(db.lookup(table='videos', which='count', A='key', name=name)[0][0])
        print 'count is %s' % count
        web.debug(count)
        web.debug(rate)
        print 'rate is %s' % type(rate)

        if count == 0:
            count += 1
            db.update('videos', 'rate', value=num, where='key', name=name)
            db.update('videos', 'count', value=count, where='key', name=name)
            print '222'
        else:
            rate = (rate * count + num) / (count + 1)
            count += 1
            db.update('videos', 'rate', value=rate, where='key', name=name)
            db.update('videos', 'count', value=count, where='key', name=name)
            print '111'
        return web.redirect('/')
示例#18
0
def obtenerNEs(lista):

    listaGeneral = []

    for (tweet, listaPalabras, clasificacion, diferenciaProbabilidad) in lista:
        # Condicionamos para que solo evalue los positivos
        print clasificacion
        if clasificacion == 'positive':
            sentences = nltk.tokenize.sent_tokenize(tweet)
            # Hacemos split en lugar de tokenize, para poder extrar las menciones a usuario.
            # El word_tokenize, separa el @ entonces no podemos filtrar
            nuevaSentences = []
            for s in sentences:
                subLista = quitarExcedenteSimple(s.split())
                nuevaSentences.append(' '.join(subLista))

            tokens = [nltk.tokenize.word_tokenize(s) for s in nuevaSentences]

            pos_tagged_tokens = [nltk.pos_tag(t) for t in tokens]
            ne_chunks = nltk.batch_ne_chunk(pos_tagged_tokens, binary=True)

            listaNEs = []
            for subArbol in ne_chunks:
                traverse(subArbol, listaNEs, False)

            if listaNEs:
                listaGeneral.append((tweet, listaPalabras, listaNEs))

    web.debug('Tweets con NEs:' + str(len(listaGeneral)))
    return listaGeneral
示例#19
0
def get_posts(limit=4):
    post_data = mget(
        key='_'.join([str(limit), 'posts']),
        namespace='posts'
    )
    if post_data is not None:
        return post_data
    else:
        query = Episode.all()
        query.order('-number')
        results = query.fetch(limit)
        post_data = [{
            'key': str(r.key()),
            'title': r.title,
            'number': r.number,
            'href': r.href,
            'thumb': r.thumb,
            'writeup': r.writeup,
        } for r in results]
        web.debug(post_data)
        if not madd(
            key='_'.join([str(limit), 'posts']),
            value=post_data,
            namespace="posts"
        ):
            logging.error('Memcache add failed!')
        return post_data
示例#20
0
 def POST(self):
     global oss, MAX_UPLOAD_SIZE
     print web.ctx.env.get('CONTENT_TYPE')
     if web.ctx.env.get('CONTENT_LENGTH') > MAX_UPLOAD_SIZE :
         return {"errno": 102,
                 "errmsg": "File size cannot more than 15M." }
     x = web.input(myfile={})
     if not x.has_key('myfile') or x['myfile'] == '':
         return {"errno": 100,
                 "errmsg": "Invalid upload !"}
     try:
         web.debug(x['myfile'].filename) # This is the filename
         content = x['myfile'].value
         dc = bencode.bdecode(content)
         binfo = bencode.bencode(dc['info'])
         infohash = sha1(binfo).hexdigest()
         sio = StringIO.StringIO()
         gz = gzip.GzipFile(fileobj=sio, mode="wb")
         gz.write(content)
         gz.close()
         gzcontent = sio.getvalue()
         if oss:
             res = oss.put_object_from_string(bucket = "test2312", 
                     object = "%s.torrent" % infohash.upper(),
                     input_content = gzcontent,
                     headers = {"Content-Encoding": "gzip"})
         return {"gzcontent" : res.status,
                 "infohash": infohash}
     except:
         return {"errno": 101,
                 "errmsg": "Unknow error, sorry :("}
示例#21
0
def addNewUser():
	# Add the user to the user database
	dbPath = "/srv/www/trackr.scottjackson.org/db/users.db"
	if DEBUG:
		dbPath = "/Users/scottjacksonx/Documents/dev/git/trackr/db/users.db"
	
	userID = 0
	conn = sqlite3.connect(dbPath)
	c = conn.cursor()
	c.execute("select MAX(id) from users")
	for row in c:
		userID = int(row[0])
		userID += 1
		web.debug("userID = " + str(userID))
		thirtyOneDays = 2678400
		web.setcookie("userid", userID, thirtyOneDays)
	c.execute("insert into users values(?)", (userID,))
	conn.commit()
	c.close()
	
	# Add a new table in the likes database for the user's likes
	dbPath = "/srv/www/trackr.scottjackson.org/db/likes.db"
	if DEBUG:
		dbPath = "/Users/scottjacksonx/Documents/dev/git/trackr/db/likes.db"
	conn = sqlite3.connect(dbPath)
	c = conn.cursor()
	values = (userID,)
	c.execute("create table ? (id INTEGER PRIMARY KEY)", values)
	conn.commit()
	c.close()
示例#22
0
 def GET(self):
     info = web.input()
     keys = list(info.keys())
     if 'scale' not in keys:
         scale = 'notSpecified'
     else:
         scale = info['scale']
     if 'imgWidth' not in keys or 'imgHeight' not in keys:
         width, height = 0, 0
     else:
         width, height = info['imgWidth'], info['imgHeight']
     folder = os.path.join(ar.DATA_DIR, 'img')
     img = info['image']
     if scale == '':
         scale = 'notSpecified'
     if width == '' or height == '':
         width, height = 0, 0
     if scale == 'notSpecified' and width == 0:
         raise internalerror()
     web.header('Content-type', 'image/%s' % img[img.rfind('.') + 1:])
     thumbFile = ar.oneThumb(img, folder, width, height, scale)
     web.debug(thumbFile)
     try:
         f = open(thumbFile, 'rb')
         while True:
             c = f.read(BUF_SIZE)
             if c:
                 yield c
             else:
                 break
     except Exception, e:
         web.debug(e)
         yield 'Error'
示例#23
0
def load_config(filename=None):
    """Load configuration from file and merge with defaults.
    
       The 'filename' of the configuration file.
    """
    # load config file
    if filename and filename.startswith('~'):
        filename = os.path.expanduser(filename)
    if not filename or not os.path.exists(filename):
        filename = os.path.expanduser(default_config_filename)
        if not os.path.exists(filename):
            return
    
    if config.debug:
        web.debug("Loading configuration from: " + filename)
    
    # skips if the file is empty
    contents = file(filename).read()
    if len(contents):
        input = json.load(file(filename))
    else:
        return

    # merge config
    for topic in input:
        if topic not in config:
            continue
        if not isinstance(input[topic], dict):
            config[topic] = input[topic]
            continue
        for key in input[topic]:
            config[topic][key] = input[topic][key]
示例#24
0
    def filterPruned(self, properties, key):
        """Returns data w/all keys removed but id and given properties

Works on filtered results

"""
        # Get all properties
        props = []
        for item in self.get("response"):
            for i in item[key]:
                for prop in i["props"].keys():
                    if prop not in props:
                        props.append(prop)

        # Keep props we want to keep
        # Start with props that are never removed
        # Add props passed in
        keeps = self.getDefaultFilterProps()
        for prop in properties:
            if prop not in keeps:
                keeps.append(prop)

        # Remove props we want to keep from list
        for keep in keeps:
            try:
                props.remove(keep)
            except ValueError, e:
                web.debug("QueryResult.filterPruned: %s: %r" % (keep, e))
示例#25
0
def doGet(pathInfo, opts):
    """Does HTTP GET"""

    web.debug("doGet")

    # Quick /entity/search for property:value
    # Looks up entity and returns
    if pathInfo == "/get":
        httpConfig = httpconfig.HttpConfig(web.ctx.env["DOCUMENT_ROOT"])
        host = httpConfig.config["serverhost"]
        port = httpConfig.config["serverport"]
        prop = "urn:lri:property_type:id"
        val = opts["id"]
        url = 'http://%s:%s/entity/search?q={"%s":"%s"}&opts={}' % (host, port, prop, val)
        web.debug("doGet: url = " + url)
        r = requests.get(url)

        text = None
        try:
            text = r.content
        except AttributeError, e:
            print ("doGet: No content")

            try:
                text = r.text
            except AttributeError, e:
                print ("doGet: No text")
	def POST(self):
		registroForm = FormularioRegistro()
		if not registroForm.validates():
			return makos.mako_template(varDep = "",titulo = self.paginaActual, formRegistro = registroForm )
		else:
			datos = web.input()
			conn = MongoClient('mongodb://localhost:27017')
			db = conn.app.usuarios
			aux = web.input()

			db_usuarios = {
				"nombre": aux.Nombre,
				"apellidos": aux.Apellidos,
				"email": aux.Email,
				"visa": aux.Visa,
				"dia": aux.Dia,
				"mes": aux.Mes,
				"ano": aux.Ano,
				"direccion": aux.Direccion,
				"contrasena": aux.Contrasena,
				"contrasena2": aux.Contrasena2,
				"pago": aux.Pago,
			}

			db.insert(db_usuarios)

			#Cerramos la conexión
			conn.close()
			datos = leerDatosBD()
			registroForm = insertarDatosForm(datos)
			web.debug(datos)
			contenido = imprimirDatosBD()
			return makos.mako_template(varDep = "", titulo = self.paginaActual, formRegistro = registroForm ,mensaje = "Registro exitoso", content = contenido)
示例#27
0
    def GET(self, status):
        web.debug("Handling update request")
        web.debug(status)
        current_version = web.ctx.env.get('HTTP_X_ESP8266_VERSION')
        mac = web.ctx.env.get('HTTP_X_ESP8266_STA_MAC')
        web.debug("Mac %s" % mac)
        # Other available headers
        # 'HTTP_CONNECTION': 'close',
        # 'HTTP_HOST': 'www.sensorbot.org:8989',
        # 'HTTP_USER_AGENT': 'ESP8266-http-Update',
        # 'HTTP_X_ESP8266_AP_MAC': '2E:3A:E8:08:2C:38',
        # 'HTTP_X_ESP8266_CHIP_SIZE': '4194304',
        # 'HTTP_X_ESP8266_FREE_SPACE': '2818048',
        # 'HTTP_X_ESP8266_MODE': 'sketch',
        # 'HTTP_X_ESP8266_SDK_VERSION': '2.2.1(cfd48f3)',
        # 'HTTP_X_ESP8266_SKETCH_MD5': '3f74331d79d8124c238361dcebbf3dc4',
        # 'HTTP_X_ESP8266_SKETCH_SIZE': '324512',
        # 'HTTP_X_ESP8266_STA_MAC': '2C:3A:E8:08:2C:38',
        # 'HTTP_X_ESP8266_VERSION': '0.120',

        # Use passed url params to display a debugging payload -- all will be read as strings; specify defaults in web.input() call to avoid exceptions for missing values
        # params = web.input(mqtt_status='Not specified')
        # mqtt_status = params.mqtt_status
        # web.debug("MQTT status:", mqtt_status)

        newest_firmware = self.find_firmware_folder(current_version, mac)

        if newest_firmware:
            web.debug("Upgrading birdhouse to " + newest_firmware)
            return get_firmware(newest_firmware)
        else:
            web.debug("Birdhouse already at most recent version (" +
                      current_version + ")")

        raise web.NotModified()
示例#28
0
 def loggit(self, message):
     """
 To suppress logging for this module, comment out the web.debug and put in a
 pass statement
 """
     if self.verbose:
         web.debug("%s.%s" % (self.module, message))
示例#29
0
def simple_compare(answer, response, vars=[]):
    """ Performs a simple symbolic comparison between two expressions.
        This method will perform a very simple comparision between two
        algebraic expressions. No expansion or factorization is performed
        hence expressions like "(x+1)^2" and "(1+x)^2" will evaluate as
        the same but expressions like "(x+1)^2" and "x^2+2*x+1" will not.
        @type answer: string
        @param answer: the first expression to compare
        @type response: string
        @param response: the second expression to compare
        @type vars: array
        @param vars: an array of variable names used in the expressions
        @rtype: bool
        @return: true if the expressions are equal, false otherwise
    """
    web.debug("Simple compare of '%s' to '%s' with variables %s" %
              (answer, response, vars))
    sage.misc.preparser.implicit_multiplication(10)  # Configure Sage

    variables, placeholders = prep_variables(vars)
    answer = prep_expression(answer, variables, placeholders)
    response = prep_expression(response, variables, placeholders)

    f = answer - response
    # Simply check to see if the representation of the expression is
    # a string containing the single character '0'.
    result = {
        'answer': str(answer),
        'response': str(response),
        'result': (f.__repr__() == '0')
    }
    web.debug(str(result))
    return result
示例#30
0
	def POST(self):
		data = web.input(file="{}")
		web.debug(data['file'])
		f = open("test.jpg", "wb")
		f.write(data['file'])
		f.close()
		pass
示例#31
0
文件: redirect.py 项目: swinsey/Morph
 def POST(self):
     data = web.data()
     (_, tmp_key) = data.split('=')
     web.debug(tmp_key)
     key = ""
     for s in tmp_key:
         if s.isdigit() or s.isalpha():
             key += s
     if len(key) == 0:
         render = web.template.render(tmpt_path, base='layout')
         return render.view_video("")
     else:
         res = gen_formats(key)
         if len(res) == 0:
             ret = '<h2>Warning</h2>' + '<pre><code>'
             ret += "No available video" + '<br>'
             ret += '</code></pre>'
             render = web.template.render(tmpt_path, base='layout')
             return render.view_video(ret)
         else:
             ret = '<h2>Enjoy it!</h2> <br><br>'
             for r in res:
                 tmp = r.split('_')
                 tmp = tmp[len(tmp) - 1].replace('.mp4', '')
                 w, h = tmp.split('x')
                 ret += "<video width=\"" + w + "\" height=\"" + h + "\" controls>"
                 ret += "<source src=\"" + r + "\" type=\"video/mp4\">"
                 ret += "</video>"
                 ret += "<br><br><br>"
             render = web.template.render(tmpt_path, base='layout')
             return render.view_video(ret)
示例#32
0
    def POST(self):
        x = web.input(myfile={})
        web.debug(x['myfile'].filename)
        #web.debug(x['myfile'].value)
        web.debug(x['myfile'].file.read())

        raise web.seeother('/upload')
示例#33
0
文件: webctx.py 项目: wunderlins/ha
    def GET(self):

        conn, cursor = oraconn()

        today = datetime.datetime.now()  # + datetime.timedelta(days=1)

        sql = (
            """SELECT o.ID, o.STMNAME, o.STMVORNAME, substr(o.OPTEXT, 0, 50)
		FROM DATO_OP o
		WHERE o.OPDATUM = '"""
            + str(today.strftime("%Y%m%d"))
            + """'
			AND o.TSCANCEL IS NULL AND (o.DEL IS NULL OR o.DEL = 'N')
		ORDER BY o.STMNAME, o.STMVORNAME"""
        )

        # web.debug(sql)
        # web.debug(conn)
        # web.debug(cursor)

        res = []

        try:
            cursor.execute(sql)
        except Exception, e:
            web.debug(e)
            return "database error"
示例#34
0
    def POST(self):
        a = web.input(file1={})

        web.debug(a.file1.filename)  # 这里是文件名
        web.debug(a.file1.value)  # 这里是文件内容

        return "upload success"
示例#35
0
def load_config(filename=None):
    """Load configuration from file and merge with defaults.
    
       The 'filename' of the configuration file.
    """
    # load config file
    if filename and filename.startswith('~'):
        filename = os.path.expanduser(filename)
    if not filename or not os.path.exists(filename):
        filename = os.path.expanduser(default_config_filename)
        if not os.path.exists(filename):
            return

    if config.debug:
        web.debug("Loading configuration from: " + filename)

    # skips if the file is empty
    contents = file(filename).read()
    if len(contents):
        input = json.load(file(filename))
    else:
        return

    # merge config
    for topic in input:
        if topic not in config:
            continue
        if not isinstance(input[topic], dict):
            config[topic] = input[topic]
            continue
        for key in input[topic]:
            config[topic][key] = input[topic][key]
示例#36
0
 def GET(self):
     q = web.input()
     t = template.env.get_template('search.html')
     f = search_form()
     try:
         if q.query:
             results = []
             user_list = []
             query = q.query.split(' ')
             for i in User.all():
                 x = util.strip_private_data(i)
                 if x is not None:
                     user_list.append(x)
             for p in user_list:
                 for i in query:
                     if i in dict(p).values():
                         results.append(p)
             return t.render(util.data(
                 title='Find who you\'re looking for!',
                 form=f,
                 results=results if results else None,
             ))
         else:
             web.debug('q.query doesn\'t exist and it didn\'t thow an exception!')
             raise Warning('Odd, huh?')
     except:
         return t.render(util.data(
             title='Find who you\'re looking for!',
             form=f,
         ))
def simple_compare(answer, response, vars=[]):
    """ Performs a simple symbolic comparison between two expressions.
        This method will perform a very simple comparision between two
        algebraic expressions. No expansion or factorization is performed
        hence expressions like "(x+1)^2" and "(1+x)^2" will evaluate as
        the same but expressions like "(x+1)^2" and "x^2+2*x+1" will not.
        @type answer: string
        @param answer: the first expression to compare
        @type response: string
        @param response: the second expression to compare
        @type vars: array
        @param vars: an array of variable names used in the expressions
        @rtype: bool
        @return: true if the expressions are equal, false otherwise
    """
    web.debug("Simple compare of '%s' to '%s' with variables %s" %
             (answer, response, vars))
    sage.misc.preparser.implicit_multiplication(10)  # Configure Sage

    variables, placeholders = prep_variables(vars)
    answer = prep_expression(answer, variables, placeholders)
    response = prep_expression(response, variables, placeholders)

    f = answer-response
    # Simply check to see if the representation of the expression is
    # a string containing the single character '0'.
    result = {
        'answer': str(answer),
        'response': str(response),
        'result': (f.__repr__() == '0')
    }
    web.debug(str(result))
    return result
示例#38
0
 def wrapper(*args):
     request_init()
     try:
         try:
             try:
                 result = original_method(*args)
                 if hasattr(result, 'next'):
                     # force any transaction deferred in iterator
                     for res in result:
                         yield res
                 else:
                     yield result
             except psycopg2.ProgrammingError, e:
                 if e.pgcode == '42501':
                     # insufficient_privilege ... HACK: add " and is" to combine into Forbidden() template
                     raise rest.Forbidden(e.pgerror.decode('utf8').replace('ERROR:  ','').replace('\n','') + ' and is')
                 elif e.pgcode == '42601':
                     # SQL syntax error means we have buggy code!
                     web.debug(e.pgcode, e.pgerror)
                     raise rest.RuntimeError('Query generation error, contact ERMrest administrator')
                 else:
                     # re-raise and let outer handlers below do something more generic
                     raise
         except (rest.WebException, web.HTTPError), e:
             # exceptions signal normal REST response scenarios
             raise e
         except (ConflictModel, ConflictData), e:
             raise rest.Conflict(e.message)
 def getNextCommand(self):
   web.debug("current floor %d" % self._currentFloor)
   web.debug("stops up:" + " - ".join(str(s) for s in self._stopsUp))
   web.debug("stops down:" + " - ".join(str(s) for s in self._stopsDown))
   web.debug("stops:" + " - ".join(str(s) for s in self._stopsDown))
   #if the current floor is in the stops no matter the firection
   if self._currentFloor in self._stops:
     self._openDoors()
   #checking the stops when going up
   elif self._currentDirection == ElevatorEngine.DIRECTION_UP and self._currentFloor in self._stopsUp:
     self._openDoors()
   #checking the stops when going down
   elif self._currentDirection == ElevatorEngine.DIRECTION_DOWN and self._currentFloor in self._stopsDown:
     self._openDoors()
   #checking in the current direction (to avoid going up/down everytime)
   elif self._numberOfStopsInDirection(self._currentDirection) != 0:
     self._goToCurrentDirection()
   #checking the other direction
   elif self._numberOfStopsInDirection(self._reverseCurrentDirection()) != 0:
     self._goToCurrentReverseDirection()
     
   ##Doing the action
   if self._actions.empty():
     action = ElevatorEngine.ACTION_NOTHING
   else:
     action = self._actions.get()
   web.debug("action: %s" % (action))
   return action
示例#40
0
 def varify_params(self, requestId, begin_ts, end_ts, media_type, channel_uuid):
     if begin_ts >= end_ts:
         err_info = {"requestId":requestId, "error": {"code": 400, "message": "begin_ts is larger or equal to end_ts"}}
         web.debug("error: %s"% str(err_info))
         err_info = simplejson.dumps(err_info)
         raise web.webapi._status_code("400 Bad Request", web.webapi.BadRequest, "begin_ts is larger or equal to end_ts"), err_info
     
     ltime = int(time.time())
     if begin_ts < ltime - self.max_reservetime * 3600:
         err_info = {"requestId":requestId, "error": {"code": 400, "message": "begin_ts is not in reserved time"}}
         web.debug("error: %s"% str(err_info))
         err_info = simplejson.dumps(err_info)
         raise web.webapi._status_code("400 Bad Request", web.webapi.BadRequest, "begin_ts is not in reserved time"), err_info
     
     if media_type.lower() not in ('video', 'screenshot'):
     
         err_info = {"requestId":requestId, "error": {"code": 400, "message": "type is error"}}
         web.debug("error: %s"% str(err_info))
         err_info = simplejson.dumps(err_info)
         raise web.webapi._status_code("400 Bad Request", web.webapi.BadRequest, "type is error"), err_info
     
     if channel_uuid is None:
         web.debug(" channel uuid is null")
         err_info = {"requestId":requestId, "error": {"code": 400, "message": "the channel uuid is not error"}}
         web.debug("error: %s"% str(err_info))
         err_info = simplejson.dumps(err_info)
         raise web.webapi._status_code("400 Bad Request", web.webapi.BadRequest, "the channel uuid is not using"), err_info
示例#41
0
 def POST(self, cmd):
     if cmd == 'total':
         pts = MongoUtil.fetchPage('columbia',{}, 0, 1)
         return pts.count()
     if cmd == 'upload':
         params = web.data();
         #passTime = params.passTime
         #ua = params.ua
         jsonData = simplejson.loads(params)
         web.debug("passTime:%r", jsonData)
         ctime = jsonData.get('time')
         MongoUtil.save('columbia', jsonData)
         if ctime:
             histGram = MongoUtil.fetch('histgram', {})
             if not histGram:
                 histGram = {}
             
             val = histGram.get(ctime)
             if val:
                 ++val
                 histGram[ctime] = val
             else:
                 histGram[ctime] = 1
             MongoUtil.update('histgram', histGram)
             total = 1
             beating = 1
             for tm in histGram:
                 if tm > ctime:
                     total += histGram.get(tm)
                     beating += histGram.get(tm)
                 else:
                     total  += histGram.get(tm)
             
             return 100 * beating/total
示例#42
0
 def POST(self):
     """Called when the user uploads a file using POST"""
     from PIL import Image
     # get the data from the form
     x = web.input(myfile=web.Storage(file=''))
     # check the input file to make sure it's legal
     if 'myfile' not in x or not x.myfile.file: raise web.badrequest()
     # create the filename (and containing dir) based on the current time
     fname = os.path.join(IMAGEDIR, '%d.jpg' % (time.time() * 1000))
     try:
         os.makedirs(os.path.dirname(fname))
     except OSError:
         pass
     # save the image
     fout = open(fname, 'w')
     fout.write(x.myfile.file.read())
     fout.close()
     # remove the image from the uploaded params
     del x['myfile']
     try:
         # if it's a valid image, process it
         im = Image.open(fname)
         web.debug(
             'Saved valid image to %s, about to call process() on it' %
             (fname))
         results = process(im, fname, dict(x))
         return results
     except IOError:
         # if not, delete the image and return bad request
         try:
             os.remove(fname)
         except IOError:
             pass
         raise web.badrequest()
示例#43
0
    def GET(self):
        if not logged():
            return json.dumps({"status": 403})

        data = web.input()
        web.debug(data)
        tag_vars = {"code": data.code}
        tid = db.select("live_tag", vars=tag_vars, where="code=$code")[0].id
        ch_vars = {"tagid": tid}
        ch_results = db.select(
            "live_channel", vars=ch_vars, where="tagid=$tagid")
        ch_list = []
        for ch in ch_results:
            channel = {}
            channel["chid"] = ch.id
            channel["name"] = ch.name
            channel["state"] = ch.state
            channel["types"] = data.code
            src_vars = {"chid": ch.id}
            src_results = db.select(
                "live_source", vars=src_vars, where="chid=$chid")
            channel["list"] = []
            for s in src_results:
                src = {}
                src["srcid"] = s.id
                src["source"] = s.source
                src["playUrl"] = s.url
                src["state"] = s.state
                channel["list"].append(src)

            ch_list.append(channel)

        resp_data = {"status": 200, "liveData": ch_list}
        return json.dumps(resp_data)
示例#44
0
    def POST(self, name):
        x = web.input(rate={})
        if x.rate == {}:
            return render.wrong('You did not choose a rate.')
        print x.rate
        num = int(x.rate)
        db = SQL.SQLtools()
        rate = float(
            db.lookup(table='videos', which='rate', A='key', name=name)[0][0])
        count = int(
            db.lookup(table='videos', which='count', A='key', name=name)[0][0])
        print 'count is %s' % count
        web.debug(count)
        web.debug(rate)
        print 'rate is %s' % type(rate)

        if count == 0:
            count += 1
            db.update('videos', 'rate', value=num, where='key', name=name)
            db.update('videos', 'count', value=count, where='key', name=name)
            print '222'
        else:
            rate = (rate * count + num) / (count + 1)
            count += 1
            db.update('videos', 'rate', value=rate, where='key', name=name)
            db.update('videos', 'count', value=count, where='key', name=name)
            print '111'
        return web.redirect('/')
示例#45
0
文件: redirect.py 项目: cap-ntu/Morph
 def POST(self):
     data = web.data()
     (_, tmp_key) = data.split('=')
     web.debug(tmp_key)
     key = ""
     for s in tmp_key:
         if s.isdigit() or s.isalpha():
             key += s 
     if len(key) == 0:
         render = web.template.render(tmpt_path, base='layout')
         return render.view_video("")
     else: 
         res = gen_formats(key)
         if len(res) == 0:
             ret = '<h2>Warning</h2>' + '<pre><code>'
             ret += "No available video" + '<br>'
             ret += '</code></pre>' 
             render = web.template.render(tmpt_path, base='layout')
             return render.view_video(ret)
         else:
             ret = '<h2>Enjoy it!</h2> <br><br>'
             for r in res:
                 tmp  = r.split('_')
                 tmp  = tmp[len(tmp)-1].replace('.mp4', '')
                 w, h = tmp.split('x')
                 ret  += "<video width=\"" + w + "\" height=\"" + h + "\" controls>"
                 ret  += "<source src=\""  + r + "\" type=\"video/mp4\">"
                 ret  += "</video>"
                 ret  += "<br><br><br>"
             render = web.template.render(tmpt_path, base='layout')
             return render.view_video(ret)
示例#46
0
文件: webctx.py 项目: wunderlins/ha
    def POST(self):
        raw_data = web.data()
        conn, cursor = oraconn()

        web.header("Content-Type", "application/json")

        try:
            data = json.loads(raw_data)
        except:
            return '{"success": false, "message": "Failed to decode json string"}'

        try:
            data["ma"]["datum"] = datetime.datetime.strptime(data["ma"]["datum"], "%d.%m.%Y")
        except:
            return "Failed to parse input date"

            # web.debug(data["ma"])

            # update metadata

        sql = "SELECT DATUM FROM DATO_HOLDINGAREA_STAFF WHERE DATUM = TO_DATE('%s', 'YYYYMMDD')" % data["ma"][
            "datum"
        ].strftime("%Y%m%d")
        web.debug(sql)
        try:
            cursor.execute(sql)
        except Exception, e:
            # web.debug(e)
            return '{"success": false, "message": "Failed to query metadata in database"}'
示例#47
0
def getTrendingTopics( placeId=1 ):
	"""
	Request a list of top Twitter trends worldwide
	"""
	returnValue = []
	requestUrl = 'https://api.twitter.com/1.1/trends/place.json'

	#Authorize app
	accessToken = authorize()

	if accessToken is not None:

		# set header with access token
		headers = {
		'Authorization' : 'Bearer '+ accessToken 
		}
		# fill in required location field to fetch worldwide trending topics
		params = { 'id': placeId }
		try:
			# make request, and populate list to be returned with name and urls
			response = requests.get( requestUrl, params=params, headers=headers )
			responseJson = response.json()
			if 'trends' in responseJson[ 0 ]:
				for trend in responseJson[ 0 ][ 'trends' ]:
					returnValue.append( { 'name': trend[ 'name' ], 'url': trend[ 'url' ] } )
			return returnValue
		except HTTPError as e:
			web.debug( e )
	else:
		web.debug( "Failed to get Twitter values" )
		return "Error while fetching topics"
	def typeFilter(self, path): 
		"""
		Pass in the pdfpath here, returns the uploaded file's MIME type
		"""	
		fileTypeString = magic.from_file(path, mime=True) # Stores the MIME string that describes the file type
		web.debug(fileTypeString)
		return fileTypeString
示例#49
0
    def POST(self):
        x = web.input(myfile={})
        print(type(x))
        print(type(x['myfile']))
        web.debug(x['myfile'].filename)  # This is the filename
        #web.debug(x['myfile'].value) # This is the file contents
        #web.debug(x['myfile'].file.read()) # Or use a file(-like) object
        w = open("static/images/resources/tmp.png", 'wb')
        w.write(x['myfile'].file.read())
        w.close()

        #"""
        total, blanks, pozitives, percent = analyse_by_name(
            "static/images/resources/tmp.png",
            "static/images/resources/tmp_rez.png", "the_one")

        #"""

        #total, blanks, pozitives, percent = 1,2,3,4

        w = open("templates/images/resources/tmp_rez.png", 'rb')
        w.close()

        print(
            render.result(total, blanks, pozitives, percent,
                          "images/resources/tmp_rez.png"))

        return render.result(total, blanks, pozitives, percent,
                             "images/resources/tmp_rez.png")
示例#50
0
def handle_user(user_email, password, function_type):
	try:
		check_username = globs.db.query("SELECT * FROM users WHERE email=$id", vars={'id':user_email})
		print "CHECK USERNAME!!!!!!!!!!!!"
		print check_username
		if (function_type == "register"):
			if not list(check_username):
				pass_hashobj = globs.PasswordHash(password)
				email_hashobj = globs.PasswordHash(user_email)
				user_ident = globs.db.query ("SELECT MAX(user_id) as highestId from users")[0]

				if (user_ident.highestId == None):
					userID = 0
				else:
					userID = user_ident.highestId + 1

				sequence_id = globs.db.insert('users',  user_id = userID, email = user_email, active = 0, password_hash = pass_hashobj.hashedpw, password_salt = pass_hashobj.salt, create_date = web.SQLLiteral("NOW()"), email_hash = email_hashobj.hashedpw, email_salt = email_hashobj.salt)
			else:
				print "I occur when the login username is already taken"
				return False
		elif (function_type == "login"):
			results = check_username[0]
			verified = globs.verify_user_hash(password, results)
			return verified

			
			
		else:
			print "I shouldn't occur"
			return False
	except IndexError:
		web.debug("AN SQL EXCEPTION HAS OCCURED")
		return False		
示例#51
0
 def GET(self):
     info = web.input()
     keys = list(info.keys())
     if 'scale' not in keys:
         scale = 'notSpecified'
     else:
         scale = info['scale']
     if 'imgWidth' not in keys or 'imgHeight' not in keys:
         width, height = 0, 0
     else:
         width, height = info['imgWidth'], info['imgHeight']
     folder = os.path.join(ar.DATA_DIR, 'img')
     img = info['image']
     if scale == '':
         scale = 'notSpecified'
     if width == '' or height == '':
         width, height = 0, 0
     if scale == 'notSpecified' and width ==0:
         raise internalerror()
     web.header('Content-type', 'image/%s'%img[img.rfind('.')+1:])
     thumbFile = ar.oneThumb(img, folder, width, height, scale)
     web.debug(thumbFile)
     try:
         f = open(thumbFile, 'rb')
         while True:
             c = f.read(BUF_SIZE)
             if c:
                 yield c
             else:
                 break
     except Exception, e:
         web.debug(e)
         yield 'Error'
示例#52
0
    def process(self):
        userSession = web.ctx.env.get('HTTP_X_CURRENT_PERSONID') 
        params = web.data()
        jsons = simplejson.loads(params if params else '{}')
        web.debug('Notify userSession: %s, %r' % (userSession, jsons))
        if not userSession:
                web.ctx.status = '406 Not login'
                return 'not userID'   
        remove = True
        startPage = 0
        pageSize = 30
        if 'keep' in jsons:
            remove = jsons['keep']
        
        if 'startPage' in jsons:
            startPage = jsons['startPage']
        
        if 'pageSize' in jsons:
            pageSize = jsons['pageSize']

        query = {'personID':userSession,}
        if remove:
            query = {'personID':userSession, 'remove':{'$ne':'1'}}
        
        notes = MongoUtil.fetchPage('notes',query,startPage,pageSize,[('createdTime', -1)])
        #web.debug('notes count:%i' % len(notes))
        res = []
        for note in notes:
           if maturedNote(note):
               if remove:
                   note['remove'] = '1'
                   MongoUtil.update('notes', note)
               res.append(cleanNote(note))
        web.debug('Total friend:'+ str(len(res)))
        return simplejson.dumps(res)        
示例#53
0
    def POST(self):
        data = web.input()
        web.debug(data)
        if not "new_model" in data:
            data.__setattr__("new_model", "off")

        ann = ANN(filename=web.ctx.globals.filename,
                  epochs=int(data.epoch),
                  learning=float(data.learning),
                  hidden=int(data.hidden),
                  decay_rate=float(data.decay_rate),
                  new_model=data.new_model,
                  activation=data.activation,
                  momentum=float(data.momentum))

        model = process_start(target=trainer, args=[ann])
        accuracy, train_error, test_error = ann.accuracy(model)
        image = process_start(target=graphpainter, args=[ann, model])
        response = json.dumps(
            {
                'Acc': accuracy,
                'TrainE': train_error,
                'TestE': test_error,
                'Process': model.process,
                "Figure": image
            },
            sort_keys=True,
            indent=2,
            separators=(',', ':'))
        return response
示例#54
0
文件: table.py 项目: ytfqj/ermrest
 def check_primary_keys(self, require):
     if not self.has_primary_key():
         if require:
             raise exception.rest.RuntimeError(
                 'Table %s lacks primary key. Contact ERMrest administrator.'
                 % self)
         else:
             web.debug('WARNING: Table %s lacks primary key.' % self)
示例#55
0
    def POST(self):
        form = web.input(action=None)

        web.debug(session.room.name)
        if session.room and session.room.name != "The End" and form.action:
            session.room = session.room.go(form.action)

        web.seeother("/game")
示例#56
0
 def __call__(self):
     engine = self.engine_factory()
     self.sessionmaker.configure(bind=engine)
     session = self.sessionmaker()
     web.debug(
         "[MODEL] Successfully instanciated DB session %s bound to %s" %
         (session, engine))
     return session
示例#57
0
 def memcache(self):
     servers = config.get("memcache_servers", None)
     if servers:
         return olmemcache.Client(servers)
     else:
         web.debug("Could not find memcache_servers in the configuration. Used dummy memcache.")
         import mockcache
         return mockcache.Client()
示例#58
0
 def POST(self):
     reqData = web.input()
     skey = reqData.searchKey
     vtype = reqData.videoType
     surl = 'http://api.tudou.com/v3/gw?method=item.search&appKey=myKey&format=json&kw=' + skey + '&pageNo=1&pageSize=20&channelId=' + vtype + '&inDays=7&media=v&sort=s'
     htmlContent = urllib2.urlopen(surl).read()
     web.debug(htmlContent)
     return htmlContent
示例#59
0
 def POST(self):
     postData = web.input(upfile={}, pictitle="")
     web.debug(postData)
     fileObj = postData.upfile
     picTitle = postData.pictitle
     fileName = fileObj.filename
     newFileName = str(uuid.uuid1()) + ".png"
     saveUploadFile(newFileName, fileObj.file.read())
     return "{'url':'" + ueconfig_url + '/' + newFileName + "','title':'" + picTitle + "','original':'" + fileName + "','state':'" + "SUCCESS" + "'}"
示例#60
0
def get_server_public_fqdn():
    try:
        reslvr = resolver.Resolver()
        ipaddr = reversename.from_address(get_server_external_ip())
        return str(reslvr.query(ipaddr, 'PTR')[0]).rstrip('.').lower()

    except Exception, e:
        web.debug('DEBUG: get_server_public_fqdn(): %s' % repr(e))
        return ipaddr