Example #1
0
def delete_user(email: str, token: str) -> Dict[Any, Any]:
    """
    Deletes a User

    Parameters
    ----------

    email: str
         Email of User to delete

    token: str
         JWT to authenticate User

    Returns
    -------

    No User with email: {email}
    Invalid token
    Successfully deleted {email}
    Failed to validate Token
    """
    user = Session.query(User).filter(User.email == email).first()
    if not user:
        return response(Status.Failure, f"No User with email: {email}")
    try:
        json = jwt.decode(token, secret, algorithms=["HS256"])
        if json["email"] != email and json["password"] == user.password:
            return response(Status.Error, "Invalid token")
        Session.delete(user)
        Session.commit()
        return response(Status.Success, f"Successfully deleted {email}")
    except jwt.DecodeError:
        return response(Status.Error, "Failed to validate token")
Example #2
0
def login_post():
	content = flask.request.json
	t = userauth.login(content)
	if t:
		return response('OK', 'Login Success.', None)
	else:
		return response('Failed', 'Login Failed.', None)
Example #3
0
def register_post():
	content = flask.request.json
	t = userauth.register(content, 0)
	if t:
		return response('OK', 'Registration Success.', None)
	else:
		return response('Failed', 'Registration Failed.', None)
Example #4
0
def login(email: str, payload: Dict[Any, Any]) -> Dict[Any, Any]:
    """
    Logins in a User

    Parameters
    ----------

    email: str
         Email for User

    payload: Dict[Any, Any]
         Payload sent as {"password": "******"}

    Returns
    -------

    No User Exists or
    Password is incorrect or
    JSON Web Token to authenticate user
    """
    user = Session.query(User).filter(User.email == email).first()
    if not user:
        return response(Status.Error, f"No user with email: {email}")
    if not bcrypt.checkpw(payload["password"].encode(), user.password):
        return response(Status.Failure, f"Password is incorrect")
    return response(Status.Success,
                    create_jwt(user.email, user.password, secret).decode())
Example #5
0
def verify_email(email, token, payload) -> Dict[Any, Any]:
    try:
        jwt.decode(token, secret, algorithms=["HS256"])
    except jwt.DecodeError:
        return response(Status.Error, "Failed to validate token")
    user = Session.query(User).filter(User.email == email).first()
    user.verified = True
    Session.commit()
    return response(Status.Success, "Successfully verified email")
Example #6
0
def del_remote(user, project, remote):
	if not all([user, project, remote]):
		return response(user, status=http.HTTP_UNPROCESSABLE_ENTITY)

	# retrieve gitlab project
	res = gitlab.Gitlab().get_project(project)
	if not res.ok:
		return response(user, res)

	result = run_command(user, _cmd_del(project, remote))
	return response(user, status=result['status'], body=result)
Example #7
0
def get_remote(user, project, remote):
	if not all([user, project, remote]):
		return response(user, status=http.HTTP_UNPROCESSABLE_ENTITY)

	remotes = _get_remotes(user, project)
	rem = filter(lambda r: r['name'] == remote, remotes['remotes'])
	if not rem:
		return response(user, status=http.HTTP_NOT_FOUND)
	res = { 'project': project }
	res.update(rem[0])
	return response(user, status=http.HTTP_OK, body=res)
Example #8
0
def plotRaw():
    global pt
    global eta
    global raw

    raw = True

    pt = response('pt')
    plotPtResponse(pt)

    eta = response('eta')
    plotEtaResponse(eta)
Example #9
0
def plotCor():
    global ptcor
    global etacor
    global raw

    raw = False

    ptcor = response('ptcor')
    plotPtResponse(ptcor)

    etacor = response('etacor')
    plotEtaResponse(etacor)
Example #10
0
def plotDREffect():
    global dRon
    global dRoff

    global dRCut

    dRCut = False

    dRoff = response('dRoff')
    plotPtResponse(dRoff)

    dRCut = True

    dRon = response('dRon')
    plotPtResponse(dRon)
