Ejemplo n.º 1
0
def create():
    response.add_header('Access-Control-Allow-Origin', config.get('main', 'url'))
    response.add_header('Access-Control-Allow-Methods', 'POST')
    response.content_type = 'application/json'

    created = datetime.now()
    try:
        jsonBody = loads(request.body.getvalue())
        title = jsonBody.get('inputTitle', 'No title')
        todo = jsonBody.get('inputTodo', 'No content')
    except Exception as e:
        response.status = 500
        return { 'error': str(e) }

    text = dumps({
        'title': title,
        'text': todo,
        'created': created
    }, cls = DateEncoder)

    try:
        db.add_post(title, text)
    except Exception as e:
        response.status = 500
        return { 'error': str(e) }

    return { 'status': 'OK' }
Ejemplo n.º 2
0
def getCourses():
	d = {}
	response.add_header('Access-Control-Allow-Origin', '*')

	result = statements.distinct("statement.context.contextActivities.grouping.definition.extensions.http://lrs&46;learninglocker&46;net/define/extensions/moodle_course.id", 
		{'lrs_id': ObjectId(LRS_ID)}
	)
	for cid in result:
		if (cid == 1): continue # Skip the site
		
		# Pull Course info for this single unit
		innerResult = statements.find({"statement.context.contextActivities.grouping.definition.extensions.http://lrs&46;learninglocker&46;net/define/extensions/moodle_course.id": cid}).limit(1)
		for row in innerResult:
			groupNode = row['statement']['context']['contextActivities']['grouping']
			for n in groupNode:
				# Break if needed
				if cid in d: break

				interestNode = n['definition']['extensions']
				if 'http://lrs&46;learninglocker&46;net/define/extensions/moodle_course' in interestNode:
					if interestNode['http://lrs&46;learninglocker&46;net/define/extensions/moodle_course']['type'] == 'course':
						d[cid] = interestNode['http://lrs&46;learninglocker&46;net/define/extensions/moodle_course']['shortname']
						break

	response.content_type = 'application/json'
	return dumps(d)
Ejemplo n.º 3
0
	def RedirectUser(self, strPostData):
		if bottle == None:
			return
		response.status = 303
		response.set_header('Location', "{0}?{1}".format(self._provider,strPostData ))	
		response.add_header('Content-Type', 'application/x-www-form-urlencoded')
		return response
Ejemplo n.º 4
0
def noCacheStaticFileReponse(file):
    response.add_header('Cache-Control', 'no-cache')
    response.add_header('Cache-Control', 'no-store')
    fileHandle = open(webRoot + '\\' + file)
    returnValue = fileHandle.read()
    fileHandle.close()
    return returnValue
Ejemplo n.º 5
0
def index():

    auth = AWS4Auth(config.aws_service_credentials.access_key, config.aws_service_credentials.secret_key, config.aws_service_region, config.aws_service_name)
    endpoint = config.aws_service_protocol + "://" + config.aws_service_endpoint + request.path + "?" + request.query_string
    proxy_req_header = {}
    for header in request.headers:
        if header.lower() in PROXY_REQ_HEADERS_WHITELIST:
            proxy_req_header[header] = request.headers[header]

    if request.method == "HEAD":
        requests_response = requests.head(endpoint, auth=auth, headers=proxy_req_header)
    elif request.method == "GET":
        requests_response = requests.get(endpoint, auth=auth, headers=proxy_req_header)
    elif request.method == "POST":
        proxy_req_body = request.body.getvalue()
        requests_response = requests.post(
            endpoint,
            auth=auth,
            data=proxy_req_body,
            headers=proxy_req_header)
    elif request.method == "PUT":
        proxy_req_body = request.body.getvalue()
        requests_response = requests.put(
            endpoint,
            auth=auth,
            data=proxy_req_body,
            headers=proxy_req_header)
    else:
        logging.error("Method not allowed")
    response.body = requests_response.content
    for header in requests_response.headers:
        if not header.lower() in PROXY_RESP_HEADERS_BLACKLIST:
            response.add_header(header, requests_response.headers[header])
    return response
