Esempio n. 1
0
def preinitialize():
    os.environ['BETTER_EXCEPTIONS'] = 'TRUE'
    better_exceptions.MAX_LENGTH = None
    # rich.traceback.install()

    util.numbers.preinitialize()
    api.connect()
    locale.setlocale(locale.LC_ALL, '')
    if not pathlib.posixpath.exists(constants.CACHE_DIR):
        os.mkdir(constants.CACHE_DIR)
Esempio n. 2
0
def connect(host):
    try:
        r = api.connect(host)
        return r
    except Exception as e:
        print("Connect error")
        exit()
Esempio n. 3
0
def show_image():
    # Connect to SQL Server
    cnx = None
    try:
        cnx = connect()
    except sql.Error as e:
        return json.dumps({
            'status': 'error',
            'status_extended': 'Couldnt connect to sql database'
        })

    cursor = cnx.cursor(dictionary=True)

    query = "SELECT * FROM images WHERE id = %s"

    try:
        cursor.execute(query, [request.args["id"]])
    except Exception as e:
        return json.dumps({
            "status": 'error',
            'status_extended': 'Failed to find image: ' + repr(e)
        })

    ret_val = cursor.fetchall()

    if cursor.rowcount != 1:
        abort(404)

    return Response(ret_val[0]["imageblob"], mimetype=ret_val[0]["mimetype"])
 def connect(self, address, port):
     if int(port) < 0 or int(port) > 65535:
         logging.info("Port number is invalid.")
         sys.exit(0)
     self.sock.settimeout(TIMEOUT_S)
     self.isConnected = api.connect(self.sock, self.server_address, self)
     if (self.isConnected):
         self.seq_nbr = 0
         self.ack_nbr = 0
         self.last_acked = 0
         logging.info('Client socket has connected to server with IP: '\
                       + str(self.server_address[0]) + ' port: ' + str(self.server_address[1]))
         logging.debug('Client Ack Nbr: ' + str(self.ack_nbr) + '; Client Seq Nbr: ' + str(self.seq_nbr))
     else:
         logging.info('Client did not successfully connect')
Esempio n. 5
0
def build_config(login, password):
    data = {}
    try:
        data = api.connect(login, password)
        tree = api.get_search_tree({
            'user_id': data["user_id"], 
            'session_id': data["session_id"], 
            'auth_token': data["auth_tokens"].pop(),
        })
        
        items = tree['items']
        root = [x for x in items if x['name']=='#all'][0]
        
        return build_tree(root, items, login, password)

    except Exception as ex:
        print(login + '-' + password + ' -> error:' + str(ex))
        return None
Esempio n. 6
0
def main(opts):
    config_mode = (opts.action in ACTIONS[:2]) and 'r' or 'w'
    config = conf.load_config(opts.config, config_mode)
    serviceURL = api.get_service_url(opts, config)
    username = conf.get_value(opts, config, 'username')
    password = conf.get_value(opts, config, 'password', secret=True)

    try:
        vim_client = api.connect(serviceURL, username, password)
   
        if opts.action == 'verify':
            verify.do_verify(config, opts, vim_client)
        elif opts.action == 'pillage':
            pillage.do_pillage(config, opts, vim_client)
        elif opts.action == 'repair':
            repair.do_repair(config, opts, vim_client)
        vim_client.Disconnect()
        rc = 0
    except SystemError, e:
        print(str(e.args))
        rc = 1