Example #11
0
def request_pose():  # Request
    if not request.json:  # or not "button" in request.json:
        abort(400)
    post = {
        "position": request.json["position"],
        "mode": request.json["mode"],
        "vid_length": request.json["vid_length"]
    }
    ip = socket.gethostbyname(socket.gethostname())
    url_settings = "http://" + ip + ":61405/pixelsettings"
    settings = requests.get(url_settings)
    settings = settings.json()[-1]
    response(post)  # action
    posts.append(post)  # see post on website
    return jsonify(posts), 201
 def test_valid_participant_stat_response(self):
     validPlayerStat = [None] * 33
     validPlayerStat[7] = 39
     validPlayerStat[31] = 29
     validPlayerStat[32] = "2018"
     resp = response()
     self.assertEqual(resp.participantResponse(validPlayerStat), 'Player No.29 has 39 Games played in 2018')
Example #13
0
    def parse_message(self, data):
        print 'origin data:' + data
        data = data.rstrip('##')
        new_data = json.loads(data)
        print new_data

        uid = new_data.get("uid")
        print self.uid
        service = new_data.get("service")
        method = new_data.get("method")
        params = new_data.get("params")
        """
        service= 'TestService'
        method= 'testMethod'
        params= {}
        """

        cls = getattr(TestService, service)
        obj = cls()
        func = getattr(obj, method)

        data = func(params)
        req = response(data)
        #print req.dump()
        return req.dump()

        return data
Example #14
0
def _create_application(user, app):
	res = provider.OpenShift(user).add_app(**app._asdict())
	if res.ok:
		print 'Application created: {app.name}-{app.domain}'.format(app=app)
		return res

	raise response(user, res=res)
Example #15
0
def request_pose():  # Request
    if not request.json:  # or not "button" in request.json:
        abort(400)
    post = {
        "position": request.json["position"],
        "mode": request.json["mode"],
        "vid_length": request.json["vid_length"]
    }
    stream = os.popen('ipconfig getifaddr en0')  # gets ip address
    ip = stream.read().rstrip()  # gets rid of newline
    url_settings = "http://" + ip + ":61405/pixelsettings"
    settings = requests.get(url_settings)
    settings = settings.json()[-1]
    response(post)  # action
    posts.append(post)  # see post on website
    return jsonify(posts), 201
Example #16
0
def adminresponce(text):
    text = str(text)
    if '/' in text:
        if '/genadmin ' in str(text):
            n = text.replace('/genadmin ', '')
            if n.isdigit():
                n = int(n)
                generateAdmins(n)
                return u'Токены сгенерированы'
            else:
                return u'Пример команды: /genadmin 3'
        if '/gen' in str(text):
            n = text.replace('/gen ', '')
            if n.isdigit():
                n = int(n)
                generateUsers(n)
                return u'Токены сгенерированы'
            else:
                return u'Пример команды: /gen 3'
        if '/tokens' in str(text):
            return ('\n'.join(getTokens()))
        return u'команды: /gen - сгенерировать токены юзеров \n/genadmin  сгенерировать токены админов \n/tokens - вывести токены \n'
    return response(text)


#print(adminresponce('/gen 3'))
#print(adminresponce('/genadmin 3'))
#print(adminresponce('/tokens'))
#print(adminresponce('/t'))
#print(adminresponce('привет'))
Example #17
0
def _create_gitlab_project(user, proj):
	res = gitlab.Gitlab().add_project(name=proj.name)
	if res.ok:
		print 'Project created:', proj.name
		return res

	raise response(user, res=res)
Example #18
0
def _get_remotes(user, project):
	# garantee ownership
	res = gitlab.Gitlab().get_project(project)
	if not res.ok:
		raise response(user, res)

	return run_command(user, _cmd_list(project))
Example #19
0
def clone_remote(user, project_name, application):
	_install_getup_key(user)
	mesg = 'setup application project repository: app={app.name}-{app.domain} project={project}'.format(app=application, project=project_name)
	print mesg
	res = _create_remote(user, project_name, application.domain, application.name, 'clone')
	print '{mesg} (end with {status})'.format(mesg=mesg, status=res.get('status'))
	return response(user, status=res['status'], body=res)