Ejemplo n.º 6
0
def index():
    data = {}
    data1 = {}
    data2 = {}
    list = []
    query = str("SELECT * FROM current_price_data ORDER BY stock_id;")
    conn = pymssql.connect(server='THUNSERV', user='sa', password='Password1', database='MarketData')
    cursor = conn.cursor()
    cursor.execute(query)
    row = cursor.fetchone()
    while row:
        data["name"] = row[5].rstrip()
        data["type"] = str(row[6]).rstrip()
        data1["price"] = row[1]
        data1["datetime"] = str(row[2])
        data1["delta"] = str(row[7])
        data1["pricechange"] = str(row[8])
        data1["stock_id"] = str(row[0]).rstrip()
        data["data"] = data1
        data1 = {}
        list.append(data)
        data = {}
        row = cursor.fetchone()
    data2["stocklist"] = list
    jsonString = json.dumps(data2)
    response.content_type = 'application/json'
    jsonhash = jsonString.encode('utf-8')
    hashed = hmac.new(key, jsonhash, sha1)
    response.add_header('Authentication', 'hmac: ' + base64.b64encode(hashed.digest()).decode('utf-8'))
    return jsonString
Ejemplo n.º 7
0
def list(id=None):
    response.add_header('Access-Control-Allow-Origin', config.get('main', 'url'))
    response.add_header('Access-Control-Allow-Methods', 'GET')
    response.content_type = 'application/json'

    # Make a list of items to respond with
    response_list = []
    try:
        for (item_id, item_data) in db:
            if id is not None and item_id != id:
                continue
            todo_dict = loads(item_data)
            todo_dict.update({
                'id': item_id
            })
            response_list.append(todo_dict)
    except Exception as e:
        response.status = 500
        return { 'error': str(e) }

    # Return 404 if the list is empty
    if not len(response_list):
        response.status = 404
        return { 'error': 'Not found' }

    # Return JSON data of the list, use the DateEncoder for datetime fields
    return dumps(response_list, cls = DateEncoder)
Ejemplo n.º 8
0
def index():
	reqID = request.headers.get('Id')
	print "req: "+str(reqID)
	response.add_header('RID', reqID)
	questionList = db.getQuestionList(20)
	print questionList
	return template("index.tpl",name="dario",questionList=questionList)
Ejemplo n.º 9
0
def index():
    data = {}
    data1 = {}
    data2 = {}
    list = []
    list2 = []
    param = str(request.query['stock'])
    query = str("SELECT * FROM daily_price_data WHERE stock_id= %s ORDER BY datetime;" %param)
    conn = pymssql.connect(server='THUNSERV', user='sa', password='Password1', database='MarketData')
    cursor = conn.cursor()
    cursor.execute(query)
    row = cursor.fetchone()
    data["name"] = row[5].rstrip()
    data1["stock_id"] = str(row[0]).rstrip()
    while row:
        data2["price"] = row[1]
        data2["datetime"] = str(row[2])
        list2.append(data2)
        data2 = {}
        row = cursor.fetchone()
    data1["pricelist"] = list2
    data["data"] = data1
    jsonString = json.dumps(data)
    response.content_type = 'application/json'
    jsonhash = jsonString.encode('utf-8')
    hashed = hmac.new(key, jsonhash, sha1)
    response.add_header('Authentication', 'hmac: ' + base64.b64encode(hashed.digest()).decode('utf-8'))
    return jsonString
Ejemplo n.º 10
0
def new():
    cipher = request.POST.get( "cipher" ).strip()
    days = int( request.POST.get( "days" ).strip() )
    myiponly = request.POST.get( "myiponly" )
    
    if len( cipher ) < 1 or len( cipher ) > 8192 \
       or days < 1 or days > 30:
        abort( 400, "invalid options" )
    
    ## generate unique pw_id ..
    pw_id = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(4))
    while Password.get_by_id( pw_id ):
        pw_id = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(4))
    
    expire = datetime.datetime.now() + datetime.timedelta( days = days )
    
    password = Password( id = pw_id,
                         ciphertext = cipher,
                         expire_date = expire )
    
    if myiponly == "true":
        ## only store a salted hash of the IP, for privacy
        ip_salt = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(4))
        password.ip_hash = ip_salt + ":" + hashlib.sha1( ip_salt + os.environ[ "REMOTE_ADDR" ] ).hexdigest()
    
    password.put()
    
    response.add_header( "Access-Control-Allow-Origin", "*" ) # for auditable version + development
    
    return { "pw_id": pw_id }