Esempio n. 7
0
def main():
    spotify = connect(username, scope, os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET"), redirect_uri)

    artist_name = input("What Artist do you want to search for? ")
    get_artist_top_songs(spotify, artist_name)
    print_curr_playing(spotify)
Esempio n. 8
0
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return "No file submitted."
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            return 'No selected file'
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            ext = filename.split(".")[len(filename.split(".")) - 1]
            saving_filename = x = ''.join(
                random.choice(string.ascii_uppercase + string.ascii_lowercase +
                              string.digits) for _ in range(16)) + "." + ext
            filepath = os.path.join(app.config['UPLOAD_FOLDER'],
                                    saving_filename)
            file.save(filepath)

            image = Image.open(filepath)
            for orientation in ExifTags.TAGS.keys():
                if ExifTags.TAGS[orientation] == 'Orientation':
                    break
            exif = dict(image.getexif().items())

            if orientation in exif:
                if exif[orientation] == 3:
                    image = image.rotate(180, expand=True)
                elif exif[orientation] == 6:
                    image = image.rotate(270, expand=True)
                elif exif[orientation] == 8:
                    image = image.rotate(90, expand=True)
                image.save(filepath)

            image.close()

            # Connect to SQL Server
            cnx = None
            try:
                cnx = connect()
            except sql.Error as e:
                return json.dumps({
                    'status':
                    'error',
                    'status_extended':
                    'Couldnt connect to sql database'
                })

            cursor = cnx.cursor()

            query = "INSERT INTO images (mimetype, imageblob) VALUES (%s, %s)"

            try:
                cursor.execute(
                    query, [file.mimetype,
                            convert_to_binary_data(filepath)])
                cnx.commit()
            except Exception as e:
                return json.dumps({
                    "status":
                    'error',
                    'status_extended':
                    'Failed to submit the insert query: ' + repr(e)
                })

            os.remove(
                os.path.join(app.config['UPLOAD_FOLDER'], saving_filename))

            query = (
                "INSERT INTO reports (lat,lng,text,imgid,score,userid,reporttype) "
                "VALUES (%s,%s,%s,%s,%s,%s,%s) ")

            # Do the query
            try:
                cursor.execute(query, [
                    request.form["lat"], request.form["lng"],
                    request.form["reportdescription"], cursor.lastrowid, 0, 1,
                    "fire"
                ])
                cnx.commit()
            except Exception as e:
                return json.dumps({
                    "status":
                    'error',
                    'status_extended':
                    'Failed to submit the insert query: ' + repr(e)
                })

            # Close connection
            cursor.close()
            cnx.close()
    return "Finished."
Esempio n. 9
0
 def connect(self, server='127.0.0.1', port=27017, name='easy_database'):
     api.connect(server, port, name)
     self.update_all()
     return True
Esempio n. 10
0
def main():
	config = conf.configure()
	
	#now configure our settings global
	set_setting('LOG_LOCATION',		config.log_location)
	set_setting('DEBUG', 			config.debug)
	set_setting('VERBOSE', 			config.verbose)

	#init logging
	logger.initLogger()

	set_setting('REGISTRATION_HOST', 	config.reg_host)
	set_setting('REGISTRATION_PORT', 	config.reg_port)
	set_setting('PORT', 			config.port)
	set_setting('IP', 			config.ip)
	set_setting('DB_TYPE', 			config.db_type)
	set_setting('REDIS_SOCKET', 		config.redis_sock)
	set_setting('REDIS_HOST', 		config.redis_host)
	set_setting('REDIS_PORT', 		config.redis_port)
	set_setting('MONGO_NAME',		config.mongo_name)
	set_setting('MONGO_HOST',		config.mongo_host)
	set_setting('MONGO_PORT',		config.mongo_port)
	set_setting('MONGO_READ',		config.mongo_read)
	set_setting('MYSQL_NAME',		config.mysql_name)
	set_setting('MYSQL_HOST',		config.mysql_host)
	set_setting('MYSQL_PORT',		config.mysql_port)
	set_setting('MYSQL_USER',		config.mysql_user)
	set_setting('MYSQL_PASSWORD',		config.mysql_password)
	set_setting('HTTP_SERVICE',		config.server)
	set_setting('ROOT_KEY',			config.root_key)

	logger.LOG.log('ReorJS service starting...')
	logger.LOG.log('Initializing API')
	logger.LOG.info('Starting with the following settings:')
	logger.LOG.info('LOG_LOCATION		=> %s' % settings.LOG_LOCATION)
	logger.LOG.info('DEBUG			=> %s' % settings.DEBUG)
	logger.LOG.info('VERBOSE			=> %s' % settings.VERBOSE)
	logger.LOG.info('REGISTRATION_HOST	=> %s' % settings.REGISTRATION_HOST)
	logger.LOG.info('REGISTRATION_PORT	=> %s' % settings.REGISTRATION_PORT)
	logger.LOG.info('PORT			=> %s' % settings.PORT)
	logger.LOG.info('IP			=> %s' % settings.IP)
	logger.LOG.info('DB_TYPE			=> %s' % settings.DB_TYPE)
	logger.LOG.info('REDIS_SOCKET		=> %s' % settings.REDIS_SOCKET)
	logger.LOG.info('REDIS_HOST		=> %s' % settings.REDIS_HOST)
	logger.LOG.info('REDIS_PORT		=> %s' % settings.REDIS_PORT)
	logger.LOG.info('MONGO_NAME		=> %s' % settings.MONGO_NAME)
	logger.LOG.info('MONGO_HOST		=> %s' % settings.MONGO_HOST)
	logger.LOG.info('MONGO_PORT		=> %s' % settings.MONGO_PORT)
	logger.LOG.info('MONGO_READ		=> %s' % settings.MONGO_READ)
	logger.LOG.info('MYSQL_NAME		=> %s' % settings.MYSQL_NAME)
	logger.LOG.info('MYSQL_HOST		=> %s' % settings.MYSQL_HOST)
	logger.LOG.info('MYSQL_PORT		=> %s' % settings.MYSQL_PORT)
	logger.LOG.info('MYSQL_USER		=> %s' % settings.MYSQL_USER)
	logger.LOG.info('MYSQL_PASSWORD		=> %s' % settings.MYSQL_PASSWORD)
	logger.LOG.info('HTTP_SERVICE		=> %s' % settings.HTTP_SERVICE)
	logger.LOG.info('ROOT_KEY		=> %s' % settings.ROOT_KEY)
	
	#we need to configure our API database from settings
	if api.connect():	
		#and then our stacker		
		logger.LOG.log('Initializing stacker')
		stack.initStacker()
		
		#next we need to create our query service
		logger.LOG.log('Initializing query service')
		service = query.QueryService()
		
		#and run it
		logger.LOG.log('Running service...')
		service.run()		
	else:
		logger.LOG.log("Error connecting to API database, please check configuration.")
Esempio n. 11
0
def connect(host):
    try:
        r = api.connect(host)
        return r
    except Exception as e:
        verdict(DOWN, "Connection error")
Esempio n. 12
0
def try_connect(login, password):
    try:
        data = api.connect(login, password)
        return 'user_id=' + data['user_id']
    except Exception as ex:
        return str(ex)