Example #20
0
 def do_single_reponse(self, idx):
     databuff = ""
     data_len = 0
     while True:
         rbuff = self.client.recv(FSIZE)
         magic_code, resp_code, id, reverse, length = unpack(FMT, rbuff)
         self.client.logger.debug("return resp_code[%d] length[%d],id[%d]" %
                                  (resp_code, length, id))
         if id != self.ids[idx]:
             raise response_exception("id is error!")
         rbuff = self.client.recv(length)
         if 400 <= resp_code < 600:
             rpos = 0
             error_code, = unpack('!L', rbuff[rpos:rpos + 4])
             if resp_code == CLIENT_STATUS_DB_ERROR:
                 raise response_exception("mysql return code [%d]" %
                                          error_code)
             if error_code < len(ERROR_MSG):
                 raise response_exception(ERROR_MSG[error_code])
             else:
                 raise response_exception("unkown error code [%d]" %
                                          error_code)
         elif resp_code == CLIENT_STATUS_ACCEPT:
             databuff += rbuff
             data_len += length
         elif resp_code == CLIENT_STATUS_OK:
             databuff += rbuff
             data_len += length
             self.client.logger.debug("return data_length[%d]" % data_len)
             return response(databuff, data_len).parse()
         else:
             raise response_exception("unknown response code [%d]" %
                                      resp_code)
Example #21
0
def add_remote(user, project_name, application):
	_install_getup_key(user)
	mesg = 'attaching repository into application: app={app.name}-{app.domain} project={project}'.format(app=application, project=project_name)
	print mesg
	res = _create_remote(user, project_name, application.domain, application.name, 'add')
	print '{mesg} (end with {status})'.format(mesg=mesg, status=res.get('status'))
	return response(user, status=res.get('status'), body=res)
def SearchRestaurant(conn, rName):
    sql = """select Restaurant.rID, rName, rAddr, rPic, tableType, time17, time18, time19, time20
             from Restaurant natural join Available
             where rName = '%s'""" % (rName)
    search = conn.cursor()
    search.execute(sql)
    result = search.fetchall()

    res = response()

    if not len(result):
        res.StatusCode = '404'
        res.ReasonPhrase = 'Restaurant ID Not Found'
    else:
        res.StatusCode = '200'
        res.ReasonPhrase = 'Search OK'


    dict = {'rID':'', 'rName':'', 'rAddr':'', 'rPic':'', 'tableInfo': []}
    dict['rID'] = result[0][0]
    dict['rName'] = result[0][1]
    dict['rAddr'] = result[0][2]
    dict['rPic'] = result[0][3]
    for rInfo in result:
        tmp = []
        tmp.append(rInfo[5])
        tmp.append(rInfo[6])
        tmp.append(rInfo[7])
        tmp.append(rInfo[8])
        dict['tableInfo'].append(tmp)

    res.Data = dict

    return res
 def do_single_reponse(self,idx):
     databuff = ""
     data_len = 0
     while True:
         rbuff = self.client.recv(FSIZE)
         magic_code, resp_code, id, reverse, length = unpack(FMT, rbuff)
         self.client.logger.debug("return resp_code[%d] length[%d],id[%d]" % (resp_code, length, id))
         if id != self.ids[idx]:
             raise response_exception("id is error!")
         rbuff = self.client.recv(length)
         if 400 <= resp_code < 600:
             rpos = 0
             error_code, = unpack('!L', rbuff[rpos:rpos + 4])
             if resp_code == CLIENT_STATUS_DB_ERROR:
                 raise response_exception("mysql return code [%d]" % error_code)
             if error_code < len(ERROR_MSG):
                 raise response_exception(ERROR_MSG[error_code])
             else:
                 raise response_exception("unkown error code [%d]" % error_code)
         elif resp_code == CLIENT_STATUS_ACCEPT:
             databuff += rbuff
             data_len += length
         elif resp_code == CLIENT_STATUS_OK:
             databuff += rbuff
             data_len += length
             self.client.logger.debug("return data_length[%d]" % data_len)
             return response(databuff, data_len).parse()
         else:
             raise response_exception("unknown response code [%d]" % resp_code)
