本文整理汇总了Python中web.internalerror函数的典型用法代码示例。如果您正苦于以下问题:Python internalerror函数的具体用法?Python internalerror怎么用?Python internalerror使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了internalerror函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: POST
def POST(self):
form = self.form()
if not form.validates():
raise web.internalerror(self.error_message)
filename = form.d.filename
if len(filename) == 0:
filename = form.d.uuid
if not filename.endswith('.tar.gz'):
filename += '.tar.gz'
os.chdir(site['downloads'])
if not os.path.isdir(form.d.uuid):
raise web.internalerror(self.error_message)
try:
subprocess.check_call(['tar', '-zcf', filename, form.d.uuid])
except subprocess.CalledProcessError:
raise web.internalerror('Unable to create tarball.')
try:
shutil.copy(filename, site['pickup'])
except:
raise web.internalerror('Unable to copy tarball to pickup site.')
else:
os.remove(filename)
web.header('Content-Type', 'application/json; charset=utf-8')
return json.dumps({
'uuid': form.d.uuid,
'filename': filename,
'url': pickup_url(),
}, indent=2)
开发者ID:csdms,项目名称:wmt,代码行数:35,代码来源:package.py
示例2: POST
def POST(self):
# Receive the passphrase through query params
query = web.input(
password = None,
maxdays = 10,
maxviews = 10
)
# Change output to JSON
web.header('Content-type', 'application/json')
# Generate unique code for phrase
uuid = uuid4()
phraseCode = str(uuid).split('-')[0]
try:
phraseid = model.add_phrase(
phrase = query.password,
code = base36decode(phraseCode),
maxdays = int(query.maxdays),
maxviews = int(query.maxviews)
)
except(model.ModelError), e:
web.internalerror(str(e))
return json.dumps(dict(error=str(e)))
开发者ID:stemid,项目名称:passwordfrank,代码行数:25,代码来源:api.py
示例3: POST
def POST(self):
''' Handles changing password. '''
chpform = self.chpform()
if not loggedin():
raise web.seeother('/login')
elif not chpform.validates():
return RENDER.changepass(chpform, None)
else:
oldpassword = gethash(chpform['oldpassword'].value)
newpassword = gethash(chpform['newpassword'].value)
if oldpassword == newpassword:
return RENDER.changepass(chpform, 'The new password can not be the same as the new one'.upper())
try:
dbh = web.database(dbn=DBTYPE, db=DBFILENAME)
rows = dbh.select(USERTABLE, what='password',
where='user="{0}"'.format(SESSION.username))
dbupass = rows[0].password
except IndexError:
SESSION.kill()
raise web.internalerror()
except OperationalError:
raise web.internalerror()
if dbupass == oldpassword:
updatepassword(SESSION.username, newpassword)
raise web.seeother('/')
else:
return RENDER.changepass(chpform, 'Password entered wrong'.upper())
开发者ID:hamartin,项目名称:vaktplan,代码行数:30,代码来源:vaktplan.py
示例4: POST
def POST(self):
x = web.input()
print x
global NS
if 'oper' in x.keys() and x['oper'] == "add":
name = x["name"]
m = re.match("^[0-9a-zA-Z_]*$", name)
if not m:
raise web.internalerror(message = "名字格式不对")
try:
size = int(x['size'])
except ValueError:
raise web.internalerror(message = "名字格式不对")
ylvmOpt.create(name, size)
if 'oper' in x.keys() and x['oper'] == "del":
pass
if 'oper' in x.keys() and x['oper'] == "edit":
name = x['name']
m = re.match("^[0-9a-zA-Z_]*$", name)
if not m:
raise web.internalerror(message = "名字格式不对")
try:
size = int(x['size'])
except ValueError:
raise web.internalerror(message = "名字格式不对")
ylvmOpt.resize(name, size)
return x
开发者ID:e42s,项目名称:uss,代码行数:29,代码来源:flvm.py
示例5: POST
def POST(self):
web.header("Content-Type", "text/html")
f = create_repo_form()
if not f.validates():
return render.createRepo(form=f)
v = dict(o=f.d.owner, i=f.d.id)
u = web.config.db.select("repositories", v, where="id=$i and owner=$o", what="id").list()
if len(u) != 0:
return web.internalerror("Invalid repository id. Repository already exists.")
repoPath = os.path.join("repositories", f.d.owner, f.d.id + ".git")
if os.path.exists(repoPath):
print "Repository already exists."
return web.internalerror("Repository already exists.")
web.config.db.query("pragma foreign_keys=ON") # making sure constraints are enforced
transaction = web.config.db.transaction()
try:
web.config.db.insert(
"repositories", id=f.d.id, name=f.d.name, owner=f.d.owner, description=f.d.desc, access=f.d.access
)
# A trigger adds rights to repo_users at this point
os.makedirs(repoPath, 0775)
git.Repo.init(repoPath, bare=True, shared="group")
transaction.commit()
return web.seeother("/%s/%s" % (f.d.owner, f.d.id))
except Exception, e:
transaction.rollback()
print "Exception on repository creation:", e
return web.internalerror("Couldn't create repository")
开发者ID:henningpohl,项目名称:gitweb.py,代码行数:31,代码来源:repositories.py
示例6: _setReturnCode
def _setReturnCode(self, code):
"""Set the return code
:param: code
:type code: integer or string
returns success: [True|False]
"""
success = False
if code in (200, "200", "ok"):
web.ok()
success = True
elif code in (201, "201", "created"):
web.created()
success = True
elif code in (400, "400", "badrequest"):
web.badrequest()
elif code in (401, "401", "unauthorized"):
web.unauthorized()
elif code in (404, "404", "notfound"):
web.notfound()
elif code in (409, "409", "conflict"):
web.conflict()
elif code in (500, "500", "internalerror"):
web.internalerror()
if success:
logging.debug("[LayMan][_setReturnCode] Code: '%s'" % code)
else:
logging.error("[LayMan][_setReturnCode] Code: '%s'" % code)
return success
开发者ID:riskatlas,项目名称:layman,代码行数:32,代码来源:__init__.py
示例7: _DELETE
def _DELETE(self, *param, **params):
host_id = self.chk_hostby1(param)
if host_id is None: return web.notfound()
watch_id = param[1]
if watch_id is None: return web.notfound()
watch = w_findby1(self.orm, watch_id)
w_delete(self.orm, watch)
# delete setting file
plugin = watch.plugin
plugin_selector = watch.plugin_selector
modules = ["collectdplugin"]
host_id = self.chk_hostby1(param)
host = m_findbyhost1(self.orm, host_id)
## read config and delete threashold
extra_args = {'include':'^threshold_'}
dop = read_conf(modules, webobj=self, machine=host, extra_args=extra_args)
if dop is False:
self.logger.debug("Delete watch failed. Failed read conf.")
return web.internalerror('Internal Server Error. (Read Conf)')
delete_threshold(plugin, plugin_selector, dop=dop, webobj=self, host=host)
## apply setting and collectd restart
command = "/etc/init.d/collectd condrestart"
extra_args = {"post-command": command}
retval = write_conf(dop, webobj=self, machine=host, extra_args=extra_args)
if retval is False:
self.logger.debug("Delete watch failed. Failed write conf.")
return web.internalerror('Internal Server Error. (Write Conf)')
return web.accepted()
开发者ID:AdUser,项目名称:karesansui,代码行数:34,代码来源:hostby1watchby1.py
示例8: get_monthly_ts
def get_monthly_ts(self, project, tablename, monthstring, args):
"""
get monthly statistical values
TODO: should be combined with get_lt_ts
"""
index_key_enc = None
value_keyname = None
stat_func_name = "avg"
if len(args) == 2:
index_key_enc, value_keyname = args
else:
index_key_enc, value_keyname, stat_func_name = args
if len(monthstring) != 7:
web.internalerror()
return "monthstring, has to be in YYYY-MM format"
# key_str should be a tuple string, convert to unicode tuple
index_key = tuple([unicode(key_value) for key_value in eval(base64.b64decode(index_key_enc))])
logging.info("index_key : %s", index_key)
logging.info("value_keyname : %s", value_keyname)
logging.info("stat_func_name: %s", stat_func_name)
datalogger = DataLogger(basedir, project, tablename)
filterkeys = dict(zip(datalogger.index_keynames, index_key))
ret_data = []
for datestring in datalogger.monthwalker(monthstring):
logging.debug("getting tsatstats for %s", monthstring)
try:
tsastats = datalogger.load_tsastats(datestring, filterkeys=filterkeys)
ret_data.append([datestring, tsastats[index_key][value_keyname][stat_func_name]])
except DataLoggerRawFileMissing as exc:
logging.error("No Input File for datestring %s found, skipping this date", datestring)
except DataLoggerLiveDataError as exc:
logging.error("Reading from live data is not allowed, skipping this data, and ending loop")
break
return json.dumps(ret_data)
开发者ID:gunny26,项目名称:datalogger,代码行数:35,代码来源:code2.py
示例9: 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
示例10: GET
def GET(self, arg=None):
# Get query params
query = web.input(
bits = 6,
words = 5
)
# Change output to JSON
web.header('Content-type', 'application/json')
# If no pattern at the end of the url,
# we will generate a random password
if not arg:
try:
words = model.get_words(results = 2**int(query.bits))
# Convert iterator
wordlist = []
for word in words:
wordlist.append(word.word)
except(), e:
web.internalerror(str(e))
raise
try:
generatedPass = generate_password(
int(query.words), wordlist
)
except(), e:
web.internalerror(str(e))
raise
开发者ID:stemid,项目名称:passwordfrank,代码行数:30,代码来源:api.py
示例11: GET
def GET(self,_hash):
# check and see if we have the data
try:
data = blobby_handler.get_data(_hash)
except Exception, ex:
# woops, error!
web.internalerror()
开发者ID:rranshous,项目名称:blobby,代码行数:8,代码来源:wsgi.py
示例12: _PUT
def _PUT(self, *param, **params):
host_id = self.chk_hostby1(param)
if host_id is None: return web.notfound()
uni_device = param[1]
if uni_device is None: return web.notfound()
device = uni_device.encode("utf-8")
if not validates_nic(self):
self.logger.debug("Change nic failed. Did not validate.")
return web.badrequest(self.view.alert)
host = findbyhost1(self.orm, host_id)
modules = ["ifcfg"]
dop = read_conf(modules, self, host)
if dop is False:
self.logger.error("Change nic failed. Failed read conf.")
return web.internalerror('Internal Server Error. (Read conf)')
ipaddr = ""
if is_param(self.input, ipaddr):
if self.input.ipaddr:
ipaddr = self.input.ipaddr
netmask = ""
if is_param(self.input, netmask):
if self.input.netmask:
netmask = self.input.netmask
bootproto = self.input.bootproto
onboot = "no"
if is_param(self.input, 'onboot'):
onboot = "yes"
net = NetworkAddress("%s/%s" % (ipaddr,netmask))
network = net.network
broadcast = net.broadcast
if not dop.get("ifcfg", device):
self.logger.error("Change nic failed. Target config not found.")
return web.internalerror('Internal Server Error. (Get conf)')
dop.set("ifcfg",[device,"ONBOOT"] ,onboot)
dop.set("ifcfg",[device,"BOOTPROTO"],bootproto)
dop.set("ifcfg",[device,"IPADDR"] ,ipaddr)
dop.set("ifcfg",[device,"NETMASK"] ,netmask)
if network is not None:
dop.set("ifcfg",[device,"NETWORK"] ,network)
if broadcast is not None:
dop.set("ifcfg",[device,"BROADCAST"],broadcast)
retval = write_conf(dop, self, host)
if retval is False:
self.logger.error("Change nic failed. Failed write conf.")
return web.internalerror('Internal Server Error. (Adding Task)')
return web.accepted(url=web.ctx.path)
开发者ID:AdUser,项目名称:karesansui,代码行数:58,代码来源:hostby1networksettingsnicby1.py
示例13: POST
def POST(self, params):
try:
if params.startswith('statuses/update.'):
web.ctx.data = self.update_filter(web.data())
return BaseProxy.POST(self, params)
except Exception, why:
import traceback
logger.error("%s %s %s" % (params, str(why), web.data()))
logger.error(traceback.format_exc())
web.internalerror()
开发者ID:sinsinpub,项目名称:sin2gae,代码行数:10,代码来源:code.py
示例14: POST
def POST(self, name):
if not name:
raise web.internalerror('500 Invalid Request')
name = self.__preflight(name)
try:
action = web.input()['action']
except:
raise web.internalerror('500 No Action Specified')
if hasattr(self, action):
return getattr(self, action)(name)
raise web.internalerror('500 Invalid Action')
开发者ID:danielsoneg,项目名称:dropWikiHosted,代码行数:11,代码来源:dropWiki.web.py
示例15: internalerror
def internalerror():
referer = web.ctx.env.get('HTTP_REFERER', web.ctx.home)
resp = utils.request('/account/rate_limit_status')
data = json.loads(resp.read())
if data['remaining_hits'] == 0:
referer = referer.replace(web.ctx.home, 'http://m.fanfou.com')
reset_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['reset_time_in_seconds']))
return web.internalerror(render.unrealized(utils.user(), 403, referer, reset_time))
else:
referer = referer.replace(web.ctx.home, '')
return web.internalerror(render.unrealized(utils.user(), 500, referer, ''))
开发者ID:Dungeonlx,项目名称:fanfou,代码行数:11,代码来源:code.py
示例16: POST
def POST(self, group):
userinfo = web.config.db.select("owners", dict(u=group), where="id=$u").list()
if len(userinfo) != 1:
raise web.notfound()
if userinfo[0].type != "group":
raise web.internalerror("Unexpected user type")
postvars = web.input()
if 'type' not in postvars:
return web.badrequest("Invalid parameters")
if postvars.type == 'user':
if 'userid' not in postvars:
return web.badrequest("Invalid parameters")
web.config.db.insert('group_users', groupid=group, userid=postvars.userid, role='member')
elif postvars.type == 'info':
if 'joinable' not in postvars:
return web.badrequest("Invalid parameters")
if 'desc' not in postvars:
postvars.desc = ""
if postvars.joinable not in ["yes", "no"]:
return web.internalerror("Invalid joinable setting")
joinable = 1 if postvars.joinable == "yes" else 0
web.config.db.update('groups', where="id=$g", vars={'g':group}, description=postvars.desc, joinable=joinable)
elif postvars.type == 'remove':
if 'userid' not in postvars:
return web.badrequest("Invalid parameters")
web.config.db.delete('group_users', where="groupid=$g and userid=$u", vars={'g':group, 'u':postvars.userid})
elif postvars.type == 'rights':
if 'userid' not in postvars or 'access' not in postvars:
return web.badrequest("Invalid parameters")
if postvars.access not in ["admin"]:
return web.internalerror("Invalid user right")
web.config.db.update('group_users', where="groupid=$g and userid=$u", vars={'g':group, 'u':postvars.userid}, role='admin')
elif postvars.type == 'delete':
if postvars.confirm != "yes, I really want to delete this group":
return web.seeother("/%s" % owner)
transaction = web.config.db.transaction()
try:
web.config.db.delete('group_users', where="groupid=$g", vars={'g':group})
web.config.db.delete('groups', where="id=$g", vars={'g':group})
except Exception, e:
transaction.rollback()
print e
return web.internalerror("Couldn't delete repository")
transaction.commit()
return web.seeother("/")
开发者ID:henningpohl,项目名称:gitweb.py,代码行数:54,代码来源:browse.py
示例17: JsonGET
def JsonGET(self):
user_data = web.input(q="")
if user_data["q"] == "":
web.badrequest()
return json.dumps([{"Message": "'q' parameter empty"}])
try:
r = IPA.simple_search(user_data['q'])
return json.dumps(r, cls=indicePA.IpaJsonEncoder, indent=4)
except Exception, e:
web.internalerror()
return json.dumps([{"Message": "Error occured: %s" % e}])
开发者ID:pbertera,项目名称:rubripa.it,代码行数:11,代码来源:search.py
示例18: protect
def protect(what, *a, **kw):
try:
return what(*a, **kw) or ""
except (IOError, OSError) as e:
if e.errno in [EACCES, ENOTDIR]:
forbidden()
else:
internalerror()
return str(e)
except CalledProcessError as e:
internalerror()
return str(e)
开发者ID:itayd,项目名称:w,代码行数:12,代码来源:common.py
示例19: POST
def POST(self):
postdata = web.input()
if len(itbf.queue.get_copy()) > 100:
# defend against people flooding the queue
errmsg = "Too many jobs! Geez."
web.internalerror(message=errmsg)
return { 'error': errmsg }
itbf.queue.append_job(postdata['tree'], postdata['revision'],
postdata['submitter_email'], postdata['return_email'])
return { 'num_pending_jobs': len(itbf.queue.get_copy()) }
开发者ID:ctalbert,项目名称:gofaster_dashboard,代码行数:12,代码来源:handlers.py
示例20: GET
def GET(self, optionsConcatenated):
try:
wh = []
specificId = None
optionList = []
for option in optionsConcatenated.split("/"):
if not option:
continue
if option.isdigit():
wh.append( int(option) )
elif option.startswith("m"):
specificId = int( option[1:] )
else:
optionList.append( option )
if len( wh ) == 0:
w = h = 640
elif len( wh ) == 1:
w = h = wh[0]
else:
assert len( wh ) == 2
w, h = wh
optionString = "".join( map( map_option, optionList ) )
except:
raise web.internalerror( render.error( "error parsing arguments" ) )
try:
if not specificId:
manul = select_random_manul( findfiles(), w, h )
else:
manul = findfiles()[ specificId ]
fn = filename( manul.filename, w, h, optionString )
except:
if specificId:
raise web.internalerror( render.error( "manul not found" ) )
else:
raise web.internalerror( render.error( "manul not found (requested resolution may be too high)" ) )
try:
if not os.path.exists( cachedDir + fn ):
convert( Image.open( sourceDir + manul.filename ), manul, w, h, optionString, cachedDir + fn )
except:
raise web.internalerror( render.error( "error processing manul" ) )
path = cachedDir + fn
mtime = os.stat( path ).st_mtime
if web.http.modified( date = datetime.datetime.fromtimestamp(mtime) ):
try:
with open( path, "rb" ) as f:
data = f.read()
web.header( "Content-Type", "image/jpeg" )
return data
except:
raise web.internalerror( render.error( "error retrieving manul" ) )
开发者ID:svk,项目名称:placemanul,代码行数:50,代码来源:placemanul.py
注:本文中的web.internalerror函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论