當前位置: 首頁>>代碼示例>>Python>>正文


Python response.content_type方法代碼示例

本文整理匯總了Python中bottle.response.content_type方法的典型用法代碼示例。如果您正苦於以下問題:Python response.content_type方法的具體用法?Python response.content_type怎麽用?Python response.content_type使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在bottle.response的用法示例。


在下文中一共展示了response.content_type方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: translate

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def translate(self):
        """
        Processes a translation request.
        """
        translation_request = request_provider(self._style, request)
        logging.debug("REQUEST - " + repr(translation_request))

        translations = self._translator.translate(
            translation_request.segments,
            translation_request.settings
        )
        response_data = {
            'status': TranslationResponse.STATUS_OK,
            'segments': [translation.target_words for translation in translations],
        }
        translation_response = response_provider(self._style, **response_data)
        logging.debug("RESPONSE - " + repr(translation_response))

        response.content_type = translation_response.get_content_type()
        return repr(translation_response) 
開發者ID:EdinburghNLP,項目名稱:nematus,代碼行數:22,代碼來源:server.py

示例2: jsonify

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def jsonify(fn):
    @ft.wraps(fn)
    def inner(*a, **kw):
        response.content_type = 'application/json'
        try:
            data = fn(*a, **kw)
        except HTTPError as e:
            response.status = e.status_code
            data = {'errors': [e.body]}
        except schema.Error as e:
            response.status = 400
            data = {'errors': e.errors, 'schema': e.schema}
        except Exception as e:
            log.exception(e)
            response.status = 500
            data = {'errors': [str(e)]}
        return json.dumps(data or {}, indent=2, ensure_ascii=False)
    return inner 
開發者ID:naspeh,項目名稱:mailur,代碼行數:20,代碼來源:web.py

示例3: report_gpustat

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def report_gpustat():
    """
    Returns the gpustat of this host.
        See `exclude-self` option of `gpuview run`.
    """

    def _date_handler(obj):
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        else:
            raise TypeError(type(obj))

    response.content_type = 'application/json'
    if EXCLUDE_SELF:
        resp = {'error': 'Excluded self!'}
    else:
        resp = core.my_gpustat()
    return json.dumps(resp, default=_date_handler) 
開發者ID:fgaim,項目名稱:gpuview,代碼行數:20,代碼來源:app.py

示例4: get_files

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def get_files(task_id):
    if not task_id.isdigit():
        return HTTPError(code=404, output="The specified ID is invalid")

    files_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "files")
    zip_file = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "files.zip")
        
    with zipfile.ZipFile(zip_file, "w", compression=zipfile.ZIP_DEFLATED) as archive:
        root_len = len(os.path.abspath(files_path))
        for root, dirs, files in os.walk(files_path):
            archive_root = os.path.abspath(root)[root_len:]
            for f in files:
                fullpath = os.path.join(root, f)
                archive_name = os.path.join(archive_root, f)
                archive.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)

    if not os.path.exists(files_path):
        return HTTPError(code=404, output="Files not found")

    response.content_type = "application/zip"
    response.set_header("Content-Disposition", "attachment; filename=cuckoo_task_%s(not_encrypted).zip" % (task_id))
    return open(zip_file, "rb").read() 
開發者ID:davidoren,項目名稱:CuckooSploit,代碼行數:24,代碼來源:web.py

示例5: task_screenshots

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def task_screenshots(task=0, screenshot=None):
    folder_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(task), "shots")

    if os.path.exists(folder_path):
        if screenshot:
            screenshot_name = "{0}.jpg".format(screenshot)
            screenshot_path = os.path.join(folder_path, screenshot_name)
            if os.path.exists(screenshot_path):
                # TODO: Add content disposition.
                response.content_type = "image/jpeg"
                return open(screenshot_path, "rb").read()
            else:
                return HTTPError(404, screenshot_path)
        else:
            zip_data = StringIO()
            with ZipFile(zip_data, "w", ZIP_STORED) as zip_file:
                for shot_name in os.listdir(folder_path):
                    zip_file.write(os.path.join(folder_path, shot_name), shot_name)

            # TODO: Add content disposition.
            response.content_type = "application/zip"
            return zip_data.getvalue()
    else:
        return HTTPError(404, folder_path) 
開發者ID:davidoren,項目名稱:CuckooSploit,代碼行數:26,代碼來源:api.py

示例6: change_indihub_agent_mode

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def change_indihub_agent_mode(mode):
    """Change INDIHUB Agent mode with a current INDI-profile"""

    if active_profile == "" or not indi_server.is_running():
        response.content_type = 'application/json'
        response.status = 500
        return json.dumps({'message': 'INDI-server is not running. You need to run INDI-server first.'})

    indihub_agent.stop()

    if mode == 'off':
        return

    indihub_agent.start(active_profile, mode)


