Exemplo n.º 1
0
def note_post(note_name):
    """
    Overwrite note `note_name` with content from `note_content` param.

    If `last_version` param is present, check that
    the note to be overwrited is on the same version on the client
    and the server. `last_version` must be a date in ISO 8601 format.
    """
    client_mtime_string = request.forms.get('last_version')
    note = notes.get_note(note_name, meta_only=True)
    if client_mtime_string and note:
        client_mtime = arrow.get(client_mtime_string)
        server_mtime = note['mtime']
        delta = abs(client_mtime - server_mtime).total_seconds()
        if delta < 10:
            notes.put_content(note_name, request.forms.note_content)
        else:
            response.status = "409 Conflict"
    else:
        notes.put_content(note_name, request.forms.note_content)

    current_mtime = notes.get_note(note_name, meta_only=True)['mtime']
    response.add_header(
        'Last-Modified',
        format_date_time(current_mtime.timestamp)
    )
Exemplo n.º 2
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)
Exemplo n.º 3
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='******', password='******', 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
Exemplo n.º 4
0
def onGetPartyRank(redis, session):
    """
        查看竞技场排行榜
    """
    response.add_header('Access-Control-Allow-Origin', '*')
    sid = request.GET.get('sid', '').strip()
    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    userTable = getUserByAccount(redis, account)
    if not redis.exists(userTable):
        return {'code': -5, 'msg': '该用户不存在'}
    picUrl, gender, groupId, isVolntExitGroup, maxScore, baseScore = \
        redis.hmget(userTable, ('headImgUrl', 'sex', 'parentAg', 'isVolntExitGroup', 'maxScore', 'baseScore'))
    if not groupId:
        return {'code': -7, 'msg': '您已被移出公会,请重新加入公会'}

    sortby = request.GET.get('sort', 'day').strip()
    limit = request.GET.get('limit', '10').strip()
    limit = int(limit)
    data = get_party_rank(
        redis,
        groupId,
        account,
        sortby,
        limit,
    )

    log_debug('*****************88888888888888888888888 {0}'.format(data))
    return {'code': 0, 'msg': '', 'data': data}
Exemplo n.º 5
0
def do_upload():
    worksheet = request.forms.get('worksheet')
    id_column = request.forms.get('id_column')
    outcome_column = request.forms.get('outcome_column')
    upload = request.files.get('upload')
    name, ext = os.path.splitext(upload.filename)
    if ext not in (
            '.xlsx',
            '.xls',
    ):
        return ('Empty' if not ext else ext) + \
        ' file extension not allowed. Only .xlsx and .xls are supported.'
    new_name = name + '.anon' + ext

    dfs = pd.read_excel(upload.file, sheet_name=None)

    excel_df = dfs[worksheet]

    result = anonyxel(excel_df, worksheet, id_column, outcome_column)

    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')

    result.to_excel(writer, sheet_name='Anonymized_DATA', index=False)

    writer.save()
    response.content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    attch_str = 'attachment; filename=' + new_name
    response.add_header('Content-Disposition', attch_str)
    return output.getvalue()
Exemplo n.º 6
0
def overloaded_error():
    """Immediate default response to an overloaded error."""
    response.add_header("Content-Type", "application/json")
    response_content = {
        "text": messages.OVERLOADED_ERROR.format(get_support_channel_id()),
    }
    return json.dumps(response_content, ensure_ascii=False).encode("utf-8")
Exemplo n.º 7
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)
Exemplo n.º 8
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='******', password='******', 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
Exemplo n.º 9
0
def do_Refresh(redis, session):
    """
    刷新接口
    """
    response.add_header('Access-Control-Allow-Origin', '*')
    curTime = datetime.now()
    sid = request.forms.get('sid', '').strip()
    SessionTable = FORMAT_USER_HALL_SESSION % (sid)
    account = redis.hget(SessionTable, 'account')
    account2user_table = FORMAT_ACCOUNT2USER_TABLE % (account)
    userTable = redis.get(account2user_table)
    roomCard, groupId = redis.hmget(userTable, ('roomCard', 'parentAg'))
    agentOwnGame = AGENT_OWN_GAME % (groupId)
    gamesSet = redis.smemerbers(agentOwnGame)
    gameInfo = {}
    for gameId in gamesSet:
        gameTable = GAME_TABLE % (gameId)
        if not redis.exists(gameTable):
            return {'code': -1}
        name, webTag, version = redis.hmget(gameTable,
                                            ('name', 'web_tag', 'version'))
        gameInfo[gameId] = {
            'id': gameId,
            'name': name,
            'web_tag': webTag,
            'version': version
        }
    return {
        'code': 0,
        'userInfo': {
            'roomCard': roomCard
        },
        'gameInfo': gameInfo
    }
