Python web.header() Examples

The following are 30 code examples of web.header(). 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 web , or try the search function .
Example #1
Source File: main.py    From BaoTa-Panel with GNU General Public License v3.0 6 votes vote down vote up
def GET(self):
        get = web.input()
        if not public.checkToken(get): get.filename = str(time.time());
        try:
            get.filename = '/www/server/panel/plugin/psync/backup/' + get.filename.encode('utf-8');
            import os
            fp = open(get.filename,'rb')
            size = os.path.getsize(get.filename)
            filename = os.path.basename(get.filename)
            
            #输出文件头
            web.header("Content-Disposition", "attachment; filename=" + filename);
            web.header("Content-Length", size);
            web.header('Content-Type','application/octet-stream')
            buff = 4096
            while True:
                fBody = fp.read(buff)
                if fBody:
                    yield fBody
                else:
                    return
        except Exception, e:
            yield 'Error' 
Example #2
Source File: site.py    From iOS-private-api-scanner with GNU General Public License v2.0 6 votes vote down vote up
def GET(self):
        res = scanapp.scan()
        web.header("Content-Type","text/html; charset=utf-8")
        html = """
        <html><head>扫描结果</head><body><table>%s</table></body></html>
        """
        table = ""
        tr = "<tr>%s</tr>"
        td = "<td>%s</td>"
        count = 6
        tmp = ""
        for r in res:
            if count > 0:
                tmp += td % r
                count -= 1
            elif count == 0:
                count = 6
                table += tr % tmp
                tmp = ""
        return html % table 
Example #3
Source File: auth.py    From netflix-proxy with MIT License 6 votes vote down vote up
def POST(self):
        auth_form = get_form()
        if not auth_form.validates():
            flash('error', 'form validation failed')
            return render.form(get_form(name='delete'))

        is_ipv4 = web.net.validipaddr(auth_form['ipaddr'].value)
        is_ipv6 = web.net.validip6addr(auth_form['ipaddr'].value)
        if is_ipv4 == False and is_ipv6 == False:
            flash('error', '%s is not a valid ipv4/6 address' % auth_form['ipaddr'].value)
            return render.form(get_form(name='delete'))
        
        web.debug('De-authorising ipaddr=%s' % auth_form['ipaddr'].value)
        web.header('Content-Type', 'text/html')
        db_result = db.delete('ipaddrs', where="user_id=%s AND ipaddr='%s'" % (session.user['ID'],
                                                                               auth_form['ipaddr'].value))
        web.debug('db.delete: %s' % db_result)
        if db_result == 0: db_result = 1
        for i in range(0, db_result):
            if is_ipv4: result = run_ipt_cmd(auth_form['ipaddr'].value, 'D')
            if is_ipv6: result = run_ipt6_cmd(auth_form['ipaddr'].value, 'D') 
            web.debug('iptables_update: %s' % [result])
        session.auth_ip_count -= 1
        flash('success', '%s de-authorized' % auth_form['ipaddr'].value)
        return render.form(get_form(name='delete')) 
Example #4
Source File: task_edit_file.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def action_download(self, courseid, taskid, path):
        """ Download a file or a directory """

        wanted_path = self.verify_path(courseid, taskid, path)
        if wanted_path is None:
            raise web.notfound()

        task_fs = self.task_factory.get_task_fs(courseid, taskid)
        (method, mimetype_or_none, file_or_url) = task_fs.distribute(wanted_path)

        if method == "local":
            web.header('Content-Type', mimetype_or_none)
            return file_or_url
        elif method == "url":
            raise web.redirect(file_or_url)
        else:
            raise web.notfound() 
Example #5
Source File: auth.py    From netflix-proxy with MIT License 6 votes vote down vote up
def POST(self):
        form = DDNSIndex.ddns_add_form()

        if not form.validates():
            flash('error', 'form validation failed')
            raise web.seeother('/ddns')

        web.debug('Removing domain=%s' % form['domain'].value)
        web.header('Content-Type', 'text/html')
        db_result = db.delete('DDNS', where="user_id=%s AND domain='%s'" % (session.user['ID'],
                                                                               form['domain'].value))
        web.debug('db.delete: %s' % db_result)
        flash('success', '%s removed' % form['domain'].value)
        return web.seeother('/ddns')        

