本文整理汇总了Python中werkzeug.wrappers.Response.status_code方法的典型用法代码示例。如果您正苦于以下问题:Python Response.status_code方法的具体用法?Python Response.status_code怎么用?Python Response.status_code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.wrappers.Response
的用法示例。
在下文中一共展示了Response.status_code方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: application
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def application(request):
root_dir = os.getcwd()
path = request.path # todo: make sure path is sandboxed!
if path in ('', '/'):
path = '/index.html'
# todo: if path is a directory, append index.html to template name
env = Environment(loader=FileSystemLoader(root_dir))
response = Response()
response.status_code = 200
response.content_type = 'text/html; charset=utf-8'
## Try to get the template
try:
template = env.get_template(path)
except TemplateNotFound:
response.status_code = 404
try:
template = env.get_template('404.html')
except TemplateNotFound:
response.content_type = 'text/plain'
template = Template("PAGE NOT FOUND")
## Prepare and send the response
rendered = template.render(request=request, response=response)
response.set_data(rendered)
return response
示例2: __call__
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def __call__(self, environ, start_response):
path = environ.get('PATH_INFO') or '/'
method = environ.get('REQUEST_METHOD')
request = Request(environ)
response = Response()
if method == 'POST': # trap all post requests for example
content_type_header = request.headers.get('Content-Type')
if not content_type_header:
response.status_code = 405
return response(environ, start_response)
transport = TIOStreamTransport(request.stream, response.stream)
if 'application/x-thrift' in content_type_header:
protocol = TBinaryProtocol.TBinaryProtocol(transport)
elif 'application/json' in content_type_header:
protocol = TJSONProtocol.TJSONProtocol(transport)
else:
response.status_code = 405
return response(environ, start_response)
self.bb_processor.process(protocol, protocol)
return response(environ, start_response)
else:
return self.app(environ, start_response)
示例3: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def wsgi_app(self, environ, start_response):
"""Execute this instance as a WSGI application.
See the PEP for the meaning of parameters. The separation of
__call__ and wsgi_app eases the insertion of middlewares.
"""
urls = self._url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
except HTTPException as exc:
return exc
assert endpoint == "rpc"
response = Response()
if self._auth is not None and not self._auth(environ):
response.status_code = 403
response.mimetype = "plain/text"
response.data = "Request not allowed."
return response
request = Request(environ)
request.encoding_errors = "strict"
remote_service = ServiceCoord(args['service'], args['shard'])
if remote_service not in self._service.remote_services:
return NotFound()
# TODO Check content_encoding and content_md5.
if request.mimetype != "application/json":
return UnsupportedMediaType()
if request.accept_mimetypes.quality("application/json") <= 0:
return NotAcceptable()
try:
data = json.load(request.stream, encoding='utf-8')
except ValueError:
return BadRequest()
if not self._service.remote_services[remote_service].connected:
return ServiceUnavailable()
result = self._service.remote_services[remote_service].execute_rpc(
args['method'], data)
# XXX We could set a timeout on the .wait().
result.wait()
response.status_code = 200
response.mimetype = "application/json"
response.data = json.dumps({
"data": result.value,
"error": None if result.successful() else "%s" % result.exception})
return response
示例4: dispatch
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def dispatch(self, request):
if request.path not in ('/', self.login_url):
return redirect('')
if request.path == self.login_url:
if request.is_somebody:
return redirect('')
elif request.authorization:
if 'username' in request.authorization:
username = request.authorization.get('username')
password = request.authorization.get('password')
user = self.app.database_engine.execute(
users.select(users.c.username==username)
).fetchone()
if user and check_pwhash(user.pw_hash, password):
request.session['uid'] = user.user_id
request.session['lt'] = time()
request.is_somebody = True
return redirect('')
response = Response()
response.www_authenticate.set_basic()
response.status_code = 401
return response
if not request.is_admin:
response = render_response(request, 'upgrade_maintenance.html',
login_url=self.login_url)
response.status_code = 503
return response
if request.method == 'POST':
open(self.lockfile, 'w').write('locked on database upgrade\n')
mdb = ManageDatabase(request.app)
db.session.close() # close open sessions
def finish():
# this is run from the template after the upgrade finishes
remove(self.lockfile)
db.session.close() # close open sessions
self.wants_reload = True # force application reload
return '' # just because I need to return something to jinja
return render_response(request, 'admin/perform_upgrade.html',
live_log=mdb.cmd_upgrade(), _stream=True,
finish=finish, blog_url=self.blog_url,
maintenance_url=self.maintenance_url,
in_progress=False)
return render_response(request, 'admin/perform_upgrade.html',
in_progress=isfile(self.lockfile),
repo_ids=self.repo_ids)
示例5: flag_status
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def flag_status(self, request, flag):
response = Response(content_type='application/json')
response.headers.add_header(
'Cache-Control', 'no-cache, no-store, must-revalidate')
try:
active = self._backend.is_active(flag)
response.data = json.dumps({
'active': bool(active), 'known': True})
response.status_code = 200
return response
except UnknownFeatureError:
response.data = json.dumps({
'active': False, 'known': False})
response.status_code = 404
return response
示例6: get_file_response
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def get_file_response(self, path, request):
try:
full_path = find_file(self.search_paths, path)
if full_path is None:
raise NotFound()
file_obj = open(full_path, 'rb')
mtime = get_file_mtime(full_path)
fsize = os.path.getsize(full_path)
except (ValueError, IOError, OSError):
raise Forbidden()
mimetype, encoding = mimetypes.guess_type(full_path)
if not mimetype:
peeked = peek_file(file_obj, 1024)
is_binary = is_binary_string(peeked)
if peeked and is_binary:
mimetype = self.default_binary_mime
else:
mimetype = self.default_text_mime # TODO: binary
resp = Response('')
cached_mtime = request.if_modified_since
if self.cache_timeout:
resp.cache_control.public = True
if mtime == cached_mtime:
file_obj.close()
resp.status_code = 304
resp.cache_control.max_age = self.cache_timeout
return resp
file_wrapper = request.environ.get('wsgi.file_wrapper', FileWrapper)
resp.response = file_wrapper(file_obj)
resp.content_type = mimetype
resp.content_length = fsize
resp.last_modified = mtime
return resp
示例7: application
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def application(request):
if request.method == 'GET':
path = list(filter((lambda x: len(x) > 0), re.split('/+', request.path)))
if len(path) == 0:
return view_root(request)
elif len(path) >= 1 and path[0] == 'messages':
if len(path) == 1:
return view_messages_list(request)
elif len(path) == 2:
return view_message(request, path[1])
elif len(path) == 3 and path[2] == 'editor':
return edit_message(request, path[1])
else:
return NotFound()
elif len(path) >= 1 and path[0] == 'services':
if len(path) == 1:
return view_services_list(request)
elif len(path) == 2:
return view_ports_list(request, path[1])
elif len(path) == 3:
return view_operations_list(request, path[1], path[2])
else:
return NotFound()
else:
return NotFound()
elif request.method == 'POST':
return Response('post')
else:
response = Response()
response.status_code = 400
return response
示例8: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def wsgi_app(self, environ, start_response):
route = self.router.bind_to_environ(environ)
try:
endpoint, args = route.match()
except HTTPException as exc:
return exc(environ, start_response)
assert endpoint == "sublist"
request = Request(environ)
request.encoding_errors = "strict"
if request.accept_mimetypes.quality("application/json") <= 0:
raise NotAcceptable()
result = list()
for task_id in self.task_store._store.keys():
result.extend(
self.scoring_store.get_submissions(
args["user_id"], task_id
).values()
)
result.sort(key=lambda x: (x.task, x.time))
result = list(a.__dict__ for a in result)
response = Response()
response.status_code = 200
response.mimetype = "application/json"
response.data = json.dumps(result)
return response(environ, start_response)
示例9: application
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def application(request):
logger = logging.getLogger('presence_detection')
logger.setLevel(logging.INFO)
fh = logging.FileHandler(os.path.expanduser('~/presence2/log/presence_detection.log'),mode='a', encoding=None, delay=False)
formatter = logging.Formatter('%(asctime)s - %(levelname)r - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
rsa_key='AAAAB3NzaC1yc2EAAAADAQABAAAAgwCjvHkbqL/V0ytnfa5pIak7bxBfj6nF4S7vy51ZG8LlWYAXcQ9WGfUGfhG+l1GW9hPeQzQbeRyNiQM+ufue/M9+JKCXTIugksAnN3W+NV/DeDcq9sKR9MiiNH3ZeNtGSyPGYjcLVmK6aSVTUoEO2yRrha9fiWBy5hb93UdmJX+QguC9'
router_address='makerbar.berthartm.org'
router_port = 2222
stdin, stdout, stderr =get_router_mac_addresses(rsa_key,router_address,router_port)
usermap = get_dict()
attendance = set()
for line in stdout:
MAC = line[10:27]
if MAC in usermap:
attendance.add(usermap[MAC])
logger.info('%s (%s) is at the MakerBar.' % (usermap[MAC],MAC))
else:
logger.info('Unknown user(%s) is at the MakerBar.' % MAC)
output = ''
for user in attendance:
output += user + '\n'
response = Response(output)
if output == '':
response.status_code = 204 # No content
fh.close()
return response
示例10: dbfile_handler
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def dbfile_handler(self, environ, args):
try:
fobj = self.file_cacher.get_file(args['digest'])
except KeyError:
raise NotFound()
response = Response()
response.status_code = 200
response.mimetype = 'application/octet-stream'
if 'name' in args:
if args["name"].endswith(".pdf"):
# Add header to allow the official pdf.js to work
response.headers.add_header(b'Access-Control-Allow-Origin',
b'https://mozilla.github.io')
else:
# Don't do this on pdf files because it breaks the native pdf reader
response.headers.add_header(
b'Content-Disposition', b'attachment',
filename=args['name'])
mimetype = mimetypes.guess_type(args['name'])[0]
if mimetype is not None:
response.mimetype = mimetype
response.response = wrap_file(environ, fobj)
response.direct_passthrough = True
response.cache_control.max_age = 31536000
response.cache_control.public = True
return response
示例11: dispatch_request
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def dispatch_request(self, urls, request):
"""Dispatch the incoming *request* to the given view function or class.
If the "request" is a socket.io message, route it to the registered
namespace.
:param urls: The URLs parsed by binding the URL map to the environment.
:param request: The current HTTP request.
:type request :class:`werkzeug.Request`:
"""
if request.path.startswith('/socket.io'):
try:
socketio_manage(request.environ, self._namespaces, request)
except:
print("Exception while handling socketio connection")
return Response()
else:
response = urls.dispatch(
lambda e, v: self._routes[e](
request, **v))
if isinstance(response, (unicode, str)):
headers = {'Content-type': 'text/html'}
response = Response(response, headers=headers)
if not response:
headers = {'Content-type': 'text/html'}
response = Response('404 Not Found', headers=headers)
response.status_code = 404
return response
示例12: run_application
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def run_application(self, environment: dict, start_response: typing.Callable) -> asyncio.Task:
"""
Runs Kyoukai for the current request.
This is **not** a coroutine - it returns a single item (a Task), which is awaited on to get
the response.
:param environment: The WSGI environment to run this request with.
:param start_response: A callable that can be used to start the response.
:return: A new :class:`asyncio.Task` that can be awaited on to get a response from the \
application.
"""
is_async = environment.get("wsgi.async", False)
if not is_async:
# Damnit. Return a WSGI response that ells the user they're stupid.
r = Response("<h1>Error</h1><br/>You did not use the <code>gaiohttp</code> "
"gunicorn worker. This is an "
"error! Please switch to the gaiohttp worker instead.")
r.headers["Content-Type"] = "text/html; charset=utf-8"
r.status_code = 500
return r(environment, start_response)
coro = self._run_application(environment, start_response)
loop = asyncio.get_event_loop()
t = loop.create_task(coro)
environment["kyoukai.task"] = t
return t
示例13: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def wsgi_app(self, environ, start_response):
"""Execute this instance as a WSGI application.
See the PEP for the meaning of parameters. The separation of
__call__ and wsgi_app eases the insertion of middlewares.
"""
urls = self._url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
except HTTPException as exc:
return exc
assert endpoint == "get"
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
result = dict()
for task_type in self._task_types:
result[task_type.__name__] = \
list(p.describe() for p in task_type.ACCEPTED_PARAMETERS)
response.status_code = 200
response.mimetype = "application/json"
response.data = json.dumps(result)
return response
示例14: __get_response
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def __get_response(self, environ, args, kwargs, endpoint):
if endpoint.__name__ == "service_check":
result = endpoint(*args, **kwargs)
response = Response(result['body'])
response.status_code = result['status']
return response
response = {
'server_info': {
'http_headers': dict(EnvironHeaders(environ)),
'response_id': 0,
'arguments': repr(args) if args else repr(kwargs),
'processing_time': 0.0
},
'response': {}
}
start_time = time.time()
# Make the call
result = endpoint(*args, **kwargs)
# Send the API call response
response['response'] = result
response['server_info']['processing_time'] = 1000*(time.time() - start_time)
try:
response = json.dumps(response)
except (TypeError, UnicodeError):
return InternalServerError(description = "Could not encode service response")
response = Response(response)
response.headers['content-type'] = 'application/json'
return response
示例15: response
# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import status_code [as 别名]
def response(self):
try:
return self._getStaticResponse()
except (OSError, IOError):
rs = Response('Not found')
rs.status_code = 404
return rs