Exemplo n.º 10
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' }
Exemplo n.º 11
0
def do_joinGroup(redis, session):
    """
    加入公会接口
    """
    response.add_header('Access-Control-Allow-Origin', '*')
    curTime = datetime.now()
    sid = request.forms.get('sid', '').strip()
    groupId = request.forms.get('groupId', '').strip()

    #print
    print '[%s][joinGroup][info] sid[%s] groupId[%s] sid[%s]' % (curTime,
                                                                 groupId, sid)

    adminTable = AGENT_TABLE % (groupId)
    SessionTable = FORMAT_USER_HALL_SESSION % (sid)
    account = redis.hget(SessionTable, 'account')
    account2user_table = FORMAT_ACCOUNT2USER_TABLE % (account)
    userTable = redis.get(account2user_table)
    id = redis.hget(userTable, 'id')

    if redis.exists(adminTable) and redis.exists(userTable):
        #如果存在,绑定
        pipe = redis.pipeline()
        pipe.sadd(FORMAT_ADMIN_ACCOUNT_MEMBER_TABLE % ('CHNWX'), id)  #上线代理需要获得
        pipe.hset(userTable, {'parentAg': groupId})
        pipe.execute()
        return {'code': 0}
    else:
        return {'code': -1}
Exemplo n.º 12
0
def create(db):
    product = request.json.get('product')
    origin = request.json.get('origin')
    best_before_date = request.json.get('best_before_date')
    amount = request.json.get('amount')
    image = request.json.get('image')

    if (product and origin and best_before_date and amount and image):
        db.execute(
            'INSERT INTO supermarket (product, origin, best_before_date, amount, image) VALUES (?, ?, ?, ?, ?)',
            (product, origin, best_before_date, amount, image))
        id = db.lastrowid
        response.status = 201
        response.content_type = 'application/json'
        response_body = {'url': 'http://localhost:8080/retrieve/{}'.format(id)}
    else:
        response.status = 400
        response.content_type = 'application/json'
        response_body = {
            'status': 'Bad Request',
            'message': 'You are missing elements in your request.'
        }

    response.add_header('Access-Control-Allow-Origin', '*')
    response.add_header('Allow', 'POST, HEAD')
    response.body = json.dumps(response_body)
    return response
Exemplo n.º 13
0
def block(block_hash=''):
    if len(block_hash) != LENGTH_CHECK:
        return "no block_hash "
    block_hash = rpc_connection.getblock(block_hash)
    block_hash = simplejson.dumps(block_hash, cls=DecimalJSONEncoder)
    response.add_header("Access-Control-Allow-Origin", "*")
    return block_hash
Exemplo n.º 14
0
def sendlicensetoaddress(sendlicensetoaddress_addr='',
                         sendlicensetoaddress_color=''):
    sendlicensetoaddress = rpc_connection.sendlicensetoaddress(
        str(sendlicensetoaddress_addr), int(sendlicensetoaddress_color),
        license_comment)
    response.add_header("Access-Control-Allow-Origin", "*")
    return {"tx_id": sendlicensetoaddress}
Exemplo n.º 15
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
Exemplo n.º 16
0
    def insert_spec(namespace, service_name):
        """
        Insert provided specification into the Consul K/V store
        and do rotations of stale specifications per retention value
        """
        response.status = 201

        payload = request.json
        spec_validator(payload)

        service_id = '{:.0f}_{}'.format(time.time() * 10**6, uuid4())
        payload['id'] = service_id
        payload['namespace'] = namespace
        spec_key = '{}/specifications/{}/{}'.format(consul_key_path, namespace,
                                                    service_name)

        for key in [service_id, 'latest']:
            create_kv(consul_host, '{}/{}'.format(spec_key, key), payload)

        response.add_header('Location', '{}/{}'.format(spec_key, service_id))

        # Cleanup
        spec_revs = get_kv(consul_host, spec_key, list_keys=True)
        for p in ['/latest', '/deployed']:
            preserve = spec_key + p
            if preserve in spec_revs:
                spec_revs.remove(preserve)

        stale_revs = sorted(spec_revs)[:-spec_retention]
        delete_kv(consul_host, stale_revs)
