当前位置: 首页>>代码示例>>Python>>正文


Python web.badrequest函数代码示例

本文整理汇总了Python中web.badrequest函数的典型用法代码示例。如果您正苦于以下问题:Python badrequest函数的具体用法?Python badrequest怎么用?Python badrequest使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了badrequest函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: POST

	def POST(self):
		i = web.input(FileData=None, FileName=None, FileSize=None)

		if i.FileData and i.FileName and i.FileSize: 
			key = str(random.random())[2:] + str(random.random())[2:] + str(random.random())[2:]

			y = datetime.now().year
			m = datetime.now().month
			year_dir = 'static/uploads/' + str(y)
			month_dir = year_dir + '/' + str(m)

			if not os.path.exists(year_dir):
				os.mkdir(year_dir)
			if not os.path.exists(month_dir):
				os.mkdir(month_dir)
			
			file_path = month_dir + '/' + key + '_' + i.FileName
			
			try:
				f = open(file_path, 'wb')
				f.write(i.FileData)
				f.close()

				return json.dumps({'url': '/' + file_path})
			except:
				if os.path.isfile(file_path):
					os.remove(file_path)

				# how to set http status? see web.webapi
				web.badrequest()
		else:
			print i.FileData == {} or i.FileData == None, i.FileName, i.FileSize
开发者ID:friendwu,项目名称:xwp2,代码行数:32,代码来源:admin.py

示例2: POST

 def POST(self):
     """Called when the user uploads a file using POST"""
     from PIL import Image
     # get the data from the form
     x = web.input(myfile=web.Storage(file=''))
     # check the input file to make sure it's legal
     if 'myfile' not in x or not x.myfile.file: raise web.badrequest()
     # create the filename (and containing dir) based on the current time
     fname = os.path.join(IMAGEDIR, '%d.jpg' % (time.time()*1000))
     try:
         os.makedirs(os.path.dirname(fname))
     except OSError:
         pass
     # save the image
     fout = open(fname, 'w')
     fout.write(x.myfile.file.read())
     fout.close()
     # remove the image from the uploaded params
     del x['myfile']
     try:
         # if it's a valid image, process it
         im = Image.open(fname)
         web.debug('Saved valid image to %s, about to call process() on it' % (fname))
         results = process(im, fname, dict(x))
         return results
     except IOError:
         # if not, delete the image and return bad request
         try:
             os.remove(fname)
         except IOError:
             pass
         raise web.badrequest()
开发者ID:neeraj-kumar,项目名称:nkpylib,代码行数:32,代码来源:simpleupload.py

示例3: GET

    def GET(self,user_id_string):
        """
        return back the info for the next set of images
        expects to receive the user id string
        can receive the id of the last viewed image
        """

        # make sure we have a user string
        if not user_id_string:
            log.warning('ImageDetails GET [%s]: no user id string' %
                        user_id_string)
            web.badrequest()

        # find user's last viewed
        key = '%s:user_details:%s' % (NS, user_id_string)
        last_viewed_id = rc.hget(key, 'last_viewed_id')
        if last_viewed_id:
            # we get back a string
            last_viewed_id = int(last_viewed_id)

        # if there is no last viewed, it's 0
        else:
            last_viewed_id = 0

        # find the data on the next set of images
        try:
            with connect(Images) as c:
                images = c.get_images_since(image_id=last_viewed_id,
                                            timestamp=None,
                                            limit=10,
                                            offset=0)
        except io.Exception, ex:
            log.exception('ImageDetails GET [%s] [%s]: getting images' %
                          (user_id_string,last_viewed_id))
            web.internalerror()
开发者ID:rranshous,项目名称:imageviewer,代码行数:35,代码来源:app.py

示例4: PUT

    def PUT(self, id, setting):
        if setting not in self.Settings:
            web.notfound()
            return None

        try:
            configData = json.loads(web.data())

            id = int(id)
            vm = model.getVM(web.ctx.veerezoDB, id)
            if vm['user'] != web.ctx.username:
                web.forbidden()
                return None
        except (ValueError, KeyError):
            web.notfound()
            return None

        fn = '_put' + self.Settings[setting]
        f = getattr(self, fn)
        try:
            f(id, vm, configData)
        except ValueError as e:
            web.badrequest()
            return {'error': 'ValueError: {0}'.format(e.message)}

        web.nocontent()
        return None