Example #24
0
 def get(self, user=None):
     return response.response(
         response.STATUS,
         {'status': self.toastStatus(),
          'count': int(self.toastCount()),
          'last': self.modified(),
          'started': self.started()
         }).json()
Example #25
0
def _create_remote(user, project, domain, application, command='add'):
	if not all([user, project, domain, application]):
		raise response(user, status=http.HTTP_UNPROCESSABLE_ENTITY)

	# retrieve openshift app
	res = provider.OpenShift(user).get_app(domain=domain, name=application)
	if not res.ok:
		raise response(user, res)
	app_data = res.json['data']

	# retrieve gitlab project
	res = gitlab.Gitlab().get_project(project)
	if not res.ok:
		raise response(user, res)

	remote = '{app[name]}-{app[domain_id]}'.format(app=app_data)
	git_url = '{app[ssh_url]}/~/git/{app[name]}.git/'.format(app=app_data)
	return run_command(user, _cmd_create(project, remote, git_url, command))
Example #26
0
def register_TBD_user_post():
	content = {}
	content["email"] = "TBD" + "@contestify.com"
	content["password"] = "******"
	content["firstName"] = ""
	content["lastName"] = "TBD"
	t = userauth.register(content, 2)
	
	return response('OK', 'TBD Registration Success.', None)
Example #27
0
def get():
    # result in form of array representing probablistic classes
    #resultClassify = res.classify(request.json["sentence"]) 
    resultResponse = res.response(request.json["sentence"])
    responseDict = {} 
    #for r in resultClassify:
        #responseDict[r[0]] = str(r[1])
    responseDict["sentence"] = resultResponse
    print(responseDict)
    return jsonify ( responseDict )
Example #28
0
def sentiment_analysis():
    """method that outputs a response"""
    if request.method == 'GET':
        text = request.args.get('text')
        return response(text)
    return make_response(
        jsonify({
            'error': 'sorry! unable to parse',
            'status_code': 500
        }), 500)
Example #29
0
def get_user(email: str) -> Dict[Any, Any]:
    """
    Gets a User by Email

    Parameters
    ----------

    email: str
         Email to query for

    Returns
    -------

    User information including public_key, bio, and handle
    """
    user = Session.query(User).filter(User.email == email).first()
    if not user:
        return response(Status.Failure, f"No Users with email: {email}")
    return response(Status.Success, user.to_json())
Example #30
0
def register_empty_users_post():
	for i in range(int(128)):
		content = {}
		content["email"] = "Player" + str(i) + "@contestify.com"
		content["password"] = "******"
		content["firstName"] = "Player"
		content["lastName"] = str(i)
		t = userauth.register(content, 1)
	
	return response('OK', 'Batch Registration Success.', None)
Example #31
0
def run_command(user, cmd):
	try:
		cmd_result = gitlab.SSHClient().run(cmd)
		output = json.loads(cmd_result.stdout)

		if 'status' not in output:
			raise response(user, status=http.HTTP_INTERNAL_SERVER_ERROR, body="Invalid result from command: missing 'status' field")
		if 200 > output['status'] >= 400:
			raise response(user, status=output['status'], body=output.get('data'))

		return output
	except ValueError, ex:
		print 'Failure parsing command output: {ex}'.format(ex=ex)
		print '--- stdout'
		print cmd_result.stdout
		print '--- stderr'
		print cmd_result.stderr
		print '---'
		raise response(user, status=http.HTTP_INTERNAL_SERVER_ERROR, body=str(ex))
Example #32
0
def _create_domain(user, app):
	res = provider.OpenShift(user).get_dom(app.domain)
	if res.ok:
		return res

	res = provider.OpenShift(user).add_dom(app.domain)
	if res.ok:
		print 'Domain created:', app.domain
		return res

	raise response(user, res=res)
Example #33
0
def main():
    #set up the request
    user_input = input("Request: ")
    a = re.split(' +', user_input)

    r = request(a[0], a[1])

    #send the request, assign it to response
    req = send_socket(r.toString())
    resp = response(req.decode('UTF-8'))
    print(resp.toString())