Exemplo n.º 17
0
def listdb(entity_type):
    try:
        response.add_header("Allow", "GET, POST, DELETE")
        for valid_type in ['pg', 'mysql']:
            if entity_type == valid_type:
                sql = "SELECT * FROM dblist('%s');" % valid_type
                logger.debug(sql)
                local_db.execute(sql)
                results = local_db.fetchall()
                if results:
                    json_data = {"Result": "success", "type": entity_type}
                    logger.info("JSON: %s" % json_data)
                    json_list = []
                    for result in results:
                        json_str = {
                            "host": result[2],
                            "name": result[0],
                            "user": result[1]
                        }
                        logger.debug(json_str)
                        json_list.append(json_str)
                    json_data.update({"data": json_list})
                    response.status = 200
                    return json_data

        response.status = 404

    except Exception as err:
        logger.critical(str(err))
Exemplo n.º 18
0
def get(pw_id):
    password = Password.get_by_id(pw_id)

    if not password:
        return abort(404)

    if password.expire_date < datetime.datetime.now(
    ):  # delete immediately if expired
        password.key.delete()
        return abort(404)

    if password.ip_hash:
        ## only allow viewing from matching IP if myiponly is set..
        ip_salt, ip_hash = password.ip_hash.split(":", 1)
        if not ip_hash == hashlib.sha1(ip_salt +
                                       os.environ["REMOTE_ADDR"]).hexdigest():
            return abort(404)

    cipher = password.ciphertext

    password.key.delete(
    )  # only return encrypted password for a SINGLE viewing

    response.add_header("Access-Control-Allow-Origin",
                        "https://tkooda.github.io")  # for auditable version

    return {"cipher": cipher}
Exemplo n.º 19
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 }
Exemplo n.º 20
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 }
Exemplo n.º 21
0
def login_action():
    j_header_http = {
        #'Authorization':''
    }

    datosUsuario = {
        'USUARIO': request.POST.user.strip(),
        'CLAVE': request.POST.pwd.strip()
    }

    tpc = TodoPagoConnector(j_header_http, str(request.POST.mode.strip()))
    result = tpc.getCredentials(datosUsuario)
    print(result)

    arrSecurity = str(result["Credentials"]["APIKey"]).split(' ')

    if result["Credentials"]["resultado"]["codigoResultado"] == 0:
        response.set_header(
            'Set-Cookie',
            'merchandid=' + str(result["Credentials"]["merchantId"]))
        response.add_header('Set-Cookie', 'security=' + arrSecurity[1])
        response.add_header('Set-Cookie',
                            'mode=' + str(request.POST.mode.strip()))
        return (
            "<p><strong>getCredentials</strong> correcto.<div></div><a href='/list'>Continuar</a></p>"
        )
    else:
        return ("<p>Error en el login.</p><p>mensajeResultado: </p><pre>" +
                str(result["Credentials"]["resultado"]["mensajeResultado"]) +
                "</pre>")
Exemplo n.º 22
0
def control_group(groupID, action):
    response.set_header('Access-Control-Allow-Origin', '*')
    response.add_header('Access-Control-Allow-Methods',
                        'GET, POST, PUT, OPTIONS, DELETE')
    response.headers['Content-Type'] = 'application/json'
    response.headers['Cache-Control'] = 'no-cache'
    return groupContainer.control_group_doors(groupID, action)
Exemplo n.º 23
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)
Exemplo n.º 24
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
Exemplo n.º 25
0
def drawReward(redis, session):
    response.add_header('Access-Control-Allow-Origin', '*')
    recordId = request.POST.get('recordId', '').strip()
    phone = request.POST.get('phone', '').strip()
    acid = request.POST.get('acid', '').strip()
    name = request.POST.get('realName', '').strip()
    sid =  request.POST.get('sid', '').strip()

    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)

    checkNullFields = [
            {'field':name,'msg':'请输入你的姓名'},
            {'field': phone, 'msg': '请输入你的手机号'},
    ]
    for check in checkNullFields:
        if not check['field']:
            return {'code':1,'msg':check['msg']}


    info = {
        'phone': phone,
        'name': name
    }
    modify_awardees(redis,recordId,acid,info)

    # 从未领取列表中删除
    remove_noreward_awardees(redis,account, acid, recordId)

    return {'code': 0, 'msg': ""}