###############################################################################
# Startup standalone server
############################################################################### 
開發者ID:knro,項目名稱:indiwebmanager,代碼行數:21,代碼來源:main.py

示例7: require_json

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def require_json(callback):

    def wrapper(*args, **kwargs):
        ct = request.content_type
        logger.debug("Content-type: %s", ct)

        if ct is None:
            ct = ''
        ct.strip().lower()

        if not ct.startswith('application/json'):
            logger.warning("JSON type expected, instead received: %s", ct)
            response.status = D.HTTP_STATUS_UNSUPPORTED_TYPE
            response.content_type = D.JSON_CONTENT_TYPE
            return dict(status='error',
                        reason='Request data type is not supported.')

        body = callback(*args, **kwargs)
        return body

    return wrapper 
開發者ID:eavatar,項目名稱:eavatar-me,代碼行數:23,代碼來源:service.py

示例8: search_json

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def search_json(query):
    authorize()

    query = '%' + query + '%'
    search_list = []

    if settings.general.getboolean('use_sonarr'):
        # Get matching series
        series = database.execute("SELECT title, sonarrSeriesId, year FROM table_shows WHERE title LIKE ? ORDER BY "
                                  "title ASC", (query,))
        for serie in series:
            search_list.append(dict([('name', re.sub(r'\ \(\d{4}\)', '', serie['title']) + ' (' + serie['year'] + ')'),
                                     ('url', base_url + 'episodes/' + str(serie['sonarrSeriesId']))]))
    
    if settings.general.getboolean('use_radarr'):
        # Get matching movies
        movies = database.execute("SELECT title, radarrId, year FROM table_movies WHERE title LIKE ? ORDER BY "
                                  "title ASC", (query,))
        for movie in movies:
            search_list.append(dict([('name', re.sub(r'\ \(\d{4}\)', '', movie['title']) + ' (' + movie['year'] + ')'),
                                     ('url', base_url + 'movie/' + str(movie['radarrId']))]))

    response.content_type = 'application/json'
    return dict(items=search_list) 
開發者ID:morpheus65535,項目名稱:bazarr,代碼行數:26,代碼來源:main.py

示例9: index

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def index():
    '''an endpoint to return alert schedules'''
    if request.body:
        request.body.read()
        request.body.close()
    response.content_type = "application/json"
    mongoclient = MongoClient(options.mongohost, options.mongoport)
    schedulers_db = mongoclient.meteor['alertschedules'].with_options(codec_options=CodecOptions(tz_aware=True))

    mongodb_alerts = schedulers_db.find()
    alert_schedules_dict = {}
    for mongodb_alert in mongodb_alerts:
        if mongodb_alert['last_run_at']:
            mongodb_alert['last_run_at'] = mongodb_alert['last_run_at'].isoformat()
        if 'modifiedat' in mongodb_alert:
            mongodb_alert['modifiedat'] = mongodb_alert['modifiedat'].isoformat()
        alert_schedules_dict[mongodb_alert['name']] = mongodb_alert

    response.body = json.dumps(alert_schedules_dict)
    response.status = 200
    return response 
開發者ID:mozilla,項目名稱:MozDef,代碼行數:23,代碼來源:index.py

示例10: sync_alert_schedules

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def sync_alert_schedules():
    '''an endpoint to return alerts schedules'''
    if not request.body:
        response.status = 503
        return response

    alert_schedules = json.loads(request.body.read())
    request.body.close()

    response.content_type = "application/json"
    mongoclient = MongoClient(options.mongohost, options.mongoport)
    schedulers_db = mongoclient.meteor['alertschedules'].with_options(codec_options=CodecOptions(tz_aware=True))
    results = schedulers_db.find()
    for result in results:
        if result['name'] in alert_schedules:
            new_sched = alert_schedules[result['name']]
            result['total_run_count'] = new_sched['total_run_count']
            result['last_run_at'] = new_sched['last_run_at']
            if result['last_run_at']:
                result['last_run_at'] = toUTC(result['last_run_at'])
            logger.debug("Inserting schedule for {0} into mongodb".format(result['name']))
            schedulers_db.save(result)

    response.status = 200
    return response 
開發者ID:mozilla,項目名稱:MozDef,代碼行數:27,代碼來源:index.py

示例11: update_alert_schedules

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def update_alert_schedules():
    '''an endpoint to return alerts schedules'''
    if not request.body:
        response.status = 503
        return response

    alert_schedules = json.loads(request.body.read())
    request.body.close()

    response.content_type = "application/json"
    mongoclient = MongoClient(options.mongohost, options.mongoport)
    schedulers_db = mongoclient.meteor['alertschedules'].with_options(codec_options=CodecOptions(tz_aware=True))
    schedulers_db.remove()

    for alert_name, alert_schedule in alert_schedules.items():
        if alert_schedule['last_run_at']:
            alert_schedule['last_run_at'] = toUTC(alert_schedule['last_run_at'])
        logger.debug("Inserting schedule for {0} into mongodb".format(alert_name))
        schedulers_db.insert(alert_schedule)

    response.status = 200
    return response 