Example #34
0
def resend_email_verificaiton(email: str, token: str,
                              payload: Dict[Any, Any]) -> Dict[Any, Any]:
    """
    Resends the Verification email

    Parameters
    ----------

    email: str
         User's email

    token: str
         JWT Token to verify the user

    payload: Dict[Any, Any]
         Empty payload

    Returns
    -------

    Dict[Any, Any]
         No User with email: {email}
         Invalid token
         Verification email sent
         Invalid Token
    """
    user = Session.query(User).filter(User.email == email).first()
    if not user:
        return response(Status.Error, f"No User with email: {email}")
    try:
        json = jwt.decode(token, secret, algorithms=["HS256"])
        if json["email"] != email and json["password"] == user.password:
            return response(Status.Error, "Invalid token")
        send_verification_email(
            email,
            rest.get_url(),
            create_jwt(user.email, user.password, secret, 24 * 7).decode(),
        )
        return response(Status.Success, "Verification email sent")
    except jwt.DecodeError:
        return response(Status.Error, "Invalid Token")
Example #35
0
def create_project(user, project):
	start_time = datetime.utcnow().ctime()

	report = []
	def add_report(action, description, **kva):
		report.append(dict(action=action, description=description, **kva))

	def set_report_status(res):
		r = report[-1]
		print '{action}: {res.status_code}\n---\n{res.json}\n---'.format(
			action=r['action'], res=res)
		report[-1].update(status=res.status_code, content=res.json)

	try:
		# create openshift domain
		add_report('domain', 'Create openshift domain')
		res = _create_domain(user, project.application)
		set_report_status(res)

		# create gitlab project
		add_report('project', 'Create project repository')
		res = _create_gitlab_project(user, project)
		set_report_status(res)

		# create openshift app
		add_report('application', 'Create openshift application')
		res = _create_application(user, project.application)
		set_report_status(res)

		# clone and setup default remote
		add_report('clone', 'Clone and setup application code into project repository')
		res = _clone_app_into_repo(user, project.name, project.application)
		set_report_status(res)

		# create dev openshift app is applicable
		if project.dev_application:
			add_report('dev_application', 'Create openshift dev_application')
			res = _create_application(user, project.dev_application)
			set_report_status(res)

			dns_register_wildcard_cname('{app.name}-{app.domain}'.format(app=project.dev_application))
			#set_report_status(res)

			# add remote to dev repoitory
			add_report('dev_remote', 'Add dev_application as remote')
			res = add_remote(user, project.name, project.dev_application)
			set_report_status(res)

	except HTTPResponse, ex:
		set_report_status(ex.res)
		add_report('finish', 'Failure creating component ({action})'.format(action=report[-1]['action']), status=str(),
			start_time=start_time, end_time=datetime.utcnow().ctime())
		return response(user, status=ex.status_code, body=report)
Example #36
0
def index(req):
    if not checkSig(req):
        return HttpResponseForbidden()
    if req.method == 'GET':
        return HttpResponse(req.GET.get('echostr', ''))
    req_msg = parseXml(req)
    ret = NULL_RESPONSE

    if req_msg.get('MsgType', '') == 'text':
        ret = response(req_msg.get('Content', ''))

    return HttpResponse(makeTextMsg(req_msg, ret))
Example #37
0
def list_users() -> Dict[Any, Any]:
    """
    Lists all Users by Email

    Returns
    -------

    List[str] of User emails
    """
    users: List[User] = Session.query(User).all()
    users_json: List[Dict[str, str]] = [user.email for user in users]
    return response(Status.Success, users_json)
Example #38
0
    def onProcessRequest(self, request):
        ret = None

        if self.mapOperation.has_key(request.method):
            for pathReg, handle in self.mapOperation[request.method].items():
                params = self.__matchPath(pathReg, request.path)
                if params:
                    ret = handle(**params)
                    if not isinstance(ret, response):
                        ret = response(200, str(ret))

        return ret