开发者ID:jakebarnwell,项目名称:PythonGenerator,代码行数:27,代码来源:main.py

示例5: POST

 def POST(self, name):
     _auth_check()
     variables = web.input()        
     if len(variables) != 1:
         try:
             if name is None:
                 raise web.badrequest()                
             raw_state = float(variables.get('state'))
             boolean_state = None
             remove_override = False
             if raw_state in ['on', 'ON', 'On', 'True', 'true', 'TRUE']:
                 boolean_state = True
             if raw_state in ['off', 'OFF', 'Of', 'False', 'false', 'FALSE']:
                 boolean_state = False
             if raw_state in ['remove', 'REMOVE', 'Remove']:
                 remove_override = True
             else:
                 raise web.badrequest()                
             if self._is_heater(name):
                 if remove_override:
                     brew_controller.remove_heater_override()
                 else:
                     brew_controller.set_heater_override(boolean_state)
             elif self._is_freezer(name):
                 if remove_override:
                     brew_controller.remove_freezer_override()
                 else:
                     brew_controller.set_freezer_override(boolean_state)
             else:
                 raise web.badrequest()
         except Exception as e:
             print 'Error calling device endpoint: ' + str(e)
             raise web.badrequest()
     else:        
         raise web.badrequest()
开发者ID:tnanakou,项目名称:chestfreezer,代码行数:35,代码来源:chestfreezer_api.py

示例6: POST

    def POST(self, device_name):
        args, body = templeton.handlers.get_request_parms()
        try:
            assignee = body['assignee']
            duration = int(body['duration'])
            image_name = body['image']
            environment = body.get('environment', 'any')
        except (KeyError, ValueError):
            raise web.badrequest()

        try:
            image = self.db.images.get(image_name)
        except exceptions.NotFound:
            raise web.notfound()

        boot_config = {}
        for k in image['boot_config_keys']:
            try:
                boot_config[k] = body[k]
            except KeyError:
                raise web.badrequest()

        request_id = self.db.requests.add(device_name, environment, assignee,
                duration, image['id'], boot_config)
        mozpool.mozpool.driver.handle_event(request_id, 'find_device', None)
        info = self.db.requests.get_info(request_id)
        info['url'] = "http://%s/api/request/%d/" % ((config.get('server', 'fqdn'), request_id))
        response_data = {'request': info}
        if self.db.requests.get_machine_state(request_id) == 'closed':
            raise ConflictJSON(response_data)
        return response_data
开发者ID:awrede,项目名称:mozpool,代码行数:31,代码来源:handlers.py

示例7: DELETE

    def DELETE(self, resource):
        """
        Try to delete the supplied resource
        """
        if isTestMode():  # check env. if in test mode, import dbconn mock
            import Shared

            dbConn = Shared.dbMock
        else:
            dbConn = DataAccessLayer.DataAccessLayer()

        if not isValidKey(resource):
            logging.info("Item-DELETE: invalid resource key (%s)", resource)
            web.badrequest()
            return

        try:
            dbConn.delete(resource)
        except AttributeError:
            logging.warning("Item-DELETE: unable to delete resource (%s)", resource)
            web.notfound()
            return
        except Exception as e:
            logging.error("Item-DELETE: Unexpected exception when deleting: %s", e)
            web.badrequest()
            return
        web.ok()
        return
开发者ID:OttoDeLupe,项目名称:ThingsToDo,代码行数:28,代码来源:BizLayer.py

示例8: GET

    def GET(self, resource):
        """
        dejsonize the critieria, get a db connection, search for the criteria, get a list of
        matching items back, json-ize them, send them back to the client
        """
        if not isValidKey(resource):
            logging.info("Item-GET: invalid resource key (%s)", resource)
            web.badrequest()
            return

        try:
            rtn = getByKeys(resource)
        except:
            logging.info("Item-GET: invalid resource (%s)", resource)
            web.badrequest()
            return

        if rtn is None:
            logging.info("Item-GET: resource not found (%s)", resource)
            web.notfound()
            return

        web.header("Content-Type", "text/plain")
        return json.JSONEncoder().encode(rtn)
        return rtn
