예제 #1
0
 def execute(self, message):
     api = Api()
     counter = 0
     for tweet in api.user_timeline(count=message.args[0]):
         tweet.destroy()
         counter = counter + 1
     return '%i tweets removed' % counter
예제 #2
0
    def __init__(self, api_key, api_secret, access_token):
        Api.__init__(self, api_key, api_secret)

        self.oauth_token = oauth.Token(
            access_token['oauth_token'], access_token['oauth_token_secret']
        )
        self.client = oauth.Client(self.consumer, self.oauth_token)
예제 #3
0
 def do_GET(self):
     try:
         
         if urlparse(self.path).query:
             params = parse_qs(urlparse(self.path).query)
             family = params.get("family")[0] if params.has_key("family") else ""
             section = params.get("section")[0] if params.has_key("section") else ""
             mtype = params.get("type")[0] if params.has_key("type") else ""
             noteid = params.get("id")[0] if params.has_key("id") else ""
             txt = params.get("search")[0] if params.has_key("search") else ""
             year = params.get("year")[0] if params.has_key("year") else ""
             month = params.get("month")[0] if params.has_key("month") else ""
             day = params.get("day")[0] if params.has_key("day") else ""
             detail = params.get("detail")[0] if params.has_key("detail") else ""
             richness = params.get("richness")[0] if params.has_key("richness") else ""
             thisapi = Api(family,section,mtype,txt,noteid,year,month,day,detail,richness)
             #Application/json
             self.send_response(200)
             self.send_header('Content-type', 'text/json')
             self.end_headers()
             self.wfile.write(thisapi.getResult())
         else:       
             thisapi = Api()
             self.send_response(200)
             self.send_header('Content-type', 'text/json')
             self.end_headers()
             self.wfile.write(thisapi.getResult())
     except Exception as e:
         self.send_error(503,'Servicio No Disponible '+e.__str__())
예제 #4
0
class SshMonitorPlugin(Plugin, Thread):
    name = 'ssh monitoring plugin for elmot by Frolov Dmitry'
    keyword = 'sshmon'
    controlled = False
    
    def __init__(self):
        Plugin.__init__(self)
        Thread.__init__(self)
        self.api = Api()
	
    def follow(self, thefile):
        thefile.seek(0,2)
        while True:
            line = thefile.readline()
            if not line:
                time.sleep(0.1)
                continue
            if ('Failed password' in line):
                yield line.split(': ')[1].split('port')[0]


    def run(self):
        logfile = open('/var/log/auth.log')
        loglines = self.follow(logfile)
        
        for line in loglines:
            line = line.replace('invalid user ', '', 1)
            self.api.tweet(line)
예제 #5
0
 def call(self, command):
     if command[0].lower() == 'exit':
         exit()
     if command[0].lower() == 'help':
         self.reader.printfile('help')
         return
     api = Api(self.client)
     api.call(command)
예제 #6
0
    def test_register_resources(self, m_flask_restful):
        Api._register_resources(m_flask_restful)

        call = mock_module.call

        m_flask_restful.add_resource.assert_has_calls(
            [call(VolumeList, '/volumes'), call(Volume, '/volumes/<volume_id>')],
            any_order=True)
예제 #7
0
파일: twiner.py 프로젝트: Gwildor/Twiner
def run(path_to_conf='conf.ini', **kwargs):
    conf = ConfigParser.SafeConfigParser()
    with io.open(path_to_conf, 'rb') as fd:
        conf.readfp(fd)

    params = {}
    for key, val in conf.items('params'):
        if key in ['trim_user', 'exclude_replies', 'contributor_details',
                   'include_rts']:
            params[key] = int(conf.getboolean('params', key))
        else:
            params[key] = val
    params.update(kwargs)

    try:
        db_url = conf.get('database', 'url')
    except ConfigParser.NoOptionError:
        if conf.get('database', 'type') == 'sqlite':
            db_url = 'sqlite://{0}'.format(conf.get('database', 'name'))
        else:
            db_url = '{0}://{1}:{2}@{3}/{4}'.format(
                conf.get('database', 'type'),
                conf.get('database', 'user'),
                conf.get('database', 'password'),
                conf.get('database', 'host'),
                conf.get('database', 'name')
            )

    engine = create_engine(db_url)
    models.Base.metadata.create_all(bind=engine)

    Session = sessionmaker(bind=engine)
    session = Session()

    api = Api(conf.get('api', 'consumer_key'), conf.get('api',
                                                        'consumer_secret'))

    for tl in session.query(models.Timeline):

        if not tl.last_update or datetime.datetime.now() >= \
                tl.last_update + tl.interval:

            last_tweet = tl.tweets.order_by(models.Tweet.id.desc()).first()
            if last_tweet:
                params['since_id'] = last_tweet.id
            elif 'since_id' in params:
                del params['since_id']

            tweets = api.get_user_timeline(params=params,
                                           screen_name=tl.screen_name)
            for tweet in tweets:
                if not session.query(models.Tweet).get(tweet['id']):
                    tl.tweets.append(models.Tweet(tweet))

            tl.last_update = datetime.datetime.now()

    session.commit()
예제 #8
0
def do(config):

    api = Api(config['api'])
    ok, status, data = api.post('/Profile/getOwnProfile')
    text = config['format'] % data['user_info']
    params = dict(content=text.encode('UTF-8'), qualifier=':')
    ok, status, data = api.post('/Timeline/plurkAdd', params)
    if not ok:
        logging.error('status: %s' % status)
        logging.error(data)
예제 #9
0
파일: test.py 프로젝트: mong2/api_helper
class Test:
	def __init__(self):
		config = ConfigParser.ConfigParser()
		# Replace config.conf with your own auth_file name
		config.read('config.conf')

		key_id = config.get('api_key_pair','key_id')
		secret_key = config.get('api_key_pair', 'secret_key')

		api_hostname = config.get('api_key_pair', 'api_hostname')

		oauth = APIToken(api_hostname)
		token = oauth.get_token(key_id, secret_key)

		self.api = Api(token)
		return None

	def test_get(self):
		resp = self.api.get("v1/servers")
		if not resp.raise_for_status():
			data = resp.json()
			print data
		return None

	def test_post(self):
		body = {
			"policy": {
				"name": "Testing-hlee",
				"platform": "linux"
			}
		}
		resp = self.api.post("v1/policies", body)
		if not resp.raise_for_status():
			data = resp.json()
			policy_id = data["policy"]["id"]
			return policy_id

	def test_put(self):
		body = {
			"policy": {
				"name": "Update-hlee"
			}
		}
		# got the policy id from test_post. you can definitely add an argument to pass in the policy
		# instead of hard coded in the below url.
		resp = self.api.put("v1/policies/15be2cbec3a511e5a01759521d1a9f69", body)
		resp.raise_for_status()
		return None

	def test_delete(self):
		self.api.delete("v1/policies/15be2cbec3a511e5a01759521d1a9f69")
		# resp.raise_for_status()
		return None