Exemplo n.º 26
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)
Exemplo n.º 27
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
Exemplo n.º 28
0
def getCourses(courseid, modtype):
    d = {}
    response.add_header('Access-Control-Allow-Origin', '*')

    result = statements.distinct(
        "statement.object.definition.extensions.http://lrs&46;learninglocker&46;net/define/extensions/moodle_module.id",
        {
            'statement.object.definition.extensions.http://lrs&46;learninglocker&46;net/define/extensions/moodle_module.type':
            modtype,
            'statement.context.contextActivities.grouping.definition.extensions.http://lrs&46;learninglocker&46;net/define/extensions/moodle_course.id':
            int(courseid),
            # 'lrs_id': ObjectId(LRS_ID)
        })
    for mid in result:
        if (mid == 1): continue  # Skip the site

        # Pull Course info for this single unit
        innerResult = statements.find({
            "statement.object.definition.extensions.http://lrs&46;learninglocker&46;net/define/extensions/moodle_module.id":
            mid
        }).limit(1)
        for row in innerResult:
            d[mid] = row['statement']['object']['definition']['extensions'][
                'http://lrs&46;learninglocker&46;net/define/extensions/moodle_module'][
                    'name']

    response.content_type = 'application/json'
    return dumps(d)
Exemplo n.º 29
0
    def __call__(self, obj):
        for route_path in self.route_paths:
            allowed_methods = set()

            for meth_name, meth_pointer in obj.__dict__.items():
                if meth_name.lower() in HTTP_METHODS:
                    route_callback = lambda mp=meth_pointer, *args, **kwargs: mp(
                        obj, *args, **kwargs)
                    app.route(route_path,
                              method=meth_name.upper())(route_callback)
                    allowed_methods.add(meth_name.upper())

            # If no user defined method for "OPTIONS",
            # create default
            if 'OPTIONS' not in allowed_methods:
                allowed_methods.add('OPTIONS', )
                app.route(
                    route_path,
                    method='OPTIONS',
                    callback=lambda *args, **kwargs:
                    (response.add_header("Access-Control-Allow-Methods", ', '.
                                         join(allowed_methods)),
                     response.add_header("Access-Control-Allow-Origin", "*"),
                     response.add_header(
                         "Access-Control-Allow-Headers",
                         "x-requested-with, content-type, accept, origin, authorization, x-csrftoken, user-agent, accept-encoding"
                     )))
        return obj
Exemplo n.º 30
0
        def generate_sitemap():
            """The view for generating the sitemap in xml format.
            :return: sitemap in xml format.
            """
            response.add_header('Content-Type', 'application/xml')

            links_for_sitemap = [link for link in app.routes if link.config.get('add_to_sitemap')]

            sitemap_links = []
            for link in links_for_sitemap:
                resource_keys = [item for item in re.findall(r'(<\w+:?\w+>)', link.rule)]

                if resource_keys:
                    result = create_dynamic_link(self.domain, self.site_name, link, resource_keys)
                    sitemap_links.extend(result)
                else:
                    result = create_static_link(self.domain, self.site_name, link)
                    sitemap_links.append(result)

            return jinja2_template('''<?xml version="1.0" encoding="UTF-8"?>
                    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                        {% for url in sitemap_links %}
                        <url>
                            <loc>{{url}}</loc>
                            <changefreq>{{changefreq}}</changefreq>
                            <priority>{{priority}}</priority>
                        </url>
                        {% endfor %}
                    </urlset>
            ''', {'sitemap_links': sitemap_links, 'changefreq': self.changefreq, 'priority': self.priority})