Ejemplo n.º 11
0
def index():
    data = {}
    data1 = {}
    list = []
    param_stock = str(request.query['stock'])
    param_days = float(request.query['days'])
    param_interval = float(request.query['interval'])
    
    query = str("SELECT * FROM technical_table2 WHERE stock_id= %s ORDER BY datetime;" %param_stock)
    conn = pymssql.connect(server='THUNSERV', user='sa', password='Password1', database='MarketData')
    cursor = conn.cursor()
    cursor.execute(query)
    row = cursor.fetchone()
    while row:
        data["metric"] = "52 Week High Low"
        data["stock_id"] = str(row[2]).rstrip()
        data1["high_52"] = row[6]
        data1["low_52"] = row[7]
        data1["datetime"] = str(row[1])
        list.append(data1)
        data1 = {}
        row = cursor.fetchone()
    data["valuelist"] = list
    jsonString = json.dumps(data)
    response.content_type = 'application/json'
    jsonhash = jsonString.encode('utf-8')
    hashed = hmac.new(key, jsonhash, sha1)
    response.add_header('Authentication', 'hmac: ' + base64.b64encode(hashed.digest()).decode('utf-8'))
    return jsonString
Ejemplo n.º 12
0
def attachment(attachment_id):
    session = create_session()
    attachment = session.query(Attachment).get(attachment_id)
    file_data = open(attachment.file_path).read()
    response.content_type = attachment.file_type
    response.add_header('Content-Disposition', 'attachment; filename="{}"'.format(attachment.file_name))
    response.add_header('Content-Length', str(len(file_data)))
    return file_data
Ejemplo n.º 13
0
    def dispatch(cls, db=None, key=None, auth=None, **params):
        """
        Dispatches an incoming request.

        Performs sanity checking on incoming data, creates an instance of this class, and then calls that instance.

        :param db: Database session (form Bottle)
        :param auth: Authentication info (from Bottle)
        :param args: Arguments from Bottle
        :param params: Bottle route parameters
        :return: Result of calling the instance, or appropriate error information.
        """
        try:
            method = bottle.request.method
            if method == 'HEAD':
                method = 'GET'
            allowed_methods = cls.collection_methods() if key is None else cls.item_methods()
            if 'GET' in allowed_methods:
                allowed_methods.add('HEAD')
            if method not in allowed_methods:
                response.add_header('Allow', ", ".join(allowed_methods))
                raise err.RequestNotAllowedError()

            if key is None:
                ref = None
            else:
                ref = cls.manager.from_key(key)

            method = bottle.request.method

            if (
                    method == 'PUT' and cls.treat_put_as_patch and not cls.allow_replace and
                    (ref or not cls.allow_replace_all)
            ):
                method = 'PATCH'

            payload = cls.get_payload(method, ref, params)
            options = cls.get_options(method, payload)
            data = cls.get_data(method, payload, ref, params)

            instance = cls(db, options, auth=auth, method=request.method, ref=ref, data=data, params=params)
            try:
                rv = instance()
            except StopDispatch:
                pass
            except err.APIError as ex:
                db.rollback()
                ex.modify_response(response)
                instance.errors.append(ex)
                return {'errors': instance.errors}
        except err.APIError as ex:
            response.status = ex.status
            return {'errors': [ex]}
        if instance.errors:
            db.rollback()
            response.status = http.client.BAD_REQUEST
            return {'errors': instance.errors}
        return rv
Ejemplo n.º 14
0
def snippetHandler():
    """
    Generates a snippet for an article where the snippet is ideally
    the first block of TEI that matches against the original query.
    This is used in conjunction with AJAX to populate the snippets
    on text search.
    Returns a json dictionary
    """
    query = request.query['query']
    queryLower = query.lower()
    teiUrl = request.query["fsmTeiUrl"]
    r = urllib2.urlopen(teiUrl).read()
    xml = et.fromstring(r)
    text = xml.findall("text")[0] # ignore the header

    def acquireTarget(xmlNode):
        """
        Gets a snippet for a target from the XML
        """
        if xmlNode.text and xmlNode.text.lower().find(queryLower) != -1:
            return xmlNode.text
        temp = None
        for child in xmlNode:
            if not temp:
                temp = acquireTarget(child)
        if xmlNode.tail and xmlNode.tail.lower().find(queryLower) != -1:
            return xmlNode.tail
        return temp

    target = acquireTarget(text)

    response.add_header('content-type', 'application/json')

    if target:
        # use the first match and highlight it

        # use regex to match it so we can ignore case.
        subbedTarget = re.sub(query, "<mark>" + query + "</mark>", target, flags=re.IGNORECASE)
        count = r.lower().count(queryLower) # find number of times query appears in the response
        myResponse = {'snippet':subbedTarget, 'matches':count}
        return json.dumps(myResponse)
    else:
        # there were no pure matches.  Just get something so the user has a snippet
        def acquireEasterEgg(egg):
            """
            Gets the first word block in the TEI text that seems reasonable
            """
            if egg.text and len(egg.text.strip()) > 20: # make sure we don't get something short
                return egg.text
            temp = None
            for chicken in egg:
                if not temp:
                    temp = acquireEasterEgg(chicken)
            return temp

        easterEgg = acquireEasterEgg(text)
        myResponse = {'snippet':easterEgg, 'matches':0}
        return json.dumps(myResponse)