Example #39
0
def index(req):
    if not checkSig(req):
        return HttpResponseForbidden()
    if req.method == 'GET':
        return HttpResponse(req.GET.get('echostr', ''))
    req_msg = parseXml(req)
    ret = 'Null Response.'

    if req_msg.get('MsgType', '') == 'text':
        ret = response(req_msg.get('Content', ''))

    return HttpResponse(makeTextMsg(req_msg, ret))
Example #40
0
def update_user(email: str, token: str, payload: Dict[Any,
                                                      Any]) -> Dict[Any, Any]:
    """
    Updates a User

    Parameters
    ----------

    email: str
         Email to query for

    jwt: str
         JSON Web Token to validate User to permit updating

    payload: Dict[Any, Any]
         Payload of the form
         {
          "password": "******",
          "handle": "handle_here",
          "public_key": "public_key_here"
          "bio": "bio_here"
         }

    Returns
    -------

    No User with email: {email}
    Updated User information
    """
    user = Session.query(User).filter(User.email == email)
    if not user:
        return response(Status.Failure, f"No User with email: {email}")
    try:
        jwt.decode(token, secret, algorithms=["HS256"])
    except jwt.DecodeError:
        return response(Status.Error, "Failed to validate token")
    user.update(payload)
    Session.commit()
    return response(Status.Success, user.to_json())
Example #41
0
 def get_response(self):
     intent = self.intent
     slot_dictionary = self.slot_dictionary
     response_dictionary = None
     if intent == 'TeamIntent':
         response_dictionary = self.interpret_team_intent(intent, slot_dictionary)
     elif intent == 'TeamParticipantIntent':
         response_dictionary = self.interpret_team_participant_intent(intent, slot_dictionary)
     elif intent == 'ScheduleIntent':
         response_dictionary = self.interpret_schedule_intent(intent, slot_dictionary)
     else:
         response_dictionary = None
     return response(response_dictionary).generate_response()
Example #42
0
    def getAllResponsePatternId(self):
        """
        Get all response for patternid
        :return:
        """
        c = con()
        #uma lista de tuplas [(id,response,patternId),...]
        aux = c.getAllResponsePattern(self.patternId)
        # temporaria para retornar
        tmp = []
        for rs in aux:
            tmp.append(response(rs))

        return tmp
    def test_valid_schedule_response(self):
        data = []
        gameObj = game(data)
        gameObj.month = "April"
        gameObj.day = 25
        gameObj.opponent_name = "#2 Wooster"
        gameObj.result = "L, 11-6"
        validSchedule = [None] * 3
        validSchedule[1] = gameObj
        validSchedule[2] = "2018"
        resp = response()

        #print(validSchedule)
        self.assertEqual(resp.scheduleResponse(validSchedule), 'CWRU baseball team played #2 Wooster on the 25 of April, and the result was L, 11-6.')
Example #44
0
    def set(self, key=None, toasting=None):
        errors = []
        toasting = toasting.lower()
        js = ''
        if key == None:
            errors.append('Empty key.')

        keyRow = self.db.execute("select * from users where secret = '" + key.upper() + "' limit 1").fetchone();

        if keyRow == None:
            errors.append('Invalid key.')
        else:
            name = keyRow['name']

        if toasting == None:
            errors.append('Empty toasting command.')
        elif toasting != 'on' and toasting != 'off' and toasting != 'reset':
            errors.append('Invalid toasting command.')

        if len(errors) > 0:
            js = response.response(response.ERROR, errors).json()
        else:
            if toasting == 'reset':
                self.db.execute("delete from records")
            else:
                timing = str(time.localtime())
                if toasting == 'on':
                    self.records.insert().execute(user='******', start=timing)
                else:
                    row = self.db.execute(
                        "select rowid from records order by start desc, finish desc limit 1"
                    ).fetchone()
                    id = row['rowid']
                    self.db.execute("update records set finish = '" + str(timing) + "' where rowid = " + str(id))
            js = response.response(response.SUCCESS, {"toasting": toasting, "effective": str(timing)}).json()
        return js