# Adds a wsgi callable for uwsgi 
Example #6
Source File: download.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ GET request """
        course, __ = self.get_course_and_check_rights(courseid)
        user_input = web.input(tasks=[], aggregations=[], users=[])
        error = ""

        # First, check for a particular submission
        if "submission" in user_input:
            submission = self.database.submissions.find_one({"_id": ObjectId(user_input.submission),
                                                             "courseid": course.get_id(),
                                                             "status": {"$in": ["done", "error"]}})
            if submission is None:
                raise web.notfound()

            self._logger.info("Downloading submission %s - %s - %s - %s", submission['_id'], submission['courseid'],
                              submission['taskid'], submission['username'])
            archive, error = self.submission_manager.get_submission_archive(course, [submission], [])
            if not error:
                web.header('Content-Type', 'application/x-gzip', unique=True)
                web.header('Content-Disposition', 'attachment; filename="submissions.tgz"', unique=True)
                return archive

        # Else, display the complete page
        return self.display_page(course, user_input, error) 
Example #7
Source File: group_edit.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid, groupid=''):  # pylint: disable=arguments-differ
        """ Edit a group """
        course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True)

        if course.is_lti():
            raise web.notfound()

        if "download" in web.input():
            web.header('Content-Type', 'text/x-yaml', unique=True)
            web.header('Content-Disposition', 'attachment; filename="groups.yaml"', unique=True)
            groups = [{"description": group["description"],
                           "students": group["students"],
                           "size": group["size"],
                            "audiences": [str(c) for c in group["audiences"]]} for group in
                          self.user_manager.get_course_groups(course)]

            return yaml.dump(groups)

        return self.display_page(course) 
Example #8
Source File: danger_zone.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ GET request """
        course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)

        data = web.input()

        if "download" in data:
            filepath = os.path.join(self.backup_dir, courseid, data["download"] + '.zip')

            if not os.path.exists(os.path.dirname(filepath)):
                raise web.notfound()

            web.header('Content-Type', 'application/zip', unique=True)
            web.header('Content-Disposition', 'attachment; filename="' + data["download"] + '.zip' + '"', unique=True)

            return open(filepath, 'rb')

        else:
            return self.page(course) 
Example #9
Source File: _api_page.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def _api_convert_output(return_value):
    """ Convert the output to what the client asks """
    content_type = web.ctx.environ.get('CONTENT_TYPE', 'text/json')

    if "text/json" in content_type:
        web.header('Content-Type', 'text/json; charset=utf-8')
        return json.dumps(return_value)
    if "text/html" in content_type:
        web.header('Content-Type', 'text/html; charset=utf-8')
        dump = yaml.dump(return_value)
        return "<pre>" + web.websafe(dump) + "</pre>"
    if "text/yaml" in content_type or \
                    "text/x-yaml" in content_type or \
                    "application/yaml" in content_type or \
                    "application/x-yaml" in content_type:
        web.header('Content-Type', 'text/yaml; charset=utf-8')
        dump = yaml.dump(return_value)
        return dump
    web.header('Content-Type', 'text/json; charset=utf-8')
    return json.dumps(return_value) 
Example #10
Source File: main.py    From BaoTa-Panel with GNU General Public License v3.0 6 votes vote down vote up
def GET(self):
        get = web.input()
        try:
            get.filename = get.filename.encode('utf-8');
            import os        
            fp = open(get.filename,'rb')
            size = os.path.getsize(get.filename)
            filename = os.path.basename(get.filename)
            
            #输出文件头
            web.header("Content-Disposition", "attachment; filename=" +filename);
            web.header("Content-Length", size);
            web.header('Content-Type','application/octet-stream');
            buff = 4096
            while True:
                fBody = fp.read(buff)
                if fBody:
                    yield fBody
                else:
                    return
        except Exception, e:
            yield 'Error' 