开发者ID:OttoDeLupe,项目名称:ThingsToDo,代码行数:25,代码来源:BizLayer.py

示例9: checked_data

    def checked_data(self, validate_method=None, **kwargs):
        try:
            data = kwargs.pop('data', web.data())
            if validate_method:
                method = validate_method
            else:
                method = self.validator.validate

            valid_data = method(data, **kwargs)
        except (
            errors.InvalidInterfacesInfo,
            errors.InvalidMetadata
        ) as exc:
            notifier.notify("error", str(exc))
            raise web.badrequest(message=str(exc))
        except (
            errors.AlreadyExists
        ) as exc:
            err = web.conflict()
            err.message = exc.message
            raise err
        except (
            errors.InvalidData,
            Exception
        ) as exc:
            raise web.badrequest(message=str(exc))
        return valid_data
开发者ID:adanin,项目名称:fuel-web,代码行数:27,代码来源:base.py

示例10: _PUT

    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # TODO valid
        network_name = param[1]
        if not network_name:
            return web.notfound()

        if validates_nw_status(self) is False:
            return web.badrequest(self.view.alert)

        status = int(self.input.status)

        kvc = KaresansuiVirtConnection()
        try:
            kvn = kvc.search_kvn_networks(network_name)[0]
            if status == NETWORK_INACTIVE:
                # Stop network
                network_start_stop_job(self, host_id, network_name, 'stop')
                return web.accepted("/host/%s/network/%s.%s" % (host_id, network_name, self.__template__['media']))
            elif status == NETWORK_ACTIVE:
                # Start network
                network_start_stop_job(self, host_id, network_name, 'start')
                return web.accepted("/host/%s/network/%s.%s" % (host_id, network_name, self.__template__['media']))
            else:
                return web.badrequest()
        finally:
            kvc.close()
开发者ID:AdUser,项目名称:karesansui,代码行数:29,代码来源:hostby1networkby1status.py

示例11: GET

    def GET(self):
        x = web.input(project=0)

        project = models.Project.get(id=x.project)
        if not project:
            raise web.notfound()

        if x.get('glyph'):
            if not models.Glyph.exists(name=x.get('glyph'),
                                       project_id=project.id):
                raise web.notfound()
            project.currentglyph = x.glyph
            web.ctx.orm.commit()

        masters = project.get_ordered_masters()

        masters_list = []

        metapost = Metapost(project)

        for i, master in enumerate(masters):

            prepare_master_environment(master)

            glyphs = master.get_glyphs()
            glyphs = glyphs.filter(models.Glyph.name == project.currentglyph)

            if not metapost.execute_single(master, glyphs.first()):
                return web.badrequest()

            master_instancelog = project.get_instancelog(master.version, 'a')
            glyphsdata = get_glyph_info_from_log(master_instancelog,
                                                 master=master)

            metalabel = get_metapolation_label(chr(models.LABELS[i]))

            masters_list.append({'glyphs': glyphsdata,
                                 'label': chr(models.LABELS[i]),
                                 'metapolation': metalabel,
                                 'master_id': master.id})

        glyphs = masters[0].get_glyphs()

        glyphs = glyphs.filter(models.Glyph.name == project.currentglyph)

        if not metapost.execute_interpolated_single(glyphs.first()):
            return web.badrequest()

        instancelog = project.get_instancelog(masters[0].version)
        metaglyphs = get_glyph_info_from_log(instancelog)

        import operator
        masters = map(operator.attrgetter('id', 'version'),
                      models.Master.filter(project_id=project.id))

        return ujson.dumps({'masters': masters_list,
                            'versions': project.get_versions(),
                            'metaglyphs': metaglyphs,
                            'mode': project.mfparser,
                            'project_id': project.id})
开发者ID:kolber,项目名称:metapolator,代码行数:60,代码来源:project.py

