• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python web.badrequest函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: yzImage

def yzImage ( imageargs, dbcfg ):
  """Return an xz plane fileobj.read()"""

  restargs = imageargs.split('/')

  if len ( restargs ) == 5:
    [ resstr, xstr, ydimstr, zdimstr, rest ]  = restargs
    globalcoords = False
  elif len ( restargs ) == 6:
    [ resstr, xstr, ydimstr, zdimstr, rest, other ]  = restargs
    globalcoords = True
  else:
    return web.badrequest()

  # expecting an argument of the form /resolution/x/y1,y2/z1,z2/
  # Check that the arguments are well formatted
  if not re.match ('[0-9]+$', xstr) or\
     not re.match ('[0-9]+,[0-9]+$', ydimstr) or\
     not re.match ('[0-9]+,[0-9]+$', zdimstr) or\
     not re.match ('[0-9]+$', resstr ):
    return web.badrequest()

  y1s,y2s = ydimstr.split(',')
  z1s,z2s = zdimstr.split(',')

  x = int(xstr)
  y1i = int(y1s)
  y2i = int(y2s)
  z1i = int(z1s)
  z2i = int(z2s)

  resolution = int(resstr)

  # Convert to local coordinates if global specified
  if ( globalcoords ):
    x = int ( float(x) / float( 2**(resolution-dbcfg.baseres)))
    y1i = int ( float(y1i) / float( 2**(resolution-dbcfg.baseres)))
    y2i = int ( float(y2i) / float( 2**(resolution-dbcfg.baseres)))


  #RBTODO need to make a dbconfig object 
  # Check arguments for legal values
  if not dbcfg.checkCube ( resolution, x, x, y1i, y2i, z1i, z2i  )\
     or  x >= dbcfg.imagesz[resolution][0]:
    return web.notfound()

  corner=[x,y1i,z1i-dbcfg.slicerange[0]]
  dim=[1,y2i-y1i,z2i-z1i ]

  try:
    annodb = anndb.AnnotateDB ( dbcfg )
    cb = annodb.cutout ( corner, dim, resolution )
    fileobj = StringIO.StringIO ( )
    cb.yzSlice ( dbcfg.zscale[resolution], fileobj )
  except:
    return web.notfound()

  web.header('Content-type', 'image/png') 
  fileobj.seek(0)
  return fileobj.read()
开发者ID:pmanava1,项目名称:EM-connectome,代码行数:60,代码来源:annrest.py


示例17: _POST

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

        if not validates_mail(self):
            self.logger.debug("Update mail setting failed. Did not validate.")
            return web.badrequest(self.view.alert)

        hostname = self.input.hostname
        port     = self.input.port
        if not port:
            port = "25"

        if hostname:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5.0)
            try:
                sock.connect((hostname, int(port)))
            except Exception, e:
                self.logger.error("Could not connect to specified MTA \n%s" % e)
                """
                TRANSLATORS:
                MTA設定の際に実際に指定したホスト名/ポート番号に接続ができる
                かチェックし、接続できなかった。
                """
                return web.badrequest(_("Could not connect to specified MTA \n%s" % e))
开发者ID:goura,项目名称:karesansui,代码行数:26,代码来源:hostby1settingby1mail.py


示例18: POST

    def POST(self):
        try:
            data = web.input()
            for field, schema in self.schema.iteritems():
                if field not in data:
                    if 'default' in self.schema[field]:
                        data[field] = self.schema[field]['default']
                    else:
                        web.badrequest()
                        return

        except AttributeError:
            pass
        else:
            # Process the logfile
            snapshot = NetworkTrafficSnapshot()
            snapshot.upload(data['title'], data['description'], data['logfile_name'], data['logfile_content'])
            snapshot_id = snapshot.save()

            # Process the statistics
            snapshot.generate_statistics()

            # Process the transactions
            transactions = SipTransactions()
            transactions.extract(snapshot_id)
            transactions.save()

            # Process the dialogs
            dialogs = SIPDialogs()
            dialogs.extract(snapshot_id)
            dialogs.save()

            return snapshot_id
开发者ID:carlchipperfield,项目名称:final_year_project,代码行数:33,代码来源:api.py


示例19: _PUT

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

        if not validates_user(self):
            self.logger.debug("Failed to update account. the value of input is invalid.")
            return web.badrequest(self.view.alert)

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

        cmp_user = findby1email(self.orm, self.input.email)
        if not cmp_user is None:
            if int(user_id) != cmp_user.id:
                self.logger.debug("Failed to update account. The same mail address '%s' already exist - user='%s'" % (self.input.email, cmp_user.nickname))
                return web.conflict(web.ctx.path)

        user.nickname = self.input.nickname
        user.email = self.input.email
        user.languages = self.input.languages

        if not is_empty(self.input.new_password):
            if compare_password(self, user) == False:
                return web.badrequest(self.view.alert)

            (password, salt) = sha1encrypt(self.input.new_password)
            user.password = password
            user.salt = salt

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


示例20: POST

    def POST(self):

        try:
            parameters = web.input()

            if (not parameters.has_key('TM_LOGIN')):
                return web.badrequest()
            login = parameters.get('TM_LOGIN')
            
            if (not parameters.has_key('TM_PASSWORD')):
                return web.badrequest()
            password = parameters.get('TM_PASSWORD')
            
            if (not parameters.has_key('to')):
                return web.badrequest()
            to = parameters.get('to')
                   
            if (not parameters.has_key('message')):
                return web.badrequest()
            message = parameters.get('message')

            smsender=APISMS.SMSSenderAPI()
            response = smsender.sendSMS(login, password, to, message)

            if response.find('OK')>=0:
                print "<html><body><span style='font-weight: bold;font-size:11pt;color:#225784;'>SMS sent succesfully!</span></body></html>"
                return
            web.ctx.status = "500 Internal Server Error"
            web.ctx.headers = [('Content-Type', 'text/html')]
            web.ctx.output = response
            return
        except Exception, e:
            web.ctx.status = "500 Internal Server Error"
            web.ctx.headers = [('Content-Type', 'text/html')]
            web.ctx.output = "<html><body>Error: %s.</body></html>" % e
开发者ID:conwetlab,项目名称:ezweb-gadgets,代码行数:35,代码来源:SMSSenderSrv.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python web.changequery函数代码示例发布时间:2022-05-26
下一篇:
Python web.application函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap