本文整理汇总了Python中pyramid.response.Response.status_code方法的典型用法代码示例。如果您正苦于以下问题:Python Response.status_code方法的具体用法?Python Response.status_code怎么用?Python Response.status_code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.response.Response
的用法示例。
在下文中一共展示了Response.status_code方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_path
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def update_path(self, id_doc, path, value):
"""
Update base in proposed path
"""
response = Response(content_type='application/json')
url = self.lbgenerator_rest_url + '/' + self.lbbase.metadata.name + '/doc/' + id_doc
url = url + '/' + path
params = {
'value': value
}
result = requests.put(
url=url,
data=params
)
if result.status_code >= 300:
response.status_code = 500
response.text = result.text
return response
response.status_code = 200
response.text = result
return response
示例2: post
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def post(self):
resp = Response(json.dumps({}), content_type='application/json')
resp.status_code = 403
if self.validate():
email = self.payload['email']
password = self.payload['password']
self.user = Users.authenticate(email, password)
print(email, password, self.user)
if self.auth():
self.request.session['token'] = self.user.token
_user = self.user.to_dict()
_user.update(token=self.user.token)
#resp = _user
resp = Response(json.dumps(_user), content_type='application/json')
resp.status_code = 200
return resp
示例3: upload
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def upload(request):
if request.content_length/1000000 > 20:
return error_response(400, 'Sorry, but the file must be under 20MB.')
# Create photo object in database
photo = Photo(datetime.today(), request.POST['file'].filename, request.client_addr, request.content_type, request.content_length)
DBSession.add(photo)
DBSession.flush()
# Save uploaded file
input_file = request.POST['file'].file
input_file.seek(0)
if not os.path.exists('data'):
os.makedirs('data')
if not os.path.exists('data/uploads'):
os.makedirs('data/uploads')
upload_path = os.path.join('data', 'uploads', str(photo.id))
with open(upload_path, 'w') as f:
shutil.copyfileobj(input_file, f)
# Check the content type and rename as appropriate
mime = magic.from_file(upload_path, mime=True)
if mime not in ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/tiff', 'image/x-tiff']:
resp = Response('Sorry, but we can only accept jpg, gif, or png files.')
resp.status_code = 400
resp.status_string = '400 Bad Request'
return resp
extension = {'image/jpeg': '.jpg', 'image/pjpeg': '.jpg',
'image/gif': '.gif', 'image/png': '.png',
'image/tiff': '.tiff', 'image/x-tiff': '.tiff'}[mime]
os.rename(upload_path, upload_path + extension)
photo.content_type = mime
return Response('OK')
示例4: internal_server_error
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def internal_server_error(context, request):
"""Generate the default internal server error page when exception falls through from a view.
This view is marked as CSRF exempt, so that HTTP POST requests to API endpoints do not cause additional Bad CSRF exception when HTTP 500 Internal server error is raised.
Also see https://github.com/Pylons/pyramid_tm/issues/40
"""
request.registry.notify(InternalServerError(context, request))
if asbool(request.registry.settings.get("websauna.log_internal_server_error", True)):
logger.exception(context)
request.user = None
# The template rendering opens a new transaction which is not rolled back by Pyramid transaction machinery, because we are in a very special view. This tranasction will cause the tests to hang as the open transaction blocks Base.drop_all() in PostgreSQL. Here we have careful instructions to roll back any pending transaction by hand.
transaction.abort() # https://github.com/Pylons/pyramid_tm/issues/40
html = render('core/internalservererror.html', {}, request=request)
resp = Response(html)
resp.status_code = 500
# Do it again in the case rendering starts another TX
transaction.abort() # https://github.com/Pylons/pyramid_tm/issues/40
return resp
示例5: forbidden
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def forbidden(request):
# The template rendering opens a new transaction which is not rolled back by Pyramid transaction machinery, because we are in a very special view. This tranaction will cause the tests to hang as the open transaction blocks Base.drop_all() in PostgreSQL. Here we have careful instructions to roll back any pending transaction by hand.
html = render('core/forbidden.html', {}, request=request)
resp = Response(html)
resp.status_code = 403
transaction.abort()
return resp
示例6: remove_file
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def remove_file(self, id_doc, id_file):
"""
Remove image from base
"""
# First gets document
document = self.get_document(id_doc)
# Now create a new image dict removing selected files
new_image = list()
for image in document.get('images'):
if image['id_file'] != id_file:
new_image.append(image)
# Finally update document and submit it back to base
document['images'] = new_image
response = Response(content_type='application/json')
try:
log.debug(document)
result = self.update_document(id_doc, document)
except HTTPError as e:
response.status_code = 500
response.text = e.message
return response
# TODO: Not yet implemented. Need fix
# Now remove file from database
#url = self.lbgenerator_rest_url + '/' + self.lbbase._metadata.name + '/' + id_file
#result = requests.delete(
# url=url
#)
#if result.status_code >= 300:
# response.status_code = result.status_code
# response.text = result.text
# return response
response.status_code = 200
response.text = result
return response
示例7: assertion_failure
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def assertion_failure(exc, request):
if request.is_xhr:
if '/edit/' in request.path:
response = Response(exc.message)
response.status_code = 500
return response
else:
return {'error': exc.message,
'assert_error': True}
request.session.flash(exc.message, 'error')
return HTTPFound(location=request.referer or '/')
示例8: insert_images
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def insert_images(self):
"""
Insert image on document
:return:
"""
id_doc = self.request.matchdict.get('id_doc')
image = self.request.params.get('image')
if id_doc is None or image is None:
log.error("id_doc and image required")
raise HTTPBadRequest
response = Response(content_type='application/json')
# Primeiro insere o documento
result = self.crimes_base.upload_file(image)
log.info("Status code: %s", result.status_code)
if result.status_code >= 300:
log.error("Erro na insercao!\n%s", result.text)
response.status_code = result.status_code
response.text = result.text
return response
file_dict = json.loads(result.text)
#file_dict['filename'] = image.filename
#file_dict['mimetype'] = image.type
log.debug("UUID para arquivo gerado: %s", file_dict)
result = self.crimes_base.update_file_document(id_doc, file_dict)
if result.status_code >= 300:
log.error("Erro na atualização da imagem %s", result.text)
response.status_code = 500
response.text = result.text
return response
response.status_code = 200
response.text = result.text
return response
示例9: internal_server_error
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def internal_server_error(context, request):
"""Generate the default internal server error page when exception falls through from a view.
This view is marked as CSRF exempt, so that HTTP POST requests to API endpoints do not cause additional Bad CSRF exception when HTTP 500 Internal server error is raised.
Also see https://github.com/Pylons/pyramid_tm/issues/40
"""
# Here we have a hardcoded support for Sentry exception logging and pyramid_raven package
# https://github.com/thruflo/pyramid_raven
if hasattr(request, "raven"):
user = getattr(request, "user", None)
user_context = {}
try:
if user:
# Add additional user context to the logged exception
username = getattr(user, "friendly_name", None) or getattr(user, "username", None) or str(user)
email = getattr(user, "email", None)
user_context.update(dict(user=username, email=email))
# All the session data
session = getattr(request, "session", None)
if session:
session = dict(session.items())
user_context.update(dict(session=session))
else:
user_context.update(dict(session="No session data available in internal_server_error()"))
except Exception as e:
logger.error("FAiled to Gather user and session data")
logger.exception(e)
request.raven.user_context(user_context)
request.raven.captureException()
if request.registry.settings.get("websauna.log_internal_server_error", True):
logger.exception(context)
# The template rendering opens a new transaction which is not rolled back by Pyramid transaction machinery, because we are in a very special view. This tranaction will cause the tests to hang as the open transaction blocks Base.drop_all() in PostgreSQL. Here we have careful instructions to roll back any pending transaction by hand.
html = render('core/internalservererror.html', {}, request=request)
resp = Response(html)
resp.status_code = 500
transaction.abort() # https://github.com/Pylons/pyramid_tm/issues/40
return resp
示例10: integrity_error
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def integrity_error(exc, request):
logging.error('DB Integrity error:', exc_info=1)
msg = exc.message
if hasattr(exc, 'orig'):
body = str(exc.orig).split(' ')
msg = ' '.join(body[2:])
field = body[1]
table = None
errors_by_table = {'tag': 'A tag with the same "Name" and "Type to show tag on" exists already. '
'There can only be one tag with the same name for each type.'}
errors_by_constraint = {
'tag_x_founder_tag_id_fkey': 'You must delete all the uses of the tag before you can delete the tag'}
if hasattr(exc.orig, 'diag'):
field = exc.orig.diag.column_name
table = exc.orig.diag.table_name
constraint = exc.orig.diag.constraint_name
if errors_by_constraint.get(constraint):
msg = errors_by_constraint[constraint]
elif errors_by_table.get(table):
msg = errors_by_table[table]
elif table == 'user':
try:
orig = 'Another user already has the same %s' % field
if field in ['linkedin', 'username']:
orig = 'An user is already connected with your LinkedIn account, please go to <a href="/">login</a>'
except:
orig = 'Similar user already exists: %s' % orig
msg = orig
elif field:
msg = 'Duplicate entry for %s' % field
if request.is_xhr:
if '/edit/' in request.path:
response = Response(msg)
response.status_code = 500
return response
else:
return {'error': msg,
'assert_error': True}
request.session.flash(msg or exc, 'error')
return HTTPFound(location=request.referer or '/')
示例11: notmodified_tween
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def notmodified_tween(request):
if os.path.isfile(lock_file):
response = Response(render('templates/maintenance.jinja2',
{},
request))
response.status_code = 503
return response
if (request.if_modified_since is not None and
request.if_modified_since >=
publication_date.replace(microsecond=0)):
return HTTPNotModified()
response = handler(request)
response.last_modified = publication_date
return response
示例12: notfound
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def notfound(request):
"""Not found view which will log the 404s in the site error log."""
# Try to extract some more information from request
user = getattr(request, "user", None)
if user:
username = getattr(user, "friendly_name", "<unknown>")
else:
username = "<anomymous>"
logger.warn("404 Not Found. user:%s URL:%s referrer:%s", request.url, username, request.referrer)
# Make sure 404 page does not have any status information, as it is often overlooked special case for caching and we don't want to cache user information
request.user = None
# The template rendering opens a new transaction which is not rolled back by Pyramid transaction machinery, because we are in a very special view. This tranaction will cause the tests to hang as the open transaction blocks Base.drop_all() in PostgreSQL. Here we have careful instructions to roll back any pending transaction by hand.
html = render('core/notfound.html', {}, request=request)
resp = Response(html)
resp.status_code = 404
transaction.abort()
return resp
示例13: controllerInternalView
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def controllerInternalView(request):
url = request.matchdict.get('controller_path', '')
path = url.split('/')
path = deque(path)
response = Response()
context = Context(request, response)
for segment, handler, endpoint, *meta in dispatch(context, controller, path):
if(endpoint and not callable(handler)):
raise HTTPNotFound('No endpoint found.')
if endpoint:
view_output = handler(*path)
if isinstance(view_output, str):
response.text = view_output
elif isinstance(view_output, Iterable):
response.app_iter = view_output
return response
response.status_code = 404
response.status = '404 Not Found'
return response
示例14: error_response
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import status_code [as 别名]
def error_response(code, msg):
status = {400: '400 Bad Request', 500: '500 Internal Server Error'}[code]
resp = Response(msg)
resp.status_code = code
resp.status_string = status
return resp