예제 #10
0
class ApiTest(unittest.TestCase):

    @defer.inlineCallbacks
    def setUp(self):
        self.conn = yield txmongo.MongoConnection('127.0.0.1', DB_PORT)
        self.db = self.conn.test_db
        self.api = Api(self.db, bcrypt.gensalt())

    @defer.inlineCallbacks
    def tearDown(self):
        yield self.db.user.drop()
        yield self.db.firm.drop()
        yield self.conn.disconnect()

    @defer.inlineCallbacks
    def test_user_create(self):
        name = "user"
        fullname = "User User"
        password = "******"
        yield self.api.create_user(name, fullname, password)
        [user] = yield self.api.get_user(name)
        self.assertEqual(user['name'], "user")
        self.assertEqual(user['fullname'], "User User")
        self.assertEqual(user['password'], self.api.hash_password("password".encode('utf-8')))

    @defer.inlineCallbacks
    def test_user_already_exists(self):
        name = "user"
        fullname = "User User"
        password = "******"
        yield self.api.create_user(name, fullname, password)
        yield self.assertFailure(self.api.create_user(name, fullname, password), UserAlreadyExists)

    @defer.inlineCallbacks
    def test_create_firms(self):
        name= 'My firm' 
        adress = 'Riksdalersgatan 25C'
        postal_code = '41481'
        city = 'Gothenburg'
        yield self.api.create_firm(name, adress, postal_code, city)

        adress2 = 'Marklandsgatan 67'
        postal_code2 = '1234'

        yield self.api.create_firm(name, adress2, postal_code2, city)

        [firm1, firm2] = yield self.api.get_firms({'name': name})

        self.assertEqual(firm1['name'], name)
        self.assertEqual(firm1['adress'], adress)
        self.assertEqual(firm1['postal_code'],postal_code)
        self.assertEqual(firm1['city'],city)

        self.assertEqual(firm2['adress'],adress2)

        [firm] = yield self.api.get_firms({'adress':adress2})
        self.assertEqual(firm['adress'],adress2)
예제 #11
0
 def draw_snake(self):
     for i in range(0, self.snake.body.__len__()):
         x0, y0 = Api.position_to_pix(self.snake.body[i][0], self.snake.body[i][1])
         x1 = x0+10
         y1 = y0+10
         self.canvas.create_rectangle(x0, y0, x1, y1, fill="white", outline=None, width=0)
         if i != (self.snake.body.__len__()-1):
             x2, y2 = Api.position_to_pix(self.snake.body[i+1][0], self.snake.body[i+1][1])
             x3 = (x0 + x2)/2
             y3 = (y0 + y2)/2
             x4 = x3+10
             y4 = y3+10
             self.canvas.create_rectangle(x3, y3, x4, y4, fill="white", outline=None, width=0)
예제 #12
0
def do_post(config, added, deled):
    api = Api(config['api'])
    desc = u''
    if added:
        desc += u'\n'.join(sorted(added)) + u'\nが増えました\n(カルマの状態によっては使えない場合があります)\n\n'
    if deled:
        desc += u'\n'.join(sorted(deled)) + u'\nが減りました\n\n'
    if desc:
        url = paste(desc)
        text = u' '.join([u' '.join(sorted(added)), u':', url, u'(details...)'])
        params = dict(content=text.encode('UTF-8'), qualifier=':')
        ok, status, data = api.post('/Timeline/plurkAdd', params)
        if not ok:
            logging.error('status: %s' % status)
            logging.error(data)
예제 #13
0
    def run(self):
        try:
            # 读取待转换的书籍信息
            wait_converts = Tbl_Wait_Converts()
            wait_converts_info = wait_converts.get(self.convert_id)
            if not wait_converts_info:
                raise Exception, '未找到待转换的书籍信息'

            # 读取书籍所需图片
            book_img = Tbl_Book_Img()
            book_img_info = book_img.get(self.book_id)
            if book_img_info:
                # 更新书籍所需图片表信息
                book_img.update_local_path(self.book_id, self.book_images_task.get())

            # 读取书籍信息
            books = Tbl_Books()
            book_info = books.get_by_book_id(self.book_id)

            ## 调用转换功能
            out_file_path = proc_helper.convert(str(wait_converts_info['book_html_local_path']), self.out_dir, book_info['book_author'], book_info['book_cover_local_path'])
            if out_file_path == None:
                # 转换失败
                wait_converts.update_status(gk7.STATUS.get('error'), self.convert_id)
                raise Exception, '转换html to mobi失败'

            # 转换成功,修改状态,添加书籍输出路径
            wait_converts.update_status(gk7.STATUS.get('complete'), self.convert_id, out_file_path)
            # 修改书籍文件路径
            books.update_file_path(self.book_id, out_file_path)

            wait_email = Tbl_Wait_Emails()
            # 修改待发送邮件附件信息
            wait_email.update_attach_file(self.email_id, out_file_path)
            # 读取待发送邮件信息
            wait_email_info = wait_email.get(self.email_id)
            if not wait_email_info:
                raise Exception, '未找到待发送邮件信息,邮件ID:%s' %self.email_id
            # 发送邮件
            Api.send_mail(self.email_id, wait_email_info['email_attach_file'], str(wait_email_info['email_to_user']), str(wait_email_info['email_title']), str(wait_email_info['email_auth']))
            # 发送邮件至个人邮箱to_private_email
            if self.to_private_email:
                private_email_id = RandomUtil.random32Str()
                wait_email.add_full(private_email_id, self.to_private_email, str(wait_email_info['email_title']), str(wait_email_info['email_auth']), wait_email_info['email_attach_file'])
                MailTask.send.delay(private_email_id, wait_email_info['email_attach_file'], self.to_private_email, str(wait_email_info['email_title']), str(wait_email_info['email_auth']))
        except Exception, err:
            logger.error(u'异步线程出错,转换ID:%s,错误信息:%s', self.convert_id, err)
            exit(-1)
예제 #14
0
    def __init__(self, parent=None):
        super().__init__(parent)
        # set app name before mediaObject was created to avoid phonon problem
        # QCoreApplication.setApplicationName("NetEaseMusic-ThirdParty")
        self.ui = UiMainWidget()    # 那些widget对象都通过self.ui.*.*来访问,感觉也不是很好
        self.ui.setup_ui(self)

        self.player = Player()

        self.current_playlist_widget = MusicTableWidget()
        self.lyric_widget = LyricWidget(u'没有正在播放的歌曲')

        self.status = self.ui.status
        self.trayicon = TrayIcon(self)
        self.webview = self.ui.right_widget.webview     # 常用的对象复制一下,方便使用
        self.progress = self.ui.top_widget.progress_info
        self.network_manger = NetworkManager()

        self.search_shortcut = QShortcut(QKeySequence("Ctrl+F"), self)

        self.play_or_pause_btn = self.ui.top_widget.play_pause_btn

        self.web = MyWeb()
        self.api = Api()
        self.network_queue = Queue()

        self.init()

        self.state = {'is_login': False,
                      'current_mid': 0}