Ejemplo n.º 15
0
def export():
    url = request.forms.get('gURL')
    name = request.forms.get('expName')
    data = urllib2.urlopen(url)

    response.add_header("Content-Disposition", "attachment;filename=%s.csv" % name);
    response.content_type = 'text/csv'

    return data
Ejemplo n.º 16
0
def hold_book(id):
    response_json = """
{
 "message": "Hevonen : kasvatus ja hoito / Chris May ; suomentanut Tuulikki Lahti ; [taiteilija: Ursula Dawson]",
 "ok": true
}
    """
    response.add_header("Content-Type", "application/json")
    return response_json
Ejemplo n.º 17
0
def logout(message = False):
    auth_cookie = request.get_cookie('AUTH_COOKIE')
    logger.debug("logout")
    if auth_cookie:
        logger.debug("remove cookie:"+CONFIG.global_config.cookie_store+auth_cookie)
        rm(authdir+auth_cookie)
    response.status = 200
    response.add_header("Content-type", "application/json")
    response.delete_cookie("AUTH_COOKIE")
    return json.dumps({"result": "success", "login_status": False,"message":message})
Ejemplo n.º 18
0
Archivo: post.py Proyecto: xme/DoFler
def login():
    '''Login function'''
    if auth_login(request):
        response.set_cookie('user', 
            request.forms.get('username'), 
            secret=setting('cookie_key').value,
        )
        response.add_header('Authentication', 'SUCCESS')
    else:
        response.add_header('Authentication', 'FAILURE')
Ejemplo n.º 19
0
def logout():
    """Destroys user session and redirects to home"""
    auth = Auth()
    sid = request.get_cookie('SID')
    if sid:
        auth.kill_session(sid)
        auth.destroy()
        response.delete_cookie('SID')
    response.add_header('Location', '/')
    response.status = 302
Ejemplo n.º 20
0
def quiz_delete(reqid):
   output = None
   res_code =  room.remove(reqid, "quiz")
   if res_code == 200:
      output = {"success" : True}
   else:
      output = {"success" : False}
   
   response.status = res_code  
   response.add_header("Content-Type", "application/json")
   return output    
Ejemplo n.º 21
0
def message_delete(discussion_id,message_id):
   output = None
   print "mess ", message_id , " dsc", discussion_id
   res_code =  room.remove_message(discussion_id, message_id)
   if res_code == 200:
      output = {"success" : True}
   else:
      output = {"success" : False}
   
   response.status = res_code  
   response.add_header("Content-Type", "application/json")
   return output    
Ejemplo n.º 22
0
def get_song_form_handler():
	try:
		uuid = UUID(request.forms.get('uuid').strip())
		data = get_song(musicbox_location, musicbox_port, uuid)
		if not data:
			raise Exception('Musicbox error')
		response.content_type = "audio/ogg"
		response.add_header('Content-Disposition', 'attachment; filename=%s.ogg;' % str(uuid))
		return data
	except Exception as e:
		print(e)
		return fail_page
Ejemplo n.º 23
0
def user_add():
   output = None
   result = room.insert(request.json, "user")
   
   if result["res_code"] == 201:
      output = {"success" : True, "id":result["id"]}
   else:
      output = {"success" : False}
      
   response.status = result["res_code"]    
   response.add_header("Content-Type", "application/json")   
   return output
