Here are the examples of the python api aiohttp.web.HTTPInternalServerError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
23 Examples
3
Example 1
@asyncio.coroutine
def forget(request, response):
"""Forget previously remembered identity.
Usually it clears cookie or server-side storage to forget user
session.
"""
identity_policy = request.app.get(IDENTITY_KEY)
if identity_policy is None:
text = ("Security subsystem is not initialized, "
"call aiohttp_security.setup(...) first")
# in order to see meaningful exception message both: on console
# output and rendered page we add same message to *reason* and
# *text* arguments.
raise web.HTTPInternalServerError(reason=text, text=text)
yield from identity_policy.forget(request, response)
3
Example 2
def test_fail_transport(self):
request = self.make_request(
'GET', '/sm/',
match_info={
'transport': 'test', 'session': 'session', 'server': '000'})
params = []
class Transport:
def __init__(self, manager, session, request):
params.append((manager, session, request))
def process(self):
raise Exception('Error')
route = self.make_route(handlers={'test': (True, Transport)})
res = self.loop.run_until_complete(route.handler(request))
self.assertIsInstance(res, web.HTTPInternalServerError)
3
Example 3
@asyncio.coroutine
def delete(self):
"""
Delete the VM (including all its files).
"""
def set_rw(operation, name, exc):
os.chmod(name, stat.S_IWRITE)
directory = self.project.vm_working_directory(self)
if os.path.exists(directory):
try:
yield from wait_run_in_executor(shutil.rmtree, directory, onerror=set_rw)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not delete the VM working directory: {}".format(e))
3
Example 4
@classmethod
def _get_default_project_directory(cls):
"""
Return the default location for the project directory
depending of the operating system
"""
server_config = Config.instance().get_section_config("Server")
path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects"))
path = os.path.normpath(path)
try:
os.makedirs(path, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e))
return path
3
Example 5
def module_working_directory(self, module_name):
"""
Returns a working directory for the module
If the directory doesn't exist, the directory is created.
:param module_name: name for the module
:returns: working directory
"""
workdir = self.module_working_path(module_name)
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create module working directory: {}".format(e))
return workdir
3
Example 6
def vm_working_directory(self, vm):
"""
Returns a working directory for a specific VM.
If the directory doesn't exist, the directory is created.
:param vm: VM instance
:returns: VM working directory
"""
workdir = os.path.join(self._path, "project-files", vm.manager.module_name.lower(), vm.id)
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create the VM working directory: {}".format(e))
return workdir
3
Example 7
def capture_working_directory(self):
"""
Returns a working directory where to store packet capture files.
:returns: path to the directory
"""
workdir = os.path.join(self._path, "project-files", "captures")
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create the capture working directory: {}".format(e))
return workdir
3
Example 8
def _check_windows_service(service_name):
import pywintypes
import win32service
import win32serviceutil
try:
if win32serviceutil.QueryServiceStatus(service_name, None)[1] != win32service.SERVICE_RUNNING:
return False
except pywintypes.error as e:
if e.winerror == 1060:
return False
else:
raise aiohttp.web.HTTPInternalServerError(text="Could not check if the {} service is running: {}".format(service_name, e.strerror))
return True
3
Example 9
def test_project_delete_permission_issue(loop):
project = Project()
directory = project.path
assert os.path.exists(directory)
os.chmod(directory, 0)
with pytest.raises(aiohttp.web.HTTPInternalServerError):
loop.run_until_complete(asyncio.async(project.delete()))
os.chmod(directory, 700)
3
Example 10
def _config_error(request):
try:
formatter = request.match_info.route.resource.get_info()['formatter']
msg = ('Bad AIOHTTPGridFS route "%s", requires a {filename} variable' %
formatter)
except (KeyError, AttributeError):
# aiohttp API changed? Fall back to simpler error message.
msg = ('Bad AIOHTTPGridFS route for request: %s' % request)
raise aiohttp.web.HTTPInternalServerError(text=msg) from None
2
Example 11
@asyncio.coroutine
def convert_old_project(self, project, legacy_id, name):
"""
Convert projects made before version 1.3
:param project: Project instance
:param legacy_id: old identifier
:param name: node name
:returns: new identifier
"""
new_id = str(uuid4())
legacy_project_files_path = os.path.join(project.path, "{}-files".format(project.name))
new_project_files_path = os.path.join(project.path, "project-files")
if os.path.exists(legacy_project_files_path) and not os.path.exists(new_project_files_path):
# move the project files
log.info("Converting old project...")
try:
log.info('Moving "{}" to "{}"'.format(legacy_project_files_path, new_project_files_path))
yield from wait_run_in_executor(shutil.move, legacy_project_files_path, new_project_files_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move project files directory: {} to {} {}".format(legacy_project_files_path,
new_project_files_path, e))
if project.is_local() is False:
legacy_remote_project_path = os.path.join(project.location, project.name, self.module_name.lower())
new_remote_project_path = os.path.join(project.path, "project-files", self.module_name.lower())
if os.path.exists(legacy_remote_project_path) and not os.path.exists(new_remote_project_path):
# move the legacy remote project (remote servers only)
log.info("Converting old remote project...")
try:
log.info('Moving "{}" to "{}"'.format(legacy_remote_project_path, new_remote_project_path))
yield from wait_run_in_executor(shutil.move, legacy_remote_project_path, new_remote_project_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move directory: {} to {} {}".format(legacy_remote_project_path,
new_remote_project_path, e))
if hasattr(self, "get_legacy_vm_workdir"):
# rename old project VM working dir
log.info("Converting old VM working directory...")
legacy_vm_dir = self.get_legacy_vm_workdir(legacy_id, name)
legacy_vm_working_path = os.path.join(new_project_files_path, legacy_vm_dir)
new_vm_working_path = os.path.join(new_project_files_path, self.module_name.lower(), new_id)
if os.path.exists(legacy_vm_working_path) and not os.path.exists(new_vm_working_path):
try:
log.info('Moving "{}" to "{}"'.format(legacy_vm_working_path, new_vm_working_path))
yield from wait_run_in_executor(shutil.move, legacy_vm_working_path, new_vm_working_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move VM working directory: {} to {} {}".format(legacy_vm_working_path,
new_vm_working_path, e))
return new_id
2
Example 12
def interfaces():
"""
Gets the network interfaces on this server.
:returns: list of network interfaces
"""
results = []
if not sys.platform.startswith("win"):
for interface in sorted(psutil.net_if_addrs().keys()):
ip_address = ""
mac_address = ""
for addr in psutil.net_if_addrs()[interface]:
# get the first available IPv4 address only
if addr.family == socket.AF_INET:
ip_address = addr.address
if addr.family == psutil.AF_LINK:
mac_address = addr.address
results.append({"id": interface,
"name": interface,
"ip_address": ip_address,
"mac_address": mac_address})
else:
try:
service_installed = True
if not _check_windows_service("npf") and not _check_windows_service("npcap"):
service_installed = False
else:
results = get_windows_interfaces()
except ImportError:
message = "pywin32 module is not installed, please install it on the server to get the available interface names"
raise aiohttp.web.HTTPInternalServerError(text=message)
except Exception as e:
log.error("uncaught exception {type}".format(type=type(e)), exc_info=1)
raise aiohttp.web.HTTPInternalServerError(text="uncaught exception: {}".format(e))
if service_installed is False:
raise aiohttp.web.HTTPInternalServerError(text="The Winpcap or Npcap is not installed or running")
return results
0
Example 13
def render_string(template_name, request, context, *, app_key=APP_KEY):
env = request.app.get(app_key)
if env is None:
text = ("Template engine is not initialized, "
"call aiohttp_jinja2.setup(..., app_key={}) first"
"".format(app_key))
# in order to see meaningful exception message both: on console
# output and rendered page we add same message to *reason* and
# *text* arguments.
raise web.HTTPInternalServerError(reason=text, text=text)
try:
template = env.get_template(template_name)
except jinja2.TemplateNotFound as e:
text = "Template '{}' not found".format(template_name)
raise web.HTTPInternalServerError(reason=text, text=text) from e
if not isinstance(context, Mapping):
text = "context should be mapping, not {}".format(type(context))
# same reason as above
raise web.HTTPInternalServerError(reason=text, text=text)
if REQUEST_CONTEXT_KEY in request:
for k, v in request.get(REQUEST_CONTEXT_KEY, {}).items():
if k not in context:
context[k] = v
text = template.render(context)
return text
0
Example 14
@asyncio.coroutine
def remember(request, response, identity, **kwargs):
"""Remember identity into response.
The action is performed by identity_policy.remember()
Usually the idenity is stored in user cookies homehow but may be
pushed into custom header also.
"""
assert isinstance(identity, str), identity
assert identity
identity_policy = request.app.get(IDENTITY_KEY)
if identity_policy is None:
text = ("Security subsystem is not initialized, "
"call aiohttp_security.setup(...) first")
# in order to see meaningful exception message both: on console
# output and rendered page we add same message to *reason* and
# *text* arguments.
raise web.HTTPInternalServerError(reason=text, text=text)
yield from identity_policy.remember(request, response, identity, **kwargs)
0
Example 15
@asyncio.coroutine
def process(self):
request = self.request
callback = request.GET.get('c', None)
if callback is None:
yield from self.session._remote_closed()
return web.HTTPInternalServerError(
body=b'"callback" parameter required')
elif not self.check_callback.match(callback):
yield from self.session._remote_closed()
return web.HTTPInternalServerError(
body=b'invalid "callback" parameter')
headers = list(
((hdrs.CONTENT_TYPE, 'text/html; charset=UTF-8'),
(hdrs.CACHE_CONTROL,
'no-store, no-cache, must-revalidate, max-age=0'),
(hdrs.CONNECTION, 'close')) +
session_cookie(request) +
cors_headers(request.headers))
# open sequence (sockjs protocol)
resp = self.response = web.StreamResponse(headers=headers)
yield from resp.prepare(self.request)
resp.write(b''.join(
(PRELUDE1, callback.encode('utf-8'), PRELUDE2, b' '*1024)))
# handle session
yield from self.handle_session()
return resp
0
Example 16
@asyncio.coroutine
def process(self):
session = self.session
request = self.request
meth = request.method
if request.method == hdrs.METH_GET:
callback = self.callback = request.GET.get('c')
if not callback:
yield from self.session._remote_closed()
return web.HTTPInternalServerError(
body=b'"callback" parameter required')
elif not self.check_callback.match(callback):
yield from self.session._remote_closed()
return web.HTTPBadRequest(
body=b'invalid "callback" parameter')
headers = list(
((hdrs.CONTENT_TYPE,
'application/javascript; charset=UTF-8'),
(hdrs.CACHE_CONTROL,
'no-store, no-cache, must-revalidate, max-age=0')) +
session_cookie(request) +
cors_headers(request.headers))
resp = self.response = web.StreamResponse(headers=headers)
yield from resp.prepare(request)
yield from self.handle_session()
return resp
elif request.method == hdrs.METH_POST:
data = yield from request.read()
ctype = request.content_type.lower()
if ctype == 'application/x-www-form-urlencoded':
if not data.startswith(b'd='):
return web.HTTPInternalServerError(
body=b'Payload expected.')
data = unquote_plus(data[2:].decode(ENCODING))
else:
data = data.decode(ENCODING)
if not data:
return web.HTTPInternalServerError(
body=b'Payload expected.')
try:
messages = loads(data)
except:
return web.HTTPInternalServerError(
body=b'Broken JSON encoding.')
yield from session._remote_messages(messages)
return web.Response(
body=b'ok',
headers=((hdrs.CONTENT_TYPE,
'text/plain; charset=UTF-8'),
(hdrs.CACHE_CONTROL,
'no-store, no-cache, must-revalidate, max-age=0')) +
session_cookie(request))
else:
return web.HTTPBadRequest(
text="No support for such method: %s" % meth)
0
Example 17
def test_release_session_for_failed_transport(self):
request = self.make_request(
'GET', '/sm/',
match_info={
'transport': 'test', 'session': 's1', 'server': '000'})
class Transport:
def __init__(self, manager, session, request):
self.manager = manager
self.session = session
def process(self):
yield from self.manager.acquire(self.session)
raise Exception('Error')
route = self.make_route(handlers={'test': (True, Transport)})
res = self.loop.run_until_complete(route.handler(request))
self.assertIsInstance(res, web.HTTPInternalServerError)
s1 = route.manager['s1']
self.assertFalse(route.manager.is_acquired(s1))
0
Example 18
@classmethod
@Route.post(
r"/projects/{project_id}/import",
description="Import a project from a portable archive",
parameters={
"project_id": "The UUID of the project",
},
raw=True,
output=PROJECT_OBJECT_SCHEMA,
status_codes={
200: "Project imported",
403: "You are not allowed to modify this property"
})
def import_project(request, response):
pm = ProjectManager.instance()
project_id = request.match_info["project_id"]
project = pm.create_project(project_id=project_id)
# We write the content to a temporary location
# and after extract all. It could be more optimal to stream
# this but it's not implemented in Python.
#
# Spooled mean the file is temporary keep in ram until max_size
try:
with tempfile.SpooledTemporaryFile(max_size=10000) as temp:
while True:
packet = yield from request.content.read(512)
if not packet:
break
temp.write(packet)
project.import_zip(temp, gns3vm=bool(int(request.GET.get("gns3vm", "1"))))
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not import the project: {}".format(e))
response.json(project)
response.set_status(201)
0
Example 19
def create_nio(self, executable, nio_settings):
"""
Creates a new NIO.
:param nio_settings: information to create the NIO
:returns: a NIO object
"""
nio = None
if nio_settings["type"] == "nio_udp":
lport = nio_settings["lport"]
rhost = nio_settings["rhost"]
rport = nio_settings["rport"]
try:
info = socket.getaddrinfo(rhost, rport, socket.AF_UNSPEC, socket.SOCK_DGRAM, 0, socket.AI_PASSIVE)
if not info:
raise aiohttp.web.HTTPInternalServerError(text="getaddrinfo returns an empty list on {}:{}".format(rhost, rport))
for res in info:
af, socktype, proto, _, sa = res
with socket.socket(af, socktype, proto) as sock:
sock.connect(sa)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create an UDP connection to {}:{}: {}".format(rhost, rport, e))
nio = NIOUDP(lport, rhost, rport)
elif nio_settings["type"] == "nio_tap":
tap_device = nio_settings["tap_device"]
# if not is_interface_up(tap_device):
# raise aiohttp.web.HTTPConflict(text="TAP interface {} does not exist or is down".format(tap_device))
# FIXME: check for permissions on tap device
# if not self.has_privileged_access(executable):
# raise aiohttp.web.HTTPForbidden(text="{} has no privileged access to {}.".format(executable, tap_device))
nio = NIOTAP(tap_device)
elif nio_settings["type"] == "nio_generic_ethernet":
ethernet_device = nio_settings["ethernet_device"]
if not is_interface_up(ethernet_device):
raise aiohttp.web.HTTPConflict(text="Ethernet interface {} does not exist or is down".format(ethernet_device))
nio = NIOGenericEthernet(ethernet_device)
elif nio_settings["type"] == "nio_nat":
nio = NIONAT()
assert nio is not None
return nio
0
Example 20
def _update_temporary_file(self):
"""
Update the .gns3_temporary file in order to reflect current
project status.
"""
if not hasattr(self, "_path"):
return
if self._temporary:
try:
with open(os.path.join(self._path, ".gns3_temporary"), 'w+') as f:
f.write("1")
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create temporary project: {}".format(e))
else:
if os.path.exists(os.path.join(self._path, ".gns3_temporary")):
try:
os.remove(os.path.join(self._path, ".gns3_temporary"))
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not mark project as no longer temporary: {}".format(e))
0
Example 21
@asyncio.coroutine
def _close_and_clean(self, cleanup):
"""
Closes the project, and cleanup the disk if cleanup is True
:param cleanup: If True drop the project directory
"""
tasks = []
for vm in self._vms:
tasks.append(asyncio.async(vm.manager.close_vm(vm.id)))
if tasks:
done, _ = yield from asyncio.wait(tasks)
for future in done:
try:
future.result()
except (Exception, GeneratorExit) as e:
log.error("Could not close VM or device {}".format(e), exc_info=1)
if cleanup and os.path.exists(self.path):
try:
yield from wait_run_in_executor(shutil.rmtree, self.path)
log.info("Project {id} with path '{path}' deleted".format(path=self._path, id=self._id))
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not delete the project directory: {}".format(e))
else:
log.info("Project {id} with path '{path}' closed".format(path=self._path, id=self._id))
if self._used_tcp_ports:
log.warning("Project {} has TCP ports still in use: {}".format(self.id, self._used_tcp_ports))
if self._used_udp_ports:
log.warning("Project {} has UDP ports still in use: {}".format(self.id, self._used_udp_ports))
# clean the remaining ports that have not been cleaned by their respective VM or device.
port_manager = PortManager.instance()
for port in self._used_tcp_ports.copy():
port_manager.release_tcp_port(port, self)
for port in self._used_udp_ports.copy():
port_manager.release_udp_port(port, self)
0
Example 22
def is_interface_up(interface):
"""
Checks if an interface is up.
:param interface: interface name
:returns: boolean
"""
if sys.platform.startswith("linux"):
if interface not in psutil.net_if_addrs():
return False
import fcntl
SIOCGIFFLAGS = 0x8913
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + '\0' * 256)
flags, = struct.unpack('H', result[16:18])
if flags & 1: # check if the up bit is set
return True
return False
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Exception when checking if {} is up: {}".format(interface, e))
else:
# TODO: Windows & OSX support
return True
0
Example 23
@asyncio.coroutine
def dht_traffic(self, request):
"""
Handle all DHT related traffic (JSON).
"""
data = None
try:
raw_data = yield from request.read()
peer = request.transport.get_extra_info('peername')[0]
log.info(peer)
log.info(raw_data)
result = yield from self.connector.receive(raw_data, peer,
self.local_node)
data = to_dict(result)
except Exception as ex:
# We log any errors in the connector / node instances,
# so return an appropriate error to the caller.
log.error(ex)
raise web.HTTPInternalServerError
raw_output = json.dumps(data).encode('utf-8')
return web.Response(body=raw_output, status=200,
content_type='application/json')