예제 #15
0
    def run(self):
        debug.message("Starting build of project %s" % self.project["Name"], indent=1)

        build_result = 0
        for solution in self.get_solutions():
            build_result += self.run_build(solution)

            if build_result != 0:
                Api.update_status(self.commit["ID"], CommitStatus.BuildError)
                raise Exception("Build of solution %s failed" % solution["name"])

            self.publish()
            debug.message("Build of solution %s succeeded!" % solution["name"], indent=2)

        Api.update_status(self.commit["ID"], CommitStatus.Build)
        debug.message("Build of project %s completed" % self.project["Name"], indent=1)
예제 #16
0
    def get_test_cases(self,id=None):
        if id is not None: response=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_test_cases_exe_filter.format(folder_name=id))
        else: response=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_test_cases_exe)
        r=['[']
        users=Api.get_users()
        for i, item in enumerate(response):
            if i!= len(response)-1:
                r.append('{ "id": "%s", "tc_id": "%s", "name": "%s", "executor": "%s", "type": "%s", "status": "%s", "date": "%s", "time": "%s" }, '%(item[0],item[1],item[2],users[item[3]],item[4],item[5],item[6].strftime("%Y-%m-%d"),item[7]))
            else:
                r.append('{ "id": "%s", "tc_id": "%s", "name": "%s", "executor": "%s", "type": "%s", "status": "%s", "date": "%s", "time": "%s" }'%(item[0],item[1],item[2],users[item[3]],item[4],item[5],item[6].strftime("%Y-%m-%d"),item[7]))
        r.append(']')
        return ''.join(r)

    # @cherrypy.expose()
    # def get_test_cases(self,id=None,_=None):
    #     #http://127.0.0.1:8081/cases/get_test_cases?id=/folder1/subfolder_1/
    #     response=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_test_cases.format(id.split("/")[-2]))
    #     r=['{"aaData":[']
    #     users=Api.get_users()
    #     for i, item in enumerate(response):
    #         if i!= len(response)-1:
    #             r.append('{"id":"%s","name":"%s","execution_type":"%s","type":"%s","execution_expected_time":"%s","creation_date":"%s","status":"%s"},'%(item[0],item[5],item[9],item[10],item[3],item[4].strftime("%Y-%m-%d"),item[11]))
    #         else:
    #             r.append('{"id":"%s","name":"%s","execution_type":"%s","type":"%s","execution_expected_time":"%s","creation_date":"%s","status":"%s"}'%(item[0],item[5],item[9],item[10],item[3],item[4].strftime("%Y-%m-%d"),item[11]))
    #     r.append(']}')
    #     return ''.join(r)
예제 #17
0
    def __init__(self, parent=None):
        super(LoginDialog, self).__init__(parent)
        self.username_lable = QLabel()
        self.password_lable = QLabel()
        self.hint_label = QLabel()
        self.username_widget = QLineEdit()
        self.password_widget = QLineEdit()
        self.login_btn = QPushButton()

        self.captcha_label = QLabel()
        self.captcha_lineedit = QLineEdit()

        self.layout = QVBoxLayout()
        self.is_remember_chb = QCheckBox(u"记住账号")

        self.nm = NetworkManager()

        self.filename = CACHE_PATH + "user.json"
        self.ne = Api()

        self.is_autofill = False
        self.is_need_captcha = False
        self.captcha_id = 0
        self.user_data = 0

        self.__set_signal_binding()
        self.__set_widgets_prop()
        self.__set_layouts_prop()
        self.__set_me()
        self.fill_content()
예제 #18
0
 def get_defect_content(self,def_id):
     users=Api.get_users()
     #users=self.get_users()
     attachments=[]
     attachments_data=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_defect_attachments.format(def_id=def_id))
     for i, attachment in enumerate(attachments_data):
         attachments.append([attachment[3],attachment[2],attachment[6]])
     comments=[]
     comments_data=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_defect_comments.format(def_id=def_id))
     for i, comment in enumerate(comments_data):
         comments.append([comment[0],users[comment[2]],comment[3].strftime("%Y-%m-%d %H:%M"),comment[4]])
     linked_test=[]
     #linked_test_data=
     ####### TODO! #######
     linked_test_data=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_defect_linked_tests.format(def_id=def_id))
     for i, comment in enumerate(linked_test_data):
         linked_test.append([comment[0],users[comment[2]],comment[3].strftime("%Y-%m-%d"),comment[1]])
     response=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_defect_additional_data.format(def_id=def_id))[0]
     data={}
     data['id']=def_id
     data['name']=response[1] if response[1] is not None else ''
     data['assign']=users[response[6]]
     data['assign_id']=response[6]
     data['status']=response[11] if response[11] is not None else ''
     data['status_id']=response[5]
     data['fix']=users[response[7]]
     data['fix_id']=response[7]
     data['type']=response[12] if response[12] is not None else ''
     data['add_date']=response[3].strftime("%Y-%m-%d")
     data['fix_date']='2012-01-01'
     data['description']=response[9] if response[9] is not None else ''
     data['solution']=response[10] if response[10] is not None else ''
     data['comments']=comments
     data['linked_test']=linked_test
     return data
예제 #19
0
        def all_routes():
            if request.method == 'OPTIONS':
                return ''

            action = (request.json and request.json.pop('action', None)) or (
                request.args and request.args.pop('action', None))
            if not action:
                return '<html><body><h1>Hi there!</h1></body></html>'

            if action == 'tree':
                return api.tree()
            elif action == 'get_all':
                return api.get_all()
            elif action == 'query':
                return api.query()
            elif action == 'update_person':
                return api.update_person()
            elif action == 'add_person':
                return api.add_person()
            elif action == 'get_role':
                return Api.get_role()
            elif action == 'remove_person':
                return api.remove_person()
            else:
                return '<html><body><h1>Unknown action</h1></body></html>', 404