Example #11
Source File: main.py    From BaoTa-Panel with GNU General Public License v3.0 6 votes vote down vote up
def GET(self):
        import vilidate,time
        if hasattr(web.ctx.session,'codeTime'):
            if (time.time() - web.ctx.session.codeTime) < 0.1:
                return public.getMsg('CODE_BOOM');
        vie = vilidate.vieCode();
        codeImage = vie.GetCodeImage(80,4);
        try:
            from cStringIO import StringIO
        except:
            from StringIO import StringIO
        out = StringIO();
        codeImage[0].save(out, "png")
        web.ctx.session.codeStr  = public.md5("".join(codeImage[1]).lower())
        web.ctx.session.codeTime = time.time()
        web.header('Cache-Control', 'private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
        web.header('Pragma', 'no-cache');
        web.header('Content-Type','image/png');
        return out.getvalue(); 
Example #12
Source File: __init__.py    From opennumber with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        web.header('Content-Type', 'text/html; charset=utf8')
        pass  # 
Example #13
Source File: __init__.py    From opennumber with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super(JsonHandler, self).__init__()
        web.header("Access-Control-Allow-Origin", '*')
        web.header('Cache-Control', 'no-cache, no-store, must-revalidate')
        web.header('Pragma', 'no-cache')
        web.header('Expires', '0')
        web.header('Content-Type', 'application/json; charset=utf8')
        
        pass 
Example #14
Source File: public.py    From BaoTa-Panel with GNU General Public License v3.0 5 votes vote down vote up
def getJson(data):
    import json,web
    web.header('Content-Type','application/json; charset=utf-8')
    return json.dumps(data) 
Example #15
Source File: auth.py    From netflix-proxy with MIT License 5 votes vote down vote up
def POST(self):
        form = DDNSIndex.ddns_add_form()
        if not form.validates():
            flash('error', 'form validation failed')
            raise web.seeother('/ddns')
        
        web.debug('Adding domain=%s' % form['domain'].value)
        web.header('Content-Type', 'text/html')
        db_result = db.insert('DDNS',
                                  user_id=session.user['ID'],
                                  domain=form['domain'].value)
        web.debug('db.insert: %s' % db_result)
        flash('success', 'succesfully added %s' % form['domain'].value)
        return web.seeother('/ddns') 
Example #16
Source File: server.py    From Apple-iOS-MDM-Server with MIT License 5 votes vote down vote up
def GET(self):

        if 'CA.crt' in os.listdir('.'):
            web.header('Content-Type', 'application/octet-stream;charset=utf-8')
            web.header('Content-Disposition', 'attachment;filename="CA.crt"')
            return open('CA.crt', "rb").read()
        else:
            raise web.notfound() 
Example #17
Source File: site.py    From iOS-private-api-scanner with GNU General Public License v2.0 5 votes vote down vote up
def GET(self):
        web.header("Content-Type","text/html; charset=utf-8")
        return """<html><head></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" />
<br/>
<input type="submit" />
</form>
</body></html>""" 
Example #18
Source File: mimerender.py    From planespotter with MIT License 5 votes vote down vote up
def _make_response(self, content, headers, status):
            web.ctx.status = status
            for k, v in headers:
                web.header(k, v)
            return content 
Example #19
Source File: server.py    From Apple-iOS-MDM-Server with MIT License 5 votes vote down vote up
def GET(self):

        if 'MyApp.ipa' in os.listdir('.'):
            web.header('Content-Type', 'application/octet-stream;charset=utf-8')
            web.header('Content-Disposition', 'attachment;filename="MyApp.ipa"')
            return open('MyApp.ipa', "rb").read()
        else:
            return web.ok 
Example #20
Source File: server.py    From Apple-iOS-MDM-Server with MIT License 5 votes vote down vote up
def GET(self):

        if 'Manifest.plist' in os.listdir('.'):
            web.header('Content-Type', 'text/xml;charset=utf-8')
            return open('Manifest.plist', "rb").read()
        else:
            raise web.notfound() 
Example #21
Source File: server.py    From Apple-iOS-MDM-Server with MIT License 5 votes vote down vote up
def GET(self):
        if 'favicon.ico' in os.listdir('.'):
            web.header('Content-Type', 'image/x-icon;charset=utf-8')
            return open('favicon.ico', "rb").read()
        elif 'favicon.ico' in os.listdir('./static/'):
            web.header('Content-Type', 'image/x-icon;charset=utf-8')
            return open('/static/favicon.ico', "rb").read()
        else:
            raise web.ok 
Example #22
Source File: images.py    From jingwei with MIT License 5 votes vote down vote up
def GET(self,name):
        ext = name.split(".")[-1] # Gather extension
        if name.find('.')<0:
            ext = 'jpg'
        imfile = self.get_local( os.path.splitext(name)[0] )
        #print imfile
        try:
            web.header("Content-Type", cType[ext]) # Set the Header
            return open(imfile,"rb").read() # Notice 'rb' for reading images
        except:
            raise web.notfound() 
Example #23
Source File: server.py    From Apple-iOS-MDM-Server with MIT License 5 votes vote down vote up
def GET(self):
        # Enroll an iPad/iPhone/iPod when requested
        if 'Enroll.mobileconfig' in os.listdir('.'):
            web.header('Content-Type', 'application/x-apple-aspen-config;charset=utf-8')
            web.header('Content-Disposition', 'attachment;filename="Enroll.mobileconfig"')
            return open('Enroll.mobileconfig', "rb").read()
        else:
            raise web.notfound() 
Example #24
Source File: saml2_auth.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def GET(self, id):
        settings = self.user_manager.get_auth_method(id).get_settings()
        auth = OneLogin_Saml2_Auth(prepare_request(settings), settings)
        metadata = auth.get_settings().get_sp_metadata()
        errors = auth.get_settings().validate_metadata(metadata)

        if len(errors) == 0:
            web.header('Content-Type', 'text/xml')
            return metadata
        else:
            web.ctx.status = "500 Internal Server Error"
            return ', '.join(errors) 
Example #25
Source File: audience_list.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def GET_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ GET request """
        course, __ = self.get_course_and_check_rights(courseid)

        if "download" in web.input():
            web.header('Content-Type', 'text/x-yaml', unique=True)
            web.header('Content-Disposition', 'attachment; filename="audiences.yaml"', unique=True)
            audiences = [{"description": audience["description"],
                           "students": audience["students"],
                           "tutors": audience["tutors"]} for audience in
                          self.user_manager.get_course_audiences(course)]

            return yaml.dump(audiences)

        return self.page(course) 
Example #26
Source File: tasks.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def GET(self, courseid, taskid, path):  # pylint: disable=arguments-differ
        """ GET request """
        try:
            course = self.course_factory.get_course(courseid)
            if not self.user_manager.course_is_open_to_user(course):
                return handle_course_unavailable(self.app.get_homepath(), self.template_helper, self.user_manager, course)

            path_norm = posixpath.normpath(urllib.parse.unquote(path))

            if taskid == "$common":
                public_folder = course.get_fs().from_subfolder("$common").from_subfolder("public")
            else:

                task = course.get_task(taskid)
                if not self.user_manager.task_is_visible_by_user(task):  # ignore LTI check here
                    return self.template_helper.get_renderer().task_unavailable()

                public_folder = task.get_fs().from_subfolder("public")
            (method, mimetype_or_none, file_or_url) = public_folder.distribute(path_norm, False)

            if method == "local":
                web.header('Content-Type', mimetype_or_none)
                return file_or_url
            elif method == "url":
                raise web.redirect(file_or_url)
            else:
                raise web.notfound()
        except web.HTTPError as error_or_redirect:
            raise error_or_redirect
        except:
            if web.config.debug:
                raise
            else:
                raise web.notfound() 
Example #27
Source File: _api_page.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def send(self):
        web.header('Allow', ",".join(self.methods))
        return APIError.send(self) 
Example #28
Source File: nightmare_frontend.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def GET(self):
    if not 'user' in session or session.user is None:
      f = register_form()
      return render.login(f)

    i = web.input()
    if not i.has_key("id"):
      return render.error("No crash identifier given")
    if i.has_key("diff"):
      is_diff = True
    else:
      is_diff = False

    db = init_web_db()

    try:
      original_file, crash_file = find_original_file(db, i.id)
    except:
      return render.error(sys.exc_info()[1])

    if original_file is not None:
      basename = os.path.basename(original_file)
      web.header("Content-type", "application/octet-stream")
      web.header("Content-disposition", "attachment; filename=%s" % basename)
      f = open(original_file, 'rb')
      return f.read()

    return render.error("Cannot find original sample.")

#----------------------------------------------------------------------- 
Example #29
Source File: nightmare_frontend.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def POST(self):
    if not 'user' in session or session.user is None:
      f = register_form()
      return render.login(f)

    i = web.input()
    if not i.has_key('samples_dir'):
      return render.error("No samples sub-directory specified.")
    if not i.has_key('magic'):
      return render.error("No magic header specified.")
    if not i.has_key('extension'):
      return render.error("No file extension specified.")
    if not i.has_key('search'):
      search = ""
    else:
      search = i["search"]
    if i["samples_dir"].find(".") > -1 or \
       i["samples_dir"].find("/") > -1 or \
       i["samples_dir"].find("\\") > -1:
      return render.error("Invalid sub-directory")

    db = init_web_db()
    res = db.select("config", what="value", where="name = 'TEMPLATES_PATH'")
    res = list(res)
    if len(res) == 0:
      return render.error("Samples path is not yet configured. Please configure it in the configuration section.")
    whole_dir = os.path.join(res[0].value, i.samples_dir)

    if not os.path.exists(whole_dir):
      os.makedirs(whole_dir)

    from find_samples import CSamplesFinder
    finder = CSamplesFinder()
    finder.find(i.extension, i.magic, whole_dir, search)
    return render.message("Process finished.")

#----------------------------------------------------------------------- 
Example #30
Source File: auth.py    From netflix-proxy with MIT License 4 votes vote down vote up
def POST(self):
        auth_form = get_form()
        if not auth_form.validates():
            flash('error', 'form validation failed')
            return render.form(get_form())

        is_ipv4 = web.net.validipaddr(auth_form['ipaddr'].value)
        is_ipv6 = web.net.validip6addr(auth_form['ipaddr'].value)
        if is_ipv4 == False and is_ipv6 == False:
            flash('error', '%s is not a valid ipv4/6 address' % auth_form['ipaddr'].value)
            return render.form(get_form())

        if session.already_authorized:
            flash('error', '%s is already authorized' % auth_form['ipaddr'].value)
            return render.form(get_form())
        
        if session.auth_ip_count <= MAX_AUTH_IP_COUNT - 1 or session.user['privilege'] == 1:
            web.debug('Authorising ipaddr=%s' % auth_form['ipaddr'].value)
            web.header('Content-Type', 'text/html')
            if is_ipv4: result = run_ipt_cmd(auth_form['ipaddr'].value, 'I')
            if is_ipv6: result = run_ipt6_cmd(auth_form['ipaddr'].value, 'I')       
            web.debug('iptables_update: %s' % [result])
            
            if result[0] == 0:
                db_result = db.insert('ipaddrs',
                                      user_id=session.user['ID'],
                                      ipaddr=auth_form['ipaddr'].value)
                web.debug('db.insert: %s' % db_result)
                session.auth_ip_count += 1
                flash('success', 'succesfully authorized %s' % auth_form['ipaddr'].value)
                if is_redirected():
                    web.debug('is_redirected()=%s' % is_redirected()) 
                    return render.redirect(get_redirect_page())
                else:
                    return render.form(get_form())
            
            else:
                flash('error', 'error authorizing %s' % auth_form['ipaddr'].value)
                return render.form(get_form())

        else:
            flash('error', 'exceeded %s maximim authorized IPs' % MAX_AUTH_IP_COUNT)                          
            return render.form(get_form())