開發者ID:mozilla,項目名稱:MozDef,代碼行數:24,代碼來源:index.py

示例12: get_key

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def get_key(id):
	api_auth = _authenticate()

	# Authorization is needed for this endpoint
	if api_auth["authenticated"] == "False":
		response.status = 401
		return dict({"info":"Unauthorized."})

	# Get User ID
	user_id = api_auth["id"]

	# Does the key have a valid format?
	if _valid_identifier(str(id)) != True:
		response.status = 400
		return dict({"info":"Key format invalid."})

	# Construct Resource Location from user_id and id
	redis_key = "KEY:"+str(user_id)+"::"+str(id)

	# Read from Redis
	try:
		key_content = rc.get(redis_key)
		if key_content == None:
			raise ValueError('not found')
	except:
		response.status = 404
		return dict({"info":"Not found."})

	response.content_type = 'text/plain'
	return(str(key_content))

# Increase Key 
開發者ID:u1i,項目名稱:bambleweeny,代碼行數:34,代碼來源:bambleweeny.py

示例13: get_list_item

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def get_list_item(id):
	api_auth = _authenticate()

	# Authorization is needed for this endpoint
	if api_auth["authenticated"] == "False":
		response.status = 401
		return dict({"info":"Unauthorized."})

	# Get User ID
	user_id = api_auth["id"]

	# Does the key have a valid format?
	if _valid_identifier_lists(str(id)) != True:
		response.status = 400
		return dict({"info":"List name is invalid."})

	# Construct Resource Location from user_id and id
	redis_key = "LIST:"+str(user_id)+"::"+str(id)

	# Read from Redis. If there's just one item left we need to
	# decrease NUMRES
	try:
		num_items = rc.llen(redis_key)
		if num_items == 1:
			rc.decr("NUMRES:"+str(user_id))
		key_content = rc.rpop(redis_key)
	except:
		response.status = 404
		return dict({"info":"Not found."})

	response.content_type = 'text/plain'
	return(str(key_content))

# Lists - Delete 
開發者ID:u1i,項目名稱:bambleweeny,代碼行數:36,代碼來源:bambleweeny.py

示例14: create_route

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def create_route():
	api_auth = _authenticate()

	# Authorization is needed for this endpoint
	if api_auth["authenticated"] == "False":
		response.status = 401
		return dict({"info":"Unauthorized."})

	# Get User ID
	user_id = api_auth["id"]

	try:
		payload = json.load(request.body)

		key = payload["key"]
		content_type = payload["content_type"]
	except:
		response.status = 400
		return dict({"info":"No valid JSON found in post body or mandatory fields missing."})

	id = str(uuid.uuid4())

	# Construct Resource Location
	redis_key = "ROUTE:"+str(id)
	route_record = {}
	route_record["key"] = key
	route_record["content_type"] = content_type
	route_record["user_id"] = user_id

	# Write to Redis
	try:
		rc.set(redis_key, json.dumps(route_record, ensure_ascii=False))

	except:
		response.status = 400
		return dict({"info":"not a valid request"})

	return(dict(info="ok", path="/routes/"+str(id)))

# Route - Read Key 
開發者ID:u1i,項目名稱:bambleweeny,代碼行數:42,代碼來源:bambleweeny.py

示例15: get_route

# 需要導入模塊: from bottle import response [as 別名]
# 或者: from bottle.response import content_type [as 別名]
def get_route(id, dummy=0, dummy2=0):
	route_key = "ROUTE:"+str(id)

	# Read Route from Redis
	try:
		route_content = rc.get(route_key)
		if route_content == None:
			raise ValueError('not found')

		route_record = json.loads(route_content)
		user_id = route_record["user_id"]
		key = route_record["key"]
		content_type = route_record["content_type"]

	except:
		response.status = 404
		return dict({"info":"Not found."})

	# Construct Resource Location from user_id and id
	redis_key = "KEY:"+str(user_id)+"::"+str(key)

	# Read from Redis
	try:
		key_content = rc.get(redis_key)
		if key_content == None:
			raise ValueError('not found.')
	except:
		response.status = 404
		return dict({"info":"Not found."})

	response.headers['Access-Control-Allow-Origin'] = '*'
	response.content_type = content_type
	return(parse_route(str(key_content), user_id))

# Create Bins 
開發者ID:u1i,項目名稱:bambleweeny,代碼行數:37,代碼來源:bambleweeny.py


注:本文中的bottle.response.content_type方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。