Example #45
0
    def pairing(self):
        url = '%s/login?pairing-guid=%s' % (self.service, self.guid)

        data = urllib2.urlopen( url ).read()
        
        resp = response.response(data)        
        self.sessionid = resp.resp['mlog']['mlid']
    
        confMan.connect( self.dbId, self.sessionid )
    
        print "Got session id", self.sessionid
        self.databases()
        pl = self.playlists()
        self.musicid = pl.library.id
        self.getspeakers()
        
        return resp
Example #46
0
 def _operation( self, command, values, verbose=True, sessionid = True):
     if sessionid:
         if self.sessionid is None:
             self.pairing()
         values['session-id'] = self.sessionid
     
     url = command
     if len(values): url += "?" + _encode(values)
     #if verbose: print url
     print url
     
     headers = { 
         'Viewer-Only-Client': '1', 
         'Connection':'keep-alive', 
         'Accept-Encoding': 'gzip'} 
     
     #    'Accept-Encoding': 'identity', 
     #    'User-agent':'Python-urllib/2.6' } 
     #    'Connection':'close' } 
     
     request = urllib2.Request( url, None, headers )
     
     try:
         resp = urllib2.urlopen(request)
         headers = resp.headers.dict
     
         if 'content-encoding' in headers and headers['content-encoding'] == 'gzip':
             compressedstream = StringIO.StringIO(resp.read())
             gzipper = gzip.GzipFile(fileobj=compressedstream)
             out = gzipper.read()                 
         else:
             out = resp.read()
         if headers['content-type'] != 'image/png':
             
             if verbose: self._decode2( out )
             resp = response.response( out )
             
             return resp.resp
         else:
             return out
     except HTTPError, e:
         print "HTTPError while running query"
         print request.get_full_url()
         print request.headers
         print e
Example #47
0
def _dns_init():
	zone = app.config.dns.zone
	key  = app.config.dns.key

	server = socket.getaddrinfo(app.config.dns.server, app.config.dns.port, socket.SOCK_DGRAM, 0, socket.SOL_UDP)
	if not server:
		raise response(user=None, status=http.HTTP_INTERNAL_SERVER_ERROR, body="Unable to resolve DNS server: {server}:{port}".format(**app.config.dns))
	server = server[0]
	af = server[0]
	addr, port = server[-1][:2]

	return {
		'af': af,
		'addr': addr,
		'port': port,
		'zone': zone,
		'keyring': dns.tsigkeyring.from_text({ zone: key }),
		'keyname': zone,
		'keyalgorithm': dns.tsig.HMAC_MD5,
	}
Example #48
0
    async def SendData(self, data):
        try:
            data += "<EOF>"
            self.encryptionconn.send(data.encode())
            recvdata = await self.RecvData()
            recvdata = recvdata.decode('UTF-8')
            if not recvdata:
                self.connected = False
                return 1

            recvdata = recvdata[:-5]
            jsonobj = json.loads(recvdata)
            if jsonobj['action'] == 'response':
                return response.response(jsonobj["rezultat"][0][0],
                                         jsonobj["rezultat"][1][1])

        except socket.error as e:
            print("Error in sending data. " + str(e))
            self.connected = False
            self.mainsocket.close()
            self.on_connection_lost(self)
            return 1
Example #49
0
    def parse_message(self, data):
        print data
        data = data.rstrip('##')

        obj = ConnectionObj()
        obj.stream = self._stream
        obj.time = 123456789
        Connection.clients[str(self._address[0]) + str(self._address[1])] = obj
        return data

        new_data = json.loads(data)
        print "data:" + data
        print new_data
        self.uid = new_data.get("uid")
        print self.uid
        service = new_data.get("service")
        method = new_data.get("method")
        params = new_data.get("params")
        """
        service= 'TestService'
        method= 'testMethod'
        params= {}
        """
        obj = ConnectionObj()
        obj.stream = self._stream
        obj.time = 123456789
        Connection.clients[str(self.uid) + self._address[1]] = obj
        #print Connection.clients[self.uid].time

        cls = getattr(TestService, service)
        obj = cls()
        func = getattr(obj, method)

        data = func(params)
        req = response(data)
        #print req.dump()
        #return req.dump()

        return data
