Python bottle.response.content_type() Examples

The following are 30 code examples of bottle.response.content_type(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bottle.response , or try the search function .
Example #1
Source File: web.py    From CuckooSploit with GNU General Public License v3.0 7 votes vote down vote up
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() 
Example #2
Source File: web.py    From mailur with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: main.py    From indiwebmanager with GNU Lesser General Public License v2.1 6 votes vote down vote up
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
############################################################################### 
Example #4
Source File: service.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: main.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: app.py    From gpuview with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: server.py    From nematus with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #8
Source File: api.py    From CuckooSploit with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #9
Source File: index.py    From MozDef with Mozilla Public License 2.0 6 votes vote down vote up
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 
Example #10
Source File: index.py    From MozDef with Mozilla Public License 2.0 6 votes vote down vote up
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 
Example #11
Source File: index.py    From MozDef with Mozilla Public License 2.0 6 votes vote down vote up
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 
Example #12
Source File: main.py    From indiwebmanager with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_indihub_status():
    """INDIHUB Agent status"""
    mode = indihub_agent.get_mode()
    is_running = indihub_agent.is_running()
    response.content_type = 'application/json'
    status = [{'status': str(is_running), 'mode': mode, 'active_profile': active_profile}]
    return json.dumps(status) 
Example #13
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def status():
    '''endpoint for grabbing watchlist contents'''
    if request.body:
        request.body.read()
        request.body.close()
    response.status = 200
    response.content_type = "application/json"
    response.body = getWatchlist()
    return response 
Example #14
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def index():
    '''returns a count of veris tags'''
    if request.body:
        request.body.read()
        request.body.close()
    response.content_type = "application/json"
    response.body = verisSummary()
    sendMessgeToPlugins(request, response, 'veris')
    return response 
Example #15
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def index():
    '''returns a list of dashboards to show on the UI'''
    if request.body:
        request.body.read()
        request.body.close()

    response.content_type = "application/json"
    response.body = kibanaDashboards()
    sendMessgeToPlugins(request, response, 'kibanadashboards')
    return response 
Example #16
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def index():
    '''
    return a json version of dshield query for an ip address
    https://isc.sans.edu/api/index.html
    '''
    if request.body:
        arequest = request.body.read()
        request.body.close()
    # valid json?
    try:
        requestDict = json.loads(arequest)
    except ValueError:
        response.status = 500
        return
    if 'ipaddress' in requestDict and isIPv4(requestDict['ipaddress']):
        url="https://isc.sans.edu/api/ip/"

        headers = {
            'User-Agent': options.user_agent
        }

        dresponse = requests.get('{0}{1}?json'.format(url, requestDict['ipaddress']), headers=headers)
        if dresponse.status_code == 200:
            response.content_type = "application/json"
            response.body = dresponse.content
        else:
            response.status = dresponse.status_code

    else:
        response.status = 500

    sendMessgeToPlugins(request, response, 'ipdshieldquery')
    return response 
Example #17
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def getPluginList(endpoint=None):
    ''' return a json representation of the plugin tuple
        (mname, mclass, mreg, mpriority)
         minus the actual class (which isn't json-able)
         for all plugins, or for a specific endpoint
    '''
    pluginResponse = list()
    if endpoint is None:
        for plugin in pluginList:
            pdict = {}
            pdict['file'] = plugin[0]
            pdict['name'] = plugin[1]
            pdict['description'] = plugin[2]
            pdict['registration'] = plugin[3]
            pdict['priority'] = plugin[4]
            pluginResponse.append(pdict)
    else:
        # filter the list to just the endpoint requested
        for plugin in pluginList:
            if endpoint in plugin[3]:
                pdict = {}
                pdict['file'] = plugin[0]
                pdict['name'] = plugin[1]
                pdict['description'] = plugin[2]
                pdict['registration'] = plugin[3]
                pdict['priority'] = plugin[4]
                pluginResponse.append(pdict)
    response.content_type = "application/json"
    response.body = json.dumps(pluginResponse)

    sendMessgeToPlugins(request, response, 'plugins')
    return response 
Example #18
Source File: bambleweeny.py    From bambleweeny with MIT License 5 votes vote down vote up
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 
Example #19
Source File: service.py    From eavatar-me with Apache License 2.0 5 votes vote down vote up
def require_auth(callback):

    def wrapper(*args, **kwargs):
        auth = request.get_header('Authorization')

        if get_webfront_engine().access_token != auth:
            response.status = D.HTTP_STATUS_AUTH_REQUIRED
            response.content_type = D.JSON_CONTENT_TYPE
            return dict(status='error', reason='Authentication required.')

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

    return wrapper 
Example #20
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def status():
    '''endpoint for a status/health check'''
    if request.body:
        request.body.read()
        request.body.close()
    response.status = 200
    response.content_type = "application/json"
    response.body = json.dumps(dict(status='ok', service='restapi'))
    sendMessgeToPlugins(request, response, 'status')
    return response 
Example #21
Source File: base.py    From mining with MIT License 5 votes vote down vote up
def base():
    response.set_header('charset', 'utf-8')
    response.content_type = 'application/json' 
Example #22
Source File: serve.py    From metadoc with MIT License 5 votes vote down vote up
def full_article():
  """GET data url required"""
  response.content_type = 'application/json'
  url = request.query.getone("url")
  if not url:
    abort(404)

  metadoc = Metadoc(url=url)
  payload = metadoc.query()

  return json.dumps(payload) 
Example #23
Source File: serve.py    From metadoc with MIT License 5 votes vote down vote up
def extract_article():
  """GET data url required"""
  response.content_type = 'application/json'
  url = request.query.getone("url")
  if not url:
    abort(404)

  metadoc = Metadoc(url=url)
  metadoc._prepare()
  metadoc._query_domain()
  metadoc._query_extract()

  payload = metadoc._render() # Preserve order
  return json.dumps(payload) 
Example #24
Source File: serve.py    From metadoc with MIT License 5 votes vote down vote up
def social_article():
  """GET data url required"""
  response.content_type = 'application/json'
  url = request.query.getone("url")
  if not url:
    abort(404)

  metadoc = Metadoc(url=url)
  payload = metadoc.query(mode="social", fmt="social")

  return json.dumps(payload) 
Example #25
Source File: maincontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def init_routes(self):
        @self.bottle_app.route(['//<url:re:.*>'])
        def empty(url=''):
            self.redirect('/' + url)

        @self.bottle_app.route(['/<user>//<url:re:.*>'])
        def empty2(user, url=''):
            self.redirect('/' + user + '/' + url)

        @self.bottle_app.route(['/static/<path:path>', '/static_cors/<path:path>'])
        def static_files(path):
            res = static_file(path, root=self.static_root)

            if 'HTTP_ORIGIN' in request.environ:
                self.set_options_headers(None, None, res)

            return res

        @self.bottle_app.route('/_message')
        def flash_message():
            message = request.query.getunicode('message', '')
            msg_type = request.query.getunicode('msg_type', '')
            self.flash_message(message, msg_type)
            return {}

        @self.bottle_app.route('/api/v1.yml')
        def get_api_spec_yaml():
            response.content_type = 'text/yaml'
            return wr_api_spec.get_api_spec_yaml(self.access.is_superuser())

        @self.bottle_app.route('/api/v1.json')
        def get_api_spec_json():
            response.content_type = 'application/json'
            return json.dumps(wr_api_spec.get_api_spec_dict(self.access.is_superuser()))

        @self.bottle_app.route('/<:re:.*>', method='ANY')
        def fallthrough():
            self._check_refer_redirect() 
Example #26
Source File: server.py    From homu with MIT License 5 votes vote down vote up
def callback():
    logger = g.logger.getChild('callback')

    response.content_type = 'text/plain'

    code = request.query.code
    state = json.loads(request.query.state)

    lazy_debug(logger, lambda: 'state: {}'.format(state))

    res = requests.post('https://github.com/login/oauth/access_token', data={
        'client_id': g.cfg['github']['app_client_id'],
        'client_secret': g.cfg['github']['app_client_secret'],
        'code': code,
    })
    args = urllib.parse.parse_qs(res.text)
    token = args['access_token'][0]

    repo_label = state['repo_label']
    repo_cfg = g.repo_cfgs[repo_label]
    repo = get_repo(repo_label, repo_cfg)

    user_gh = github3.login(token=token)

    if state['cmd'] == 'rollup':
        return rollup(user_gh, state, repo_label, repo_cfg, repo)
    elif state['cmd'] == 'synch':
        return synch(user_gh, state, repo_label, repo_cfg, repo)
    else:
        abort(400, 'Invalid command') 
Example #27
Source File: bottle.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def send_file(filename, root, guessmime=True, mimetype='text/plain'):
    """ Aborts execution and sends a static files as response. """
    root = os.path.abspath(root) + '/'
    filename = os.path.normpath(filename).strip('/')
    filename = os.path.join(root, filename)

    if not filename.startswith(root):    # HTTP状态码: 401
        abort(401, "Access denied.")
    if not os.path.exists(filename) or not os.path.isfile(filename):
        abort(404, "File does not exist.")     # 文件不存在
    if not os.access(filename, os.R_OK):
        abort(401, "You do not have permission to access this file.")

    if guessmime:
        guess = mimetypes.guess_type(filename)[0]
        if guess:
            response.content_type = guess
        elif mimetype:
            response.content_type = mimetype
    elif mimetype:
        response.content_type = mimetype

    stats = os.stat(filename)
    # TODO: HTTP_IF_MODIFIED_SINCE -> 304 (Thu, 02 Jul 2009 23:16:31 CEST)
    if 'Content-Length' not in response.header:
        response.header['Content-Length'] = stats.st_size
    if 'Last-Modified' not in response.header:
        ts = time.gmtime(stats.st_mtime)
        ts = time.strftime("%a, %d %b %Y %H:%M:%S +0000", ts)
        response.header['Last-Modified'] = ts

    raise BreakTheBottle(open(filename, 'r'))    # 抛出异常


###############################################################################
###############################################################################
###############################################################################


# Routing   路由处理部分-定义 
Example #28
Source File: bottle.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def bind(self):
        """ Clears old data and creates a brand new Response object """
        self._COOKIES = None

        self.status = 200
        self.header = HeaderDict()          # HTTP 头数据
        self.content_type = 'text/html'
        self.error = None 
Example #29
Source File: api.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def pcap_get(task_id):
    file_path = os.path.join(CUCKOO_ROOT, "storage", "analyses",
                             "%d" % task_id, "dump.pcap")
    if os.path.exists(file_path):
        response.content_type = "application/octet-stream; charset=UTF-8"
        try:
            return open(file_path, "rb").read()
        except:
            return HTTPError(500, "An error occurred while reading PCAP")
    else:
        return HTTPError(404, "File not found") 
Example #30
Source File: api.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def jsonize(data):
    """Converts data dict to JSON.
    @param data: data dict
    @return: JSON formatted data
    """
    response.content_type = "application/json; charset=UTF-8"
    return json.dumps(data, sort_keys=False, indent=4)