예제 #20
0
def watch(build_queue):
    while True:
        debug.set_prefix("repository_watcher")
        debug.message("Retrieving projects")
        try:
            projects = Api.get_projects()

            for project in projects:
                debug.message("Check repository status for project %s" % project["Name"])
                repository = Git(get_path(project), get_origin_url(project))
                commit_count = handle_incoming_commits(repository.check_for_new_commits_on_origin(), project,
                                                       repository, build_queue)
                if commit_count > 0:
                    repository.merge_origin()

                # Add <initial_nr_commits> commits if this is a new repository
                if project["Commits"] is None or len(project["Commits"]) == 0:
                    handle_incoming_commits(
                        repository.get_commits(registry.config["repositories"]["initial_nr_commits"]), project,
                        repository, build_queue)

        except ValueError, e:
            debug.exception("Error retrieving projects", e)
        except GitError, e:
            debug.exception("Error with Git repository", e)
예제 #21
0
    def get_main_content(self):
        data={}

        user_name="Test Test"
        login_time="12:00" #sqlquery_get_login_time
        logged_time="58" #now() - login_time
        data['user_name']=user_name
        data['login_time']=login_time
        data['logged_time']=logged_time
        response=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_project_notes)
        users=Api.get_users()
        project_notes = []
        for i, item in enumerate(response):
            temp=[]
            temp.append(item[0])
            temp.append(item[1])
            temp.append(item[2])
            temp.append(users[item[5]])
            project_notes.append(temp)
        data['project_notes']=project_notes
        response=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_user_notes)
        user_notes = []
        for i, item in enumerate(response):
            temp=[]
            temp.append(item[0])
            temp.append(item[1])
            temp.append(item[3])
            user_notes.append(temp)
        data['user_notes']=user_notes
        return data
예제 #22
0
 def update_defect(self,def_id,params):
     defects_data={'name':'def_name','assign':'def_assigned_to','status_id':'def_status','fix':'def_fixed_by','type':'def_type','description':'def_description'}
     for key, value in params.items():
         #if key == 'status':
         #    value=Api.get_statuses()[value]
         if key == 'type':
             value=Api.get_types()[value]
         cherrypy.session.get('project_db_connection').execute_query(sqlquery_update_defect.format(position=defects_data[key], value=value, def_id=def_id),select=False)
예제 #23
0
def handle_incoming_commits(commits, project, repository, build_queue):
    for commit in commits:
        debug.message("Add commit %s to database" % commit.oid, indent=2)

        commit_date = datetime.fromtimestamp(int(commit.commit_time)).strftime('%Y-%m-%d %H:%M:%S')

        if len(commit.parents) > 0:
            changes = repository.get_changes(commit, commit.parents[0])
        else:
            changes = repository.get_changes(commit)

        Api.add_commit(project["ID"], commit.oid, commit_date, commit.message, commit.author.name, changes)

        project["commit"] = commit.oid
        build_queue.put(project)

    return len(commits)
예제 #24
0
class Thread(QThread):

    def __init__(self, user, password):
        QThread.__init__(self)
        self.api = Api(user, password)
        self.executable = self.login
        self.data = None
        self.folder = ''

    def run(self):
        self.executable()
        self.data = None
        self.folder = ''

    def login(self):
        auth = self.api.login()
        if auth == 0:
            self.emit(SIGNAL("loginSuccess()"))
        elif auth == 1:
            self.emit(SIGNAL("loginFail()"))
        else:
            self.emit(SIGNAL("userUnknown()"))

    def get_files(self):
        self.api.get_files()
        self.emit(SIGNAL("filesList()"))

    def update_files(self):
        self.api.get_files()
        self.emit(SIGNAL("filesUpdated()"))

    def download_file(self):
        self.api.download_file(self.data, self.folder)
        self.emit(SIGNAL("downloadFinished(QString)"), self.data['file-name'])
예제 #25
0
파일: manager.py 프로젝트: lbryio/lbry
 def new_instance(cls, api=None, events=None):
     if api is None:
         api = Api.new_instance()
     if events is None:
         events = Events(
             make_context(get_platform(), settings.wallet),
             'not loaded', 'not loaded'
         )
     return cls(api, events, Track())
예제 #26
0
class ApiTest(unittest.TestCase):


	def setUp(self):
		self.Api = Api(source='hacker_news')

	def test_hacker_news_api(self):
		self.assertEqual(self.Api.url, 'http://api.ihackernews.com/page')


	def test_can_retrive_data(self):
		self.Api.fetch_data()
		self.assertTrue(self.Api.json_response)


	def test_to_pass_data_into_processor(self):
		self.test_can_retrive_data()
		self.Processor = Processor(self.json_response)
예제 #27
0
def init_file_server_by_key(key):
    config = Api(key=key).get_config_by_key().get('data')

    file_service = FileService(account_name=config.get('account_name'),
                               account_key=config.get('account_key'),
                               endpoint_suffix=config.get('endpoint_suffix'))

    logging.basicConfig(
        format='%(asctime)s %(name)-20s %(levelname)-5s %(message)s',
        level=logging.INFO)
    logger = logging.getLogger('azure.storage')
    handler = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)s %(name)-20s %(levelname)-5s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)

    return file_service
예제 #28
0
파일: nso.py 프로젝트: denniswa/nerds
def main(config, section, out_dir, not_to_disk):
    base_url = config['nso']['url']
    api_user = config['nso']['user']
    api_password = config['nso']['password']

    api = Api(base_url, api_user, api_password)
    device_groups = api.get('/devices/device-group?shallow', collection=True)
    device_groups = {
        dg['name']: dg['device-name']
        for dg in find(
            'collection.tailf-ncs:device-group', device_groups, default=[])
    }

    if config.has_section(section):
        devices = get_devices(config[section], device_groups)
        logger.debug('Processing %s: %s', section, devices)
        process_devices(api, out_dir, not_to_disk, devices)
    else:
        logger.error('Configuration does not have a %s section', section)
예제 #29
0
    def __init__(self, n, m, depth, save_permission, user_id, team_id,
                 game_id):
        self.N = n
        self.M = m
        self.DEPTH = depth
        self.SAVE_PERMISSION = save_permission
        self.SLEEP_TIME = 5

        self.G = Game(n, m)
        self.T = Tree(n, m, depth)
        self.API = Api(user_id, team_id)
        self.API.set_game_id(game_id)

        # load cache
        self.S = Save(n, m, self.SAVE_PERMISSION)
        out = self.S.load()
        if out:
            print('loaded')
            self.T.EF.Hash = out
예제 #30
0
def main(team, password, url):
	api = Api(url, password, team)
	board = Board(25, 25)

	cursor.hide()
	print("\033[2J")
	initState(api, board)

	mainLoop(api, board)
	exit()
예제 #31
0
def main():
    api = Api()
    good_consumer(api.get_foo())
    print("*** After good consumer ***")
    print(api.get_foo())
    print()

    api = Api()
    evil_consumer(api.get_foo())
    print("*** After evil consumer ***")
    print(api.get_foo())
    print()