Ejemplo n.º 24
0
def user_add():
    print "Here"
    output = None
    result = Storage().insert(request.json)
    print result
    if result["res_code"] == 200:
      output = {"success" : True, "id":result["id"]}
    else:
      output = {"success" : False}
    response.status = result["res_code"]    
    response.add_header("Content-Type", "application/json")   
    return output
Ejemplo n.º 25
0
def excel_download(entity_id):
    """Download the file as Excel."""

    finvis.aaa.require(fail_redirect="/login")

    entity = Entity.objects(id=entity_id)[0]

    response.content_type = 'application/vnd.ms-excel'
    response.add_header('Content-Disposition',
                        'attachment; filename="' + entity.name + '.xls"')

    return excel.export_excel(entity)
Ejemplo n.º 26
0
def user_edit(email):
   output = None
   res_code = room.update(request.json, email, "user")
   if res_code == 200 or res_code == 201:
         output = {"success" : True}
   else:
         output = {"success" : False}
         
   response.status = res_code
   
   response.add_header("Content-Type", "application/json")
   return output  
Ejemplo n.º 27
0
def course_edit(course_id):
   output = None
   res_code = room.update(request.json,course_id, "course")
   
   if res_code == 200:
      output = {"success" : True}
   else:
      output = {"success" : False}
           
   response.status = res_code
   response.add_header("Content-Type", "application/json")
   return output  
Ejemplo n.º 28
0
def quiz_list():
   resCode = 200
   output = room.list("quiz") 
   if output == None :
      resCode = 500
      output = {"success" : False}
   else:
      resCode = 200
         
   response.status = resCode    
   response.add_header("Content-Type", "application/json")
   return output 
Ejemplo n.º 29
0
def quiz_edit(quiz_id):
 
   res_code = room.update(request.json,quiz_id, "quiz")
   
   if res_code == 200:
      output = {"success" : True}
   else:
      output = {"success" : False}
           
   response.status = res_code
   response.add_header("Content-Type", "application/json")
   return output  
Ejemplo n.º 30
0
def returnSessionViaMax(requestId):
    global mapRequestToReturnURL
    P3Auth.LogActivity.logDebugInfo("return ID:" + repr(requestId))

    P3Auth.LogActivity.logPageTurn("nosession", "ReturnMaxLoginPage")

    ticket = request.query["ticket"]
    P3Auth.LogActivity.logDebugInfo("MAX AUTHENTICATED ticket :" + ticket)

    amendedReturnURL = CAS_CREATE_SESSION_IF_AUTHENTICATED + "/" + repr(requestId)

    status, id, cookie = P3Auth.pycas.check_authenticated_p(
        CAS_LEVEL_OF_ASSURANCE_PREDICATE,
        ticket,
        CAS_SERVER,
        amendedReturnURL,
        lifetime=None,
        secure=1,
        protocol=2,
        path="/",
        opt="",
    )
    maxAuthenticatedProperly = status == P3Auth.pycas.CAS_OK

    P3Auth.LogActivity.logDebugInfo("MAX AUTHENTICATED WITH ID:" + id)

    P3Auth.LogActivity.logDebugInfo("ReturnSessionViaMax authenticated :" + repr(maxAuthenticatedProperly))
    if maxAuthenticatedProperly:
        sendTokensBackTo = mapRequestToReturnURL[requestId]
        response.status = 303
        domain, path = urlparse.urlparse(CAS_RETURN_SERVICE_URL)[1:3]
        secure = 1
        setCookieCommand = P3Auth.pycas.make_pycas_cookie("gateway", domain, path, secure)
        strip = setCookieCommand[12:]
        # We will set this cookie to make it easier for the user
        # to avoid multiple logins---but technically, this is not
        # what is being used and the user, who is probably using the API,
        # will want to ignore this.
        response.set_header("Set-Cookie", strip)
        ses_id = P3Auth.auth.create_session_id()
        acsrf = P3Auth.auth.get_acsrf(ses_id)
        response.add_header("Location", sendTokensBackTo + "?p3session_id=" + ses_id + "&p3acsrf=" + acsrf)
        return "You will be redirected." + strip + sendTokensBackTo
    else:
        P3Auth.LogActivity.logBadCredentials("Failed to Authenticate with Max")
        return template(
            "Login",
            message="Improper Credentials.",
            footer_html=FOOTER_HTML,
            extra_login_methods=EXTRA_LOGIN_METHODS,
            goog_anal_script=GoogleAnalyticsInclusionScript,
        )