示例12: GET

 def GET(self,uri):
   request = uri.split('/')
   if request == ['']:
     web.badrequest()
     return "Incorrect request : /tempoedf/{now | tomorrow}\n"
   try:
     format = request[1]
   except:
     format = None
   if request[0] == "now":
     result = temporequest.TempoToday()
     if format == "json":
       web.header('Content-Type', 'application/json')
       return json.dumps({"tempocolor": result})
     else:
       return result
   if request[0] == "tomorrow":
     result = temporequest.TempoTomorrow()
     if format == "json":
       web.header('Content-Type', 'application/json')
       return json.dumps({"tempocolor": result})
     else:
       return result
   web.badrequest()
   return "Incorrect request : /tempoedf/{now | tomorrow}\n"
开发者ID:badele,项目名称:api-domogeek,代码行数:25,代码来源:apidomogeek.py

示例13: POST

        def POST(self):
            web.header('Content-Type', 'text/json')
            data = web.data()
            try:
                data = JSONWrapper(json.loads(data))
            except ValueError:
                data = web.input()

            timelimit = getattr(data, 'timelimit', straitjacket_settings.MAX_RUNTIME)
            timelimit = float(timelimit) if timelimit else None

            if hasattr(data, 'stdin'):
                stdin = [data.stdin] if not type(data.stdin) == list else data.stdin
            else:
                stdin = [None]

            try:
                results = wrapper.run(data.language, data.source, stdin, timelimit=timelimit)
                return json.dumps(results)
            except straitjacket.InputError as ex:
                LOGGER.error("Input error: {0}".format(ex))
                raise web.badrequest()
            except AttributeError as ex:
                LOGGER.error("Attribute error: {0}".format(ex))
                raise web.badrequest()
开发者ID:EliRibble,项目名称:straitjacket,代码行数:25,代码来源:server.py

示例14: unspuninput

def unspuninput(page_name, *args, **kwargs):
    myspinner = web.input('spinner').spinner
    spinfield = genspinfield(myspinner)
    mapping = dict((spinfield(x), x) for x in args + tuple(kwargs.keys()) + ('timestamp',))
    i = web.input(
      *[spinfield(x) for x in args],
      **dict((spinfield(k), v) for k, v in kwargs.iteritems()))

    for k in ['s', 't']:
        for n in itertools.count():
            fn = 'honeypot_%s%s' % (k, n)
            if spinfield(fn) not in i: break
            mapping[spinfield(fn)] = fn

    newi = web.storage((mapping[k], v) for k, v in i.iteritems() if k in mapping)

    try:
        #assert myspinner == spinner(page_name, newi.timestamp)
        # (not using because we got some odd errors)
        assert int(newi.timestamp) < time.time()
        # assert int(i.timestamp) > (time.time() - 3600)
        # (not using yet because it causes usability loss)
        del newi['timestamp']
        for k in newi.copy():
            assert not k.startswith('honeypot_s')
            if k.startswith('honeypot_t'):
                assert newi[k] == ""
                del newi[k]
    except AssertionError:
        web.badrequest()
        raise StopIteration

    return newi
开发者ID:10sr,项目名称:jottit,代码行数:33,代码来源:auth.py

示例15: _PUT

    def _PUT(self, *param, **params):
        tag_id = param[0]
        if not validates_param_id(self, tag_id):
            self.logger.debug("Failed to update tag. The value of parameter is invalid.")
            return web.badrequest(self.view.alert)

        if not validates_tag(self):
            self.logger.debug("Failed to update tag. The value of input is invalid.")
            return web.badrequest(self.view.alert)

        tag = findby1(self.orm, tag_id)
        if not tag:
            self.logger.debug("Failed to update tag. No such tag - id=%s" % tag_id)
            return web.notfound() 

        cmp_tag = findby1name(self.orm, self.input.name)
        if not cmp_tag is None:
            if cmp_tag.id != tag.id:
                self.logger.debug("Failed to update tag. The same tag already exist - id='%s'" % (cmp_tag.id))
                return web.conflict(web.ctx.path)

        tag.name = self.input.name

        update(self.orm, tag)
        return web.seeother(web.ctx.path)
开发者ID:goura,项目名称:karesansui,代码行数:25,代码来源:tag.py


注:本文中的web.badrequest函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。