예제 #32
0
 def __init__(self,
              protocol="http",
              hostname="",
              port="",
              authenticationMethode="basic"):
     Api.__init__(self)
     self._protocol = protocol.lower()
     self._hostname = hostname
     self._port = port
     self._rootUrl = self._protocol + "://" + self._hostname + ":" + self._port
     self.setAuthenticationMethode(authenticationMethode)
     # Loading configuration file with all the api
     with open("ambari_api.json") as jsonFile:
         self._config = json.load(jsonFile)
     self._clusterNameMask = self._config["clusterNameMask"]
     self._serviceNameMask = self._config["serviceNameMask"]
     self._requestIdMask = self._config["requestIdMask"]
     self._sleepingTimeInSeconds = self._config["sleepingTimeInSeconds"]
     self._api = self._config["api"]
예제 #33
0
파일: manager.py 프로젝트: Fillerix99/lbry
 def new_instance(cls, api=None, events=None):
     if api is None:
         api = Api.new_instance()
     if events is None:
         events = Events(
             make_context(get_platform(), conf.settings['wallet']),
             base58.b58encode(conf.settings.get_lbry_id()),
             conf.settings.get_session_id(),
         )
     return cls(api, events, Track())
예제 #34
0
def do(config):

    api = Api(config['api'])
    ok, status, data = api.post('/Timeline/getUnreadPlurks')
    if not ok:
        logging.error('''api.post('/Timeline/getPlurks')''')
        logging.error('status: %s' % status)
        logging.error(data)
        return

    interval = config.get('interval', 1)
    balancer = Balancer()
    for rec in data.get('plurks', []):
        if is_god_reading_fortune(rec):
            balancer.clear()
            plurk_id = rec.get('plurk_id', 0)
            content = rec.get('content', u'')
            do_post(balancer, content)
            logging.info('plurk: %ld' % plurk_id)
            ok, status, data = api.post('/Responses/get', dict(plurk_id=plurk_id))
            if not ok:
                logging.error('''api.post('/Responses/get', dict(plurk_id=%s))''' % plurk_id)
                logging.error('status: %s' % status)
                logging.error(data)
                continue
            for rec in data.get('responses', []):
                content = rec.get('content', u'')
                do_post(balancer, content)
                logging.debug([content, balancer.complement])

            complement = balancer.complement
            if 0 < len(complement):
                for text in uniquify(split_text(complement)):
                    logging.info('  posting: %s' % text)
                    params = dict(plurk_id=plurk_id, qualifier=':', content=text.encode('UTF-8'))
                    ok, status, data = api.post('/Responses/responseAdd', params)
                    if not ok:
                        logging.error('''api.post('/Responses/responseAdd', dict(content=%s))''' % complement)
                        logging.error('status: %s' % status)
                        logging.error(data)
                        break
                    sleep(interval)
예제 #35
0
def do(config):

    api = Api(config["api"])
    ok, status, data = api.post("/Timeline/getUnreadPlurks")
    if not ok:
        logging.error("""api.post('/Timeline/getPlurks')""")
        logging.error("status: %s" % status)
        logging.error(data)
        return

    interval = config.get("interval", 1)
    balancer = Balancer()
    for rec in data.get("plurks", []):
        if is_god_reading_fortune(rec):
            balancer.clear()
            plurk_id = rec.get("plurk_id", 0)
            content = rec.get("content", u"")
            do_post(balancer, content)
            logging.info("plurk: %ld" % plurk_id)
            ok, status, data = api.post("/Responses/get", dict(plurk_id=plurk_id))
            if not ok:
                logging.error("""api.post('/Responses/get', dict(plurk_id=%s))""" % plurk_id)
                logging.error("status: %s" % status)
                logging.error(data)
                continue
            for rec in data.get("responses", []):
                content = rec.get("content", u"")
                do_post(balancer, content)
                logging.debug([content, balancer.complement])

            complement = balancer.complement
            if 0 < len(complement):
                for text in uniquify(split_text(complement)):
                    logging.info("  posting: %s" % text)
                    params = dict(plurk_id=plurk_id, qualifier=":", content=text.encode("UTF-8"))
                    ok, status, data = api.post("/Responses/responseAdd", params)
                    if not ok:
                        logging.error("""api.post('/Responses/responseAdd', dict(content=%s))""" % complement)
                        logging.error("status: %s" % status)
                        logging.error(data)
                        break
                    sleep(interval)
예제 #36
0
    def testRun(self):
        """Verify plain RestAPI GET request"""
        try:
            json_str = self.setup_class()
            if json_str['url1']['path']:
                url = constructURL.constURL(
                    baseurl=json_str['url1']['baseurl'],
                    path=json_str['url1']['path'])
            else:
                url = json_str['url1']['baseurl']

            req = Api(url=url)

            resp = req.get()
            self.assertEqual(200, resp.status_code)
            response_type = resp.headers["content-type"]
            if re.search(r'json', response_type):
                response = resp.json()
        except Exception as e:
            print("Exception occurred during test run", e)
예제 #37
0
class EdgeAI:
    def __init__(self, app_token=None, app_secret=None):
        self.app_token = app_token or os.environ.get('EDGE_AI_TOKEN')
        self.app_secret = app_secret or os.environ.get('EDGE_AI_SECRET')

        self.api = Api(self.app_secret)

    def predict(self, features=None):
        payload = {'features': features or {}, 'app_token': self.app_token}

        return self.api.post('/predict', payload)
예제 #38
0
    def __init__(self, *args, **kwargs):
        """
        Initialize the Service object.

        Keyword Arguments:
            poll_seconds: time between checks for new files
        """
        self.poll_seconds = kwargs.pop('poll_seconds')

        self.api = Api()
        self.stop_event = Event()
예제 #39
0
 def get_test_cases(self,_=None):
     response=cherrypy.session.get('project_db_connection').execute_query(sqlquery_get_test_cases_for_iterations)
     r=['[']
     users=Api.get_users()
     for i, item in enumerate(response):
         if i!= len(response)-1:
             r.append('{ "id": "%s", "name": "%s", "designer": "%s", "execution_expected_time": "%s" }, '%(item[0],item[1],users[item[2]],item[3]))
         else:
             r.append('{ "id": "%s", "name": "%s", "designer": "%s", "execution_expected_time": "%s" } '%(item[0],item[1],users[item[2]],item[3]))
     r.append(']')
     return ''.join(r)
예제 #40
0
 def start(self):
     api = Api()
     self.window = webview.create_window(
         "Магазин приложений", 
         "../front/dist/index.html",
         js_api=api, 
         width=self.width, 
         height=self.height, 
         resizable=self.resizable,
     )
     webview.start(gui='cef', http_server=False, debug=True)