Exemplo n.º 31
0
def index():
    data = {}
    data1 = {}
    data2 = {}
    list = []
    query = str("SELECT * FROM current_price_data ORDER BY stock_id;")
    conn = pymssql.connect(server='THUNSERV', user='******', password='******', 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
Exemplo n.º 32
0
def onGetPartyRule(redis, session):
    """
        查看竞技场页面信息
        玩法规则
    """
    response.add_header('Access-Control-Allow-Origin', '*')
    sid = request.GET.get('sid', '').strip()
    SessionTable, account, uid, verfiySid = getInfoBySid(redis, sid)
    userTable = getUserByAccount(redis, account)
    if not redis.exists(userTable):
        return {'code': -5, 'msg': '该用户不存在'}
    picUrl, gender, groupId, isVolntExitGroup, maxScore, baseScore = \
        redis.hmget(userTable, ('headImgUrl', 'sex', 'parentAg', 'isVolntExitGroup', 'maxScore', 'baseScore'))
    if not groupId:
        return {'code': -7, 'msg': '您已被移出公会,请重新加入公会'}

    timeList = get_party_time(redis)
    timeArr = []
    for item in timeList:
        timeArr.append("{0}~{1}".format(item[0][:5], (item[1] or item[0])[:5]))

    info = {
        'time': timeArr,
        'fee': '1个钻石',
    }
    msg = "竞技场开启时间:\n\n{0}\n\n需要:{1}".format('\n'.join(info['time']),
                                             info['fee'])
    return {'code': 0, 'msg': msg}
Exemplo n.º 33
0
def slack_login():
    code = request.query['code']
    result = requests.get(
        "https://slack.com/api/oauth.access?client_id={0}&client_secret={1}&code={2}&redirect_uri={3}".format(
            client_id,
            client_secret,
            code,
            "{0}/slack/login".format(url)
        )
    )
    slack_token = result.json()['access_token']
    team = result.json()['team_id']

    sc = SlackClient(slack_token)
    result = sc.api_call('users.profile.get')
    if result['ok']:
        email = result['profile']['email']
        users = DbUsers(db)
        if not users.contains(email):
            users.add(email)
            DbUser(db, email).notifications().add(
                team=team,
                token=slack_token,
                profile=json.dumps(result['profile'])
            )
        token = DbSessions(db).add(email)
        response.add_header('Set-Cookie', 'token={0}; Path=/; HttpOnly;'.format(token))
        return redirect('/')
Exemplo n.º 34
0
def getMessionDayList(redis, session):
    """每日任务"""
    response.add_header('Access-Control-Allow-Origin', '*')
    sid = request.forms.get('sid', '').strip()
    # return
    log_debug('********getPartyGoldInfo sid %s'.format(sid))

    return {'code': 0, 'msg': ""}
Exemplo n.º 35
0
def retrieveone_db(db,rownumber):
    db.execute("SELECT name, category, location, date, amount FROM inventory WHERE id=?", rownumber)
    rowRAW=db.fetchone()
    rowJSON=json.dumps(rowRAW)
    response.set_header('content-type', 'application/json')
    response.add_header('Access-Control-Allow-Origin', '*')
    response.add_header('Allow', 'GET, HEAD')
    return rowJSON
Exemplo n.º 36
0
 def RedirectUser(self, strPostData):
     logger.info('Invoked the bottlepy RedirectUser!')
     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
Exemplo n.º 37
0
def retrieve_db(db):
    db.execute("SELECT name, category, location, date, amount FROM inventory")
    names = db.fetchall()
    database = json.dumps(names)
    response.set_header('content-type', 'application/json')
    response.add_header('Access-Control-Allow-Origin', '*')
    response.add_header('Allow', 'GET, HEAD')
    return database
Exemplo n.º 38
0
def piscinas():
    if not check_headers():
        abort(400, "Few headers")
    with open('./alguicultura.json', 'r') as f:
        data = json.load(f)
    out = json.dumps(data['pools'])
    response.add_header("Content-Type", "application/json; charset=UTF-8")
    return out
Exemplo n.º 39
0
def delete_door_from_group(groupID, doorID):
    response.set_header('Access-Control-Allow-Origin', '*')
    response.add_header('Access-Control-Allow-Methods',
                        'GET, POST, PUT, OPTIONS, DELETE')
    response.headers['Content-Type'] = 'text/html'
    response.headers['Cache-Control'] = 'no-cache'
    groupContainer.remove_from_group(groupID, doorID)
    return
Exemplo n.º 40
0
    def default_error_handler(self, res):
        logger.error(messages.SERVER_ERROR.format(res.status_code, res.body))
        if not slackapi.logger_error(
                messages.SERVER_ERROR.format(res.status_code, res.body)):
            logger.warn(messages.SLACK_POST_LOG_FAILED)

        response.add_header("Content-Type", "application/json")
        return json.dumps(dict(message=res.body, status_code=res.status_code))
Exemplo n.º 41
0
def allgroups():
    response.set_header('Access-Control-Allow-Origin', '*')
    response.add_header('Access-Control-Allow-Methods',
                        'GET, POST, PUT, OPTIONS, DELETE')
    response.headers['Content-Type'] = 'application/json'
    response.headers['Cache-Control'] = 'no-cache'
    output = [p.__dict__ for p in groupContainer.groupList]
    return json.dumps(output)
Exemplo n.º 42
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
Exemplo n.º 43
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
Exemplo n.º 44
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)
Exemplo n.º 45
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
Exemplo n.º 46
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
Exemplo n.º 47
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
Exemplo n.º 48
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})
Exemplo n.º 49
0
Arquivo: post.py Projeto: 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')
Exemplo n.º 50
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    
Exemplo n.º 51
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
Exemplo n.º 52
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  
Exemplo n.º 53
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  
Exemplo n.º 54
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)
Exemplo n.º 55
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  
Exemplo n.º 56
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 
Exemplo n.º 57
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    
Exemplo n.º 58
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
Exemplo n.º 59
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
Exemplo n.º 60
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,
        )