Example #50
0
def insert_appointment(conn, rid, uid, tableType, startTime, duration):
    res = response()
    cur = conn.cursor()
    find_restTable_sql = """
                        SELECT rID, tableType, time17, time18, time19, time20
                        FROM Available
                        WHERE rid = '%d' AND tableType = '%d'""" % (rid,
                                                                    tableType)
    cur.execute(find_restTable_sql)
    find_restTable_result = cur.fetchall()
    #print(find_restTable_result)

    if (check_remaining(find_restTable_result, startTime, duration) == -1):
        print("no remaining")
        res.StatusCode = '404'
        res.ReasonPhrase = 'no remaining'

    insert_sql = """INSERT INTO Appointment
                    VALUES('%d','%s','%d','%d','%d')""" % (rid, uid, tableType,
                                                           startTime, duration)

    update_remaining_sql = update_remaining(find_restTable_result, rid,
                                            tableType, startTime, duration)
    print(update_remaining_sql)

    try:
        cur.execute(insert_sql)
        cur.execute(update_remaining_sql)
        conn.commit()
        res.StatusCode = '200'
        res.ReasonPhrase = 'successfully inserted'
    except MySQLdb.Error, e:
        conn.rollback()
        for index in range(len(e.args)):
            print "Error %s" % (e.args[index])
        res.StatusCode = '404'
        res.ReasonPhrase = 'fail to insert'
Example #51
0
def post_create(user, domain, application, project, cartridge, scale, dev_gear):
	'''Clone and bind project to application, creating any missing component.
	'''
	scale = bool(scale)
	if not project:
		project = '%s-%s' % (application, domain)

	if dev_gear:
		dev_application = 'dev%s' % application

	checklist = {
		'project': False,
		'domain': False,
		'application': False,
	}

	checklist['project'] = gitlab.Gitlab().get_project(project).status_code == 404
	checklist['domain'] = provider.OpenShift(user).get_dom(name=domain).status_code == 200
	checklist['application']  = provider.OpenShift(user).get_app(domain=domain, name=application).status_code == 404
	if dev_gear:
		checklist['dev-application']  = provider.OpenShift(user).get_app(domain=domain, name=dev_application).status_code == 404

	if checklist['project'] is False or checklist['application'] is False or \
		(dev_gear is True and checklist['dev-application'] is False):
		return response(user, status=http.HTTP_CONFLICT, body=checklist)

	p_app = projects.Application(domain=domain, name=application, cartridge=cartridge, scale=scale, \
		gear_profile=app.config.provider.openshift.default_gear_profile)

	if dev_gear:
		d_app = projects.Application(domain=domain, name=dev_application, cartridge=cartridge, scale=False, \
			gear_profile=app.config.provider.openshift.devel_gear_profile)
	else:
		d_app = False

	return projects.create_project(user, projects.Project(name=project, application=p_app, dev_application=d_app))
Example #52
0
def player_list_put(contest_id):
	content = flask.request.json
	contestmanage.register_player(contest_id = contest_id, user_id = content["userId"])
	return response('OK', '', None)
Example #53
0
def current_user_get():
	t = {}
	t['currentUserId'] = current_user.get_id()
	return response('OK', '', t)
Example #54
0
def upload_match_result(match_id):
    OperationData.increaseContests()
    content = flask.request.json
    contestmanage.upload_match_result(match_id = match_id, contest_id = content["contestId"], score1 = content["score1"], score2 = content["score2"])
    return response('OK', '', None)
Example #55
0
def contest_post():
	content = flask.request.json
	content['adminId'] = current_user.get_id()
	t = contestmanage.new_contest(content)
	return response('OK', 'New Contest Success.', t)
Example #56
0
def graph_get():
	contest_id = flask.request.args.get('id')
	t = contestmanage.get_graph_by_contest_id(contest_id = contest_id)
	return response('OK', '', t)
Example #57
0
def match_get():
	contest_id = flask.request.args.get('id')
	t = contestmanage.get_match_by_id(match_id = contest_id)
	return response('OK', '', t)
Example #58
0
def player_list_get():
	contest_id = flask.request.args.get('id')
	t = contestmanage.get_player_list_by_contest_id(contest_id = contest_id)
	return response('OK', '', t)