예제 #41
0
def put(put_request: PutRequest) -> Verdict:
    api = Api(put_request.hostname)
    try:
        username, password, bark = get_random_str(), get_random_str(), get_random_text()
        r = api.sing_up(username, password, get_random_str(), get_random_str())
        r = api.add_bark(username, bark, is_private=True)
        bark_id = int(r.text.split(bark)[0].split("/get_bark/")[1][0:-3])
        api.comment_bark(bark_id, put_request.flag, is_private=True)
        token = api.generate_token()
        api.logout()
        return Verdict.OK(f"{username}:{password}:{bark_id}")
    except RequestException as e:
        print(f"can't connect due to {e}")
        return Verdict.DOWN("can't connect to host")
    except Exception as e:
        print(e)
        return Verdict.MUMBLE("bad proto")
예제 #42
0
def main_function():
    uid = login_from_cli()
    running = True  # There's no do-while loop in Python, so we use this instead
    print_help()
    api = Api()
    while running:
        cmd = [i.strip() for i in input(">").strip().split(" ")]
        print(cmd)
        if cmd[0] == "quit" or cmd[0] == "exit":
            exit(1)
        elif cmd[0] == "list" and cmd[1] == "item":
            items = api.get_items_by_category(uid, cmd[2])
            for item_id in items:
                print(api.get_item_info(item_id))
        elif cmd[0] == "add":
            print(api.add_item_to_cart(uid, cmd[1], cmd[2]))
        elif cmd[0] == "list" and cmd[1] == "cart":
            print(api.get_cart_by_id(uid))
        elif cmd[0] == "remove" and cmd[1] == "item":
            print(api.remove_item_from_cart(uid, cmd[2], cmd[3]))
        elif cmd[0] == "checkout":
            pass
        elif cmd[0] == "edit" and cmd[1] == "address":
            read = ""
            name = input("shipping name > ")
            line1 = input("address line 1 > ")
            line2 = input("address line 2 > ")
            city = input("city > ")
            state = input("state > ")
            zip = input("zip > ")
            while True:
                read = input(
                    f"Does the following look correct?\n{name}\n{line1}\n{line2}\n{city}, {state}\n{zip}\ny/n"
                )
                if read.lower().strip() == "y":
                    print(
                        api.edit_address(name=name,
                                         line1=line1,
                                         line2=line2,
                                         city=city,
                                         state=state,
                                         zip=zip))
                if read.lower().strip() == "n":
                    continue

            print(api.edit_address())
예제 #43
0
    def get(self, *args, **kwargs):
        """Handles ALL requests. Figures out the user and then delegates to
        more purpose-specific methods."""
        # Some poorly-behaved libraries screw with the default logging level,
        # killing our 'info' and 'warning' logs. Make sure it's set correctly
        # for our code.
        util.allow_all_logging()

        # Mark the start time of the request. You can add events to this
        # profiler in any request handler like this:
        # util.profiler.add_event("this is my event")
        util.profiler.clear()
        util.profiler.add_event('START')

        # create and sign in as a god user under certain conditions
        self.immaculately_conceive()
        # Running this ensures that cached users (e.g. self._user) are
        # correctly synched with the session ids.
        self.clean_up_users('user')
        self.clean_up_users('impersonated_user')
        # Deal with impersonation options
        if self.request.get('escape_impersonation') in config.true_strings:
            # Allow calls to escape impersonation, i.e. treat the call as if
            # the true user (not the impersonated user) was making it.
            # Should have no effect when no impersonation is happening.
            self._impersonated_user = None
            self.api = Api(self.get_current_user(method='normal'))
        elif self.request.get('impersonate'):
            # If allowed, impersonate the provided user for just this call
            target_user = User.get_by_id(self.request.get('impersonate'))
            normal_user = self.get_current_user(method='normal')
            if normal_user.can_impersonate(target_user):
                self._impersonated_user = target_user
                self.api = Api(target_user)
            else:
                logging.info('Impersonation denied. '
                             '{} is not allowed to impersonate {}.'.format(
                                 normal_user.id, target_user.id))
        if not hasattr(self, 'api'):
            # Instantiate an api class that knows about the current user and
            # their permissions. Will default to the permissions of the
            # impersonated user if there is one, or the public user if no one
            # is signed in.
            self.api = Api(self.get_current_user())
        # Also create an internal API that has god-like powers, only to be used
        # by interal platform code, never exposed through URLs.
        self.internal_api = Api(User.create(user_type='god'))
        # We are in the "grandparent" function; do_wrapper() is the "parent",
        # defined in either ApiHandler or ViewHandler; in turn, the "child"
        # function do() will be called.
        self.do_wrapper(*args, **kwargs)
예제 #44
0
class Poloniex:
    def __init__(self, currency_pair, period):
        self.currency_pair = currency_pair
        self.period = period
        self._api = Api(self.currency_pair, self.period)

    def _list_currencies(self):
        return self._api.currencies()

    def valids_currencies(self):
        if self.currency_pair in self._list_currencies():
            return True
        return False

    def get_response(self):
        if self._api.get_status_code() == 200:
            return self._api.response()
        raise ConnectionError('Could not possible return the response')

    def get_chart_data(self):
        try:
            for currency in self.get_response().items():
                if currency[0] == self.currency_pair:
                    currency[1].pop('lowestAsk', None)
                    currency[1].pop('highestBid', None)
                    currency[1].pop('percentChange', None)
                    currency[1].pop('baseVolume', None)
                    currency[1].pop('quoteVolume', None)
                    currency[1].pop('isFrozen', None)
                    return currency[1]
            return None
        except IndexError:
            raise IndexError('List out of range')

    def get_field(self, name):
        items = self.get_chart_data().items()
        if items is not None:
            for key, value in items:
                if key == name:
                    return value
        return None
예제 #45
0
class ApiTestCase(unittest.TestCase):
    def setUp(self):
        self.api = Api('BTC_BTS', 60)

    def test_instance(self):
        self.assertIsInstance(self.api, Api)

    def test_get_status_code(self):
        self.assertEqual(self.api.get_status_code(), 200)

    def test_response(self):
        self.assertIsNotNone(self.api.response())

    def test_currencies(self):
        data = self.api._connection.json().keys()
        self.assertEqual(self.api.currencies(), data)

    def test_raise_currencies(self):
        data = self.api._connection.json()
        self.assertRaises(TypeError, self.api.currencies(),
                          type(data) != dict(), data.keys())
예제 #46
0
def get_api():
    api = Api(
        config.API_BASE_URL,
        basic_auth=(
            u'{0}@{1}'.format(
                config.ORIGIN_ADMIN_USERNAME,
                config.ORIGIN_TENANT_NAME,
            ),
            config.ORIGIN_ADMIN_PASSWORD,
        ),
    )
    return api
예제 #47
0
def get(get_request: GetRequest) -> Verdict:
    api = Api()
    try:
        addr, secret = get_request.flag_id.strip().split(":")
        try:
            resulting_info = api.basement_info(get_request.hostname, addr,
                                               secret)
            if get_request.flag in resulting_info:
                return Verdict.OK()
            else:
                print(resulting_info, get_request.flag)
                return Verdict.CORRUPT("bad flag")
        except Exception as e:
            print(f"bad access {e}")
            return Verdict.CORRUPT("can't reach flag")
    except RequestException as e:
        print(e)
        return Verdict.DOWN("seems to be down")
    except Exception as e:
        print(f"ex {e}")
        return Verdict.MUMBLE("bad proto")
예제 #48
0
async def read_messages_from_admin_scenario(chats):
    for chat in chats:
        user = User()
        chat_id = chat['id']
        async with Api(url) as api:
            await api.register(user.get_register_data())
            await api.login(user.username, user.password)
            await api.join(chat_id, chat_id)
            resp = await api.read_messages(chat_id)
        if len(resp['messages']) > 0:
            print(resp['messages'])
            yield [x['text'] for x in resp['messages']]
예제 #49
0
파일: state.py 프로젝트: gimu/chancli
    def __init__(self):
        # Api calls
        self.api = Api()

        # Save temporary data for quick opening (open <index> command)
        self.current_threads = {'board': None, 'list': []}

        # JSON data
        self.boards_json = None
        self.threads_json = None
        self.thread_json = None
        self.archive_json = None
예제 #50
0
def get(get_request: GetRequest) -> Verdict:
    api = Api(get_request.hostname)
    try:
        username, password = get_request.flag_id.split(":")
        r = api.login(username, password)

        if r.status_code != 200:
            return Verdict.MUMBLE("can't login")

        if get_request.flag in r.text:
            return Verdict.OK()
        else:
            print(f"Can't find flag {get_request.flag} in {r.text}")
            return Verdict.CORRUPT("flag not found")

    except RequestException as e:
        print(f"can't connect due to {e}")
        return Verdict.DOWN("can't connect to host")
    except Exception as e:
        print(e)
        return Verdict.MUMBLE("bad proto")
예제 #51
0
 def setup_services(self):
     """A method to prepare the possible services that Cobalt can have."""
     self._service_endpoints = {
         'engine':
         Engine(self.etcd, self.volume_manager, self.machine_manager,
                self.config['engine']),
         'api':
         Api(self.volume_manager, self.config['api']),
         'agent':
         Agent(self.machine_manager, self.volume_manager,
               self.config['agent'])
     }
예제 #52
0
    def init_context(self):
        # public api
        self.p_api = Api(User(user_type='public'))

        # This closely follows the pattern of the populate script in god.html
        self.researcher = User(user_type='researcher')
        self.researcher.put()
        self.r_api = Api(self.researcher)
        self.teacher = User.create(user_type='teacher')
        self.teacher.put()
        self.t_api = Api(self.teacher)

        self.school = self.r_api.create('school', {'name': 'DGN'})
        self.program = self.r_api.create('program', {
            'name': 'Test Program',
            'abbreviation': 'TP1',
        })
        self.bad_program = self.r_api.create('program', {
            'name': 'Bad Program',
            'abbreviation': 'TP2',
        })
        self.cohort = self.r_api.create(
            'cohort', {
                'name': 'DGN 2014',
                'code': 'trout viper',
                'program': self.program.id,
                'school': self.school.id,
            })
        self.bad_cohort = self.r_api.create(
            'cohort', {
                'name': 'bad cohort',
                'code': 'king dolphin',
                'program': self.bad_program.id,
                'school': self.school.id,
            })
        self.r_api.associate('associate', self.teacher, self.cohort)
        self.classroom = self.t_api.create(
            'classroom', {
                'name': "English 101",
                'user': self.teacher.id,
                'program': self.program.id,
                'cohort': self.cohort.id,
            })
        # the researcher has to create this one, since the teacher is only
        # associated with the "good" program.
        self.bad_classroom = self.r_api.create(
            'classroom', {
                'name': "English 101",
                'user': self.teacher.id,
                'program': self.bad_program.id,
                'cohort': self.bad_cohort.id,
            })

        # Identify a student into a classroom. See
        # url_handlers._create_student()
        self.student = self.p_api.create('user', {
            'user_type': 'student',
            'classroom': self.classroom.id,
        })
        self.student.put()
예제 #53
0
def check_service(host: str) -> Verdict:
    try:
        with build_session() as session:
            api = Api(host, session)

            resp = api.register_user(Randomizer.user())
            if resp.status_code != 201:
                return Verdict.MUMBLE("Can't register user", "Can't register user")

            file_in_zip, *file = create_zip()
            resp = api.upload_zip(file)
            if resp.status_code != 202:
                return Verdict.MUMBLE("Can't upload file", "Can't upload file")

            resp = api.search_file(file_in_zip)
            if file_in_zip not in resp.text:
                return Verdict.MUMBLE("Can't find file from zip", "Can't find file from zip")

            resp = api.create_note(get_text(), True)
            if resp.status_code != 201:
                return Verdict.MUMBLE("Can't create note", "Can't create note")

            return Verdict.OK()
    except Exception as e:
        return Verdict.DOWN("Can't connect to service", str(e))
예제 #54
0
class Interface():
    def __init__(self):
        self.api = Api()
        board = self.api.make_board()
        self.sudoku = Sudoku(board)

    def validate_input_number(self, number, position_x, position_y):
        # Funcionalidad: Verifica si el valor ingresado es una letra o un
        # numero fuera de rango
        if number.isalpha() or position_x.isalpha() or position_y.isalpha():
            raise ValueError()
        if 1 <= int(number) <= 9 and -1 < int(position_x) < 9 and -1 < int(
                position_y) < 9:
            return True
        raise IncorrectNumber()

    def play_sudoku(self):

        print(self.sudoku.print_board())
        try:
            while not self.sudoku.is_over():
                self.number = input("Ingrese un numero: ")
                self.position_x = input("Ingrese la posicion x: ")
                self.position_y = input("Ingrese la posicion y: ")
                print("\n")
                if self.validate_input_number(self.number, self.position_x,
                                              self.position_y):
                    self.sudoku.put_number(int(self.position_x),
                                           int(self.position_y),
                                           int(self.number))
                print(self.sudoku.print_board())
            print("Felicitaciones ganaste")

        except InvalidPosition:
            print("No se puedo colocar el numero, hay un numero fijo")
            self.play_sudoku()
        except InvalidRow:
            print("El numero ya esta  en la fila")
            self.play_sudoku()
        except InvalidColumn:
            print("El numero ya esta  en la columna")
            self.play_sudoku()
        except InvalidRegion:
            print("El numero ya esta en la region")
            self.play_sudoku()
        except IncorrectNumber:
            print(
                "Ha ingresado incorrecto, debe ingresar un numero entre 1 y 9")
            self.play_sudoku()
        except ValueError:
            print("Ha ingresado una letra")
            self.play_sudoku()
예제 #55
0
파일: menu.py 프로젝트: djeidot/Battleship
 def get_games_list(self, event):
     player_name = event.el.get_value()
     r = Api.getPlayerInfo(player_name)
     games_list = [id for id in r["games"]] if r is not None else []
     label = thorpy.OneLineText.make("Here's a list of games " + player_name + " is in:")
     self.gamesListEdit = thorpy.DropDownList.make(games_list, size=(250,150), x=5)
     self.gamesListEdit.finish()
     gameSelectReaction = thorpy.Reaction(reacts_to=thorpy.constants.THORPY_EVENT,
                                          reac_func=self.start_game_join,
                                          event_args={"id": thorpy.constants.EVENT_DDL})
     self.gamesListEdit.add_reaction(gameSelectReaction)
     goBackButton = thorpy.make_button("Go Back", func=self.start_menu)
     self.replace_elements([label, self.gamesListEdit, goBackButton])
예제 #56
0
def wait_for_tray_event(mygui, server, username, hash_login, hash_msg):
    """ Check for config modification while waiting for action in systray
    """
    log.debug("Main Loop\n")
    log.debug(f"{server} - {username} - {hash_login} - {hash_msg}")
    api = Api(server, username, hash_login, hash_msg)

    while True:
        if Config.was_configfile_modified():
            log.info("Configfile was modified.")
            self_restart()
        event = mygui.tray.read()
        deal_with_tray_event(mygui, api, event)
예제 #57
0
파일: routes.py 프로젝트: MrKooka/YAPI
def app1_template():
    form = Search_form()

    q = request.args.get('q')  # q variable contains a search pattert

    if form.validate_on_submit():
        print('Сработала app1_template POST')
        url = form.url.data
        n = form.maxResults.data
        print(url, n)
        if 'replice' in request.form:
            print('replise in request.form')
            replice = request.form['replice']
            api = Api(url, n, replice)
            comments = api.get_all_comments()
            total = len(comments)
            return render_template('app1.html',
                                   dash_url=DashApp1.url_base,
                                   comments=comments,
                                   total=total,
                                   form=form)

        api = Api(url, n)
        comments = api.get_all_comments()
        total = len(comments)

        return render_template('app1.html',
                               dash_url=DashApp1.url_base,
                               comments=comments,
                               total=total,
                               form=form)

    q_comments = []

    if q and hasattr(Api, 'comments') and Api.comments != None:
        comments = Api.comments
        for i in comments:
            if q in i['textDisplay']:
                q_comments.append(i)
        total = len(q_comments)

        return render_template('app1.html',
                               dash_url=DashApp1.url_base,
                               comments=q_comments,
                               total=total,
                               form=form)

    else:
        if hasattr(Api, 'comments') and Api.comments != None:
            print('Сработало else hasattr(Api,"comments"')
            comments = Api.comments
            total = len(comments)
            return render_template('app1.html',
                                   dash_url=DashApp1.url_base,
                                   comments=comments,
                                   total=total,
                                   form=form)

    return render_template('app1.html', dash_url=DashApp1.url_base, form=form)
예제 #58
0
async def get_flag_from_deleted_messages(request: GetRequest) -> Verdict:
    admin_username, admin_password, chat_id, message_id = request.flag_id.split(
        ':')
    async with Api(f'http://{request.hostname}:3000') as api:
        try:
            await api.login(admin_username, admin_password)
        except InvalidResponseException as e:
            return Verdict.CORRUPT('Could not login or register',
                                   traceback.format_exc())
        except:
            return Verdict.DOWN('Could not connect to service',
                                traceback.format_exc())
        try:
            resp = await api.read_messages(chat_id)
        except InvalidResponseException:
            return Verdict.CORRUPT('Invalid response from service',
                                   traceback.format_exc())
        except:
            return Verdict.DOWN('Invalid response from service',
                                traceback.format_exc())
        try:
            messages = resp['messages']
            message = list(
                filter(lambda m: int(m['id']) == int(message_id), messages))
            if len(message) != 1:
                return Verdict.CORRUPT('Invalid messages count',
                                       f'with id: {message_id}')
            message_content = message[0]['text']
        except:
            return Verdict.CORRUPT('Invalid response from service',
                                   traceback.format_exc())

        try:
            resp = await api.get_chats()
            if 'chats' not in resp:
                return Verdict.MUMBLE('Invalid contract in chats listing',
                                      'invalid data')
            chats = resp['chats']
            if not chat_in_chats(chats, chat_id):
                return Verdict.MUMBLE('Can not find chat in chats',
                                      'invalid /chats')
        except:
            return Verdict.DOWN('Invalid response from service',
                                traceback.format_exc())

        if message_content != request.flag:
            return Verdict.CORRUPT(
                'Invalid flag',
                f'{request.flag}, message content: {message_content}')

        return Verdict.OK()
def upload_file_to_step(api: Api, run_id: int, file_path: str) -> bool:
    """
    Finds a run by the provided run ID and uploads the provided file
    to the first step of that run.

    Args:
        api (Api): API instance to send authenticated requests
        file_path (str): The path of the file to upload to the step

    Returns:
        bool: True if the upload succeeded
    """
    # Get the run you want to upload to, so we can find the step to upload to
    r = api.request({
        'query': queries.GET_RUN,
        'variables': {'id': run_id}
    })
    run = r['data']['run']
    first_step = run['steps'][0]

    # Get the target URL we can upload our file to by using the
    # createFileAttachment API mutation. We are making the request against
    # the step's entityId, which is how files are associated to objects in ion
    attachment_data = {
        'input': {
            'entityId': first_step['entityId'],
            'filename': os.path.basename(file_path)
            }
        }
    upload_request = api.request({
        'query': queries.CREATE_FILE_ATTACHMENT,
        'variables': attachment_data
    })
    url = upload_request['uploadUrl']

    # Now, let's upload the file!
    r = requests.put(url, data=open(file_path, 'rb'))
    return r.ok
예제 #60
0
def sploit2(hostname: str) -> list:
    api = Api(hostname)
    username = get_random_string()
    api.sing_up(username, get_random_string(), get_random_string(),
                get_random_string())

    token = api.generate_token()
    flags = []
    for page_n in range(0, 5):
        users_list = api.api_get_users(token, page_n)
        for user in users_list:
            api.add_friend(user["username"])
            r = api.get_user_barks(user["username"])
            if r:
                flags += get_flags(r.text)
        if not users_list:
            break

    return flags