index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
21,393,452
miguelgrinberg/python-engineio
refs/heads/main
/examples/server/tornado/simple.py
import os import tornado.ioloop from tornado.options import define, options, parse_command_line import tornado.web import engineio define("port", default=8888, help="run on the given port", type=int) define("debug", default=False, help="run in debug mode") eio = engineio.AsyncServer(async_mode='tornado') class MainHandler(tornado.web.RequestHandler): def get(self): self.render("simple.html") @eio.on('connect') def connect(sid, environ): print("connect ", sid) @eio.on('message') async def message(sid, data): print('message from', sid, data) await eio.send(sid, 'Thank you for your message!') @eio.on('disconnect') def disconnect(sid): print('disconnect ', sid) def main(): parse_command_line() app = tornado.web.Application( [ (r"/", MainHandler), (r"/engine.io/", engineio.get_tornado_handler(eio)), ], template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), debug=options.debug, ) app.listen(options.port) tornado.ioloop.IOLoop.current().start() if __name__ == "__main__": main()
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,453
miguelgrinberg/python-engineio
refs/heads/main
/tests/asyncio/test_asyncio_server.py
import asyncio import gzip import io import logging import sys import unittest from unittest import mock import zlib import pytest from engineio import asyncio_server from engineio.async_drivers import aiohttp as async_aiohttp from engineio import exceptions from engineio import json from engineio import packet from engineio import payload def AsyncMock(*args, **kwargs): """Return a mock asynchronous function.""" m = mock.MagicMock(*args, **kwargs) async def mock_coro(*args, **kwargs): return m(*args, **kwargs) mock_coro.mock = m return mock_coro def _run(coro): """Run the given coroutine.""" return asyncio.get_event_loop().run_until_complete(coro) @unittest.skipIf(sys.version_info < (3, 5), 'only for Python 3.5+') class TestAsyncServer(unittest.TestCase): @staticmethod def get_async_mock(environ={'REQUEST_METHOD': 'GET', 'QUERY_STRING': ''}): if environ.get('QUERY_STRING'): if 'EIO=' not in environ['QUERY_STRING']: environ['QUERY_STRING'] = 'EIO=4&' + environ['QUERY_STRING'] else: environ['QUERY_STRING'] = 'EIO=4' a = mock.MagicMock() a._async = { 'asyncio': True, 'create_route': mock.MagicMock(), 'translate_request': mock.MagicMock(), 'make_response': mock.MagicMock(), 'websocket': 'w', } a._async['translate_request'].return_value = environ a._async['make_response'].return_value = 'response' return a def _get_mock_socket(self): mock_socket = mock.MagicMock() mock_socket.connected = False mock_socket.closed = False mock_socket.closing = False mock_socket.upgraded = False mock_socket.send = AsyncMock() mock_socket.handle_get_request = AsyncMock() mock_socket.handle_post_request = AsyncMock() mock_socket.check_ping_timeout = AsyncMock() mock_socket.close = AsyncMock() mock_socket.session = {} return mock_socket @classmethod def setUpClass(cls): asyncio_server.AsyncServer._default_monitor_clients = False @classmethod def tearDownClass(cls): asyncio_server.AsyncServer._default_monitor_clients = True def setUp(self): logging.getLogger('engineio').setLevel(logging.NOTSET) def tearDown(self): # restore JSON encoder, in case a test changed it packet.Packet.json = json def test_is_asyncio_based(self): s = asyncio_server.AsyncServer() assert s.is_asyncio_based() def test_async_modes(self): s = asyncio_server.AsyncServer() assert s.async_modes() == ['aiohttp', 'sanic', 'tornado', 'asgi'] def test_async_mode_aiohttp(self): s = asyncio_server.AsyncServer(async_mode='aiohttp') assert s.async_mode == 'aiohttp' assert s._async['asyncio'] assert s._async['create_route'] == async_aiohttp.create_route assert s._async['translate_request'] == async_aiohttp.translate_request assert s._async['make_response'] == async_aiohttp.make_response assert s._async['websocket'].__name__ == 'WebSocket' @mock.patch('importlib.import_module') def test_async_mode_auto_aiohttp(self, import_module): import_module.side_effect = [self.get_async_mock()] s = asyncio_server.AsyncServer() assert s.async_mode == 'aiohttp' def test_async_modes_wsgi(self): with pytest.raises(ValueError): asyncio_server.AsyncServer(async_mode='eventlet') with pytest.raises(ValueError): asyncio_server.AsyncServer(async_mode='gevent') with pytest.raises(ValueError): asyncio_server.AsyncServer(async_mode='gevent_uwsgi') with pytest.raises(ValueError): asyncio_server.AsyncServer(async_mode='threading') @mock.patch('importlib.import_module') def test_attach(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.attach('app', engineio_path='abc') a._async['create_route'].assert_called_with('app', s, '/abc/') s.attach('app', engineio_path='/def/') a._async['create_route'].assert_called_with('app', s, '/def/') s.attach('app', engineio_path='/ghi') a._async['create_route'].assert_called_with('app', s, '/ghi/') s.attach('app', engineio_path='jkl/') a._async['create_route'].assert_called_with('app', s, '/jkl/') def test_session(self): s = asyncio_server.AsyncServer() s.sockets['foo'] = self._get_mock_socket() async def _func(): async with s.session('foo') as session: await s.sleep(0) session['username'] = 'bar' assert await s.get_session('foo') == {'username': 'bar'} _run(_func()) def test_disconnect(self): s = asyncio_server.AsyncServer() s.sockets['foo'] = mock_socket = self._get_mock_socket() _run(s.disconnect('foo')) assert mock_socket.close.mock.call_count == 1 mock_socket.close.mock.assert_called_once_with() assert 'foo' not in s.sockets def test_disconnect_all(self): s = asyncio_server.AsyncServer() s.sockets['foo'] = mock_foo = self._get_mock_socket() s.sockets['bar'] = mock_bar = self._get_mock_socket() _run(s.disconnect()) assert mock_foo.close.mock.call_count == 1 assert mock_bar.close.mock.call_count == 1 mock_foo.close.mock.assert_called_once_with() mock_bar.close.mock.assert_called_once_with() assert 'foo' not in s.sockets assert 'bar' not in s.sockets @mock.patch('importlib.import_module') def test_jsonp_not_supported(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'j=abc'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() response = _run(s.handle_request('request')) assert response == 'response' a._async['translate_request'].assert_called_once_with('request') assert a._async['make_response'].call_count == 1 assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' @mock.patch('importlib.import_module') def test_jsonp_index(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'j=233'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() response = _run(s.handle_request('request')) assert response == 'response' a._async['translate_request'].assert_called_once_with('request') assert a._async['make_response'].call_count == 1 assert a._async['make_response'].call_args[0][0] == '200 OK' assert ( a._async['make_response'] .call_args[0][2] .startswith(b'___eio[233]("') ) assert a._async['make_response'].call_args[0][2].endswith(b'");') @mock.patch('importlib.import_module') def test_connect(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert len(s.sockets) == 1 assert a._async['make_response'].call_count == 1 assert a._async['make_response'].call_args[0][0] == '200 OK' assert ('Content-Type', 'text/plain; charset=UTF-8') in a._async[ 'make_response' ].call_args[0][1] packets = payload.Payload( encoded_payload=a._async['make_response'].call_args[0][2].decode( 'utf-8')).packets assert len(packets) == 1 assert packets[0].packet_type == packet.OPEN assert 'upgrades' in packets[0].data assert packets[0].data['upgrades'] == ['websocket'] assert 'sid' in packets[0].data @mock.patch('importlib.import_module') def test_connect_async_request_response_handlers(self, import_module): a = self.get_async_mock() a._async['translate_request'] = AsyncMock( return_value=a._async['translate_request'].return_value ) a._async['make_response'] = AsyncMock( return_value=a._async['make_response'].return_value ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert len(s.sockets) == 1 assert a._async['make_response'].mock.call_count == 1 assert a._async['make_response'].mock.call_args[0][0] == '200 OK' assert ('Content-Type', 'text/plain; charset=UTF-8') in a._async[ 'make_response' ].mock.call_args[0][1] packets = payload.Payload( encoded_payload=a._async['make_response'].mock.call_args[0][ 2].decode('utf-8')).packets assert len(packets) == 1 assert packets[0].packet_type == packet.OPEN assert 'upgrades' in packets[0].data assert packets[0].data['upgrades'] == ['websocket'] assert 'sid' in packets[0].data @mock.patch('importlib.import_module') def test_connect_no_upgrades(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer(allow_upgrades=False) _run(s.handle_request('request')) packets = payload.Payload( encoded_payload=a._async['make_response'].call_args[0][2].decode( 'utf-8')).packets assert packets[0].data['upgrades'] == [] @mock.patch('importlib.import_module') def test_connect_bad_eio_version(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'EIO=1'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert a._async['make_response'].call_count == 1 assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' assert b'unsupported version' in \ a._async['make_response'].call_args[0][2] @mock.patch('importlib.import_module') def test_connect_custom_ping_times(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer(ping_timeout=123, ping_interval=456) _run(s.handle_request('request')) packets = payload.Payload( encoded_payload=a._async['make_response'].call_args[0][2].decode( 'utf-8')).packets assert packets[0].data['pingTimeout'] == 123000 assert packets[0].data['pingInterval'] == 456000 @mock.patch('importlib.import_module') @mock.patch('engineio.asyncio_server.asyncio_socket.AsyncSocket') def test_connect_bad_poll(self, AsyncSocket, import_module): a = self.get_async_mock() import_module.side_effect = [a] AsyncSocket.return_value = self._get_mock_socket() AsyncSocket.return_value.poll.side_effect = [exceptions.QueueEmpty] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert a._async['make_response'].call_count == 1 assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' @mock.patch('importlib.import_module') @mock.patch('engineio.asyncio_server.asyncio_socket.AsyncSocket') def test_connect_transport_websocket(self, AsyncSocket, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'transport=websocket', 'HTTP_UPGRADE': 'websocket', } ) import_module.side_effect = [a] AsyncSocket.return_value = self._get_mock_socket() s = asyncio_server.AsyncServer() s.generate_id = mock.MagicMock(return_value='123') # force socket to stay open, so that we can check it later AsyncSocket().closed = False _run(s.handle_request('request')) assert ( s.sockets['123'].send.mock.call_args[0][0].packet_type == packet.OPEN ) @mock.patch('importlib.import_module') @mock.patch('engineio.asyncio_server.asyncio_socket.AsyncSocket') def test_http_upgrade_case_insensitive(self, AsyncSocket, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'transport=websocket', 'HTTP_UPGRADE': 'WebSocket', } ) import_module.side_effect = [a] AsyncSocket.return_value = self._get_mock_socket() s = asyncio_server.AsyncServer() s.generate_id = mock.MagicMock(return_value='123') # force socket to stay open, so that we can check it later AsyncSocket().closed = False _run(s.handle_request('request')) assert ( s.sockets['123'].send.mock.call_args[0][0].packet_type == packet.OPEN ) @mock.patch('importlib.import_module') @mock.patch('engineio.asyncio_server.asyncio_socket.AsyncSocket') def test_connect_transport_websocket_closed( self, AsyncSocket, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'transport=websocket', 'HTTP_UPGRADE': 'websocket' } ) import_module.side_effect = [a] AsyncSocket.return_value = self._get_mock_socket() s = asyncio_server.AsyncServer() s.generate_id = mock.MagicMock(return_value='123') # this mock handler just closes the socket, as it would happen on a # real websocket exchange async def mock_handle(environ): s.sockets['123'].closed = True AsyncSocket().handle_get_request = mock_handle _run(s.handle_request('request')) assert '123' not in s.sockets # socket should close on its own @mock.patch('importlib.import_module') def test_connect_transport_invalid(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'transport=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert a._async['make_response'].call_count == 1 assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' @mock.patch('importlib.import_module') def test_connect_transport_websocket_without_upgrade(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'transport=websocket'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert a._async['make_response'].call_count == 1 assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' @mock.patch('importlib.import_module') def test_connect_cors_headers(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Credentials', 'true') in headers @mock.patch('importlib.import_module') def test_connect_cors_allowed_origin(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'HTTP_ORIGIN': 'b'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins=['a', 'b']) _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Origin', 'b') in headers @mock.patch('importlib.import_module') def test_connect_cors_allowed_origin_with_callable(self, import_module): def cors(origin): return origin == 'a' environ = { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'HTTP_ORIGIN': 'a' } a = self.get_async_mock(environ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins=cors) _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Origin', 'a') in headers environ['HTTP_ORIGIN'] = 'b' _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' @mock.patch('importlib.import_module') def test_connect_cors_not_allowed_origin(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'HTTP_ORIGIN': 'c'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins=['a', 'b']) _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Origin', 'c') not in headers assert ('Access-Control-Allow-Origin', '*') not in headers @mock.patch('importlib.import_module') def test_connect_cors_not_allowed_origin_async_response( self, import_module ): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'HTTP_ORIGIN': 'c'} ) a._async['make_response'] = AsyncMock( return_value=a._async['make_response'].return_value ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins=['a', 'b']) _run(s.handle_request('request')) assert ( a._async['make_response'].mock.call_args[0][0] == '400 BAD REQUEST' ) headers = a._async['make_response'].mock.call_args[0][1] assert ('Access-Control-Allow-Origin', 'c') not in headers assert ('Access-Control-Allow-Origin', '*') not in headers @mock.patch('importlib.import_module') def test_connect_cors_all_origins(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'HTTP_ORIGIN': 'foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins='*') _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Origin', 'foo') in headers assert ('Access-Control-Allow-Credentials', 'true') in headers @mock.patch('importlib.import_module') def test_connect_cors_one_origin(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'HTTP_ORIGIN': 'a'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins='a') _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Origin', 'a') in headers assert ('Access-Control-Allow-Credentials', 'true') in headers @mock.patch('importlib.import_module') def test_connect_cors_one_origin_not_allowed(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'HTTP_ORIGIN': 'b'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins='a') _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Origin', 'b') not in headers assert ('Access-Control-Allow-Origin', '*') not in headers @mock.patch('importlib.import_module') def test_connect_cors_headers_default_origin(self, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'wsgi.url_scheme': 'http', 'HTTP_HOST': 'foo', 'HTTP_ORIGIN': 'http://foo', } ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Origin', 'http://foo') in headers @mock.patch('importlib.import_module') def test_connect_cors_no_credentials(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_credentials=False) _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] assert ('Access-Control-Allow-Credentials', 'true') not in headers @mock.patch('importlib.import_module') def test_connect_cors_options(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'OPTIONS', 'QUERY_STRING': ''} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_credentials=False) _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] assert ( 'Access-Control-Allow-Methods', 'OPTIONS, GET, POST', ) in headers @mock.patch('importlib.import_module') def test_connect_cors_disabled(self, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'HTTP_ORIGIN': 'http://foo', } ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins=[]) _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] for header in headers: assert not header[0].startswith('Access-Control-') @mock.patch('importlib.import_module') def test_connect_cors_default_no_origin(self, import_module): a = self.get_async_mock({'REQUEST_METHOD': 'GET', 'QUERY_STRING': ''}) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins=[]) _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] for header in headers: assert header[0] != 'Access-Control-Allow-Origin' @mock.patch('importlib.import_module') def test_connect_cors_all_no_origin(self, import_module): a = self.get_async_mock({'REQUEST_METHOD': 'GET', 'QUERY_STRING': ''}) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins='*') _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] for header in headers: assert header[0] != 'Access-Control-Allow-Origin' @mock.patch('importlib.import_module') def test_connect_cors_disabled_no_origin(self, import_module): a = self.get_async_mock({'REQUEST_METHOD': 'GET', 'QUERY_STRING': ''}) import_module.side_effect = [a] s = asyncio_server.AsyncServer(cors_allowed_origins=[]) _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' headers = a._async['make_response'].call_args[0][1] for header in headers: assert header[0] != 'Access-Control-Allow-Origin' @mock.patch('importlib.import_module') def test_connect_event(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.generate_id = mock.MagicMock(return_value='123') def mock_connect(sid, environ): return True s.on('connect', handler=mock_connect) _run(s.handle_request('request')) assert len(s.sockets) == 1 @mock.patch('importlib.import_module') def test_connect_event_rejects(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.generate_id = mock.MagicMock(return_value='123') def mock_connect(sid, environ): return False s.on('connect')(mock_connect) _run(s.handle_request('request')) assert len(s.sockets) == 0 assert a._async['make_response'].call_args[0][0] == '401 UNAUTHORIZED' assert a._async['make_response'].call_args[0][2] == b'"Unauthorized"' @mock.patch('importlib.import_module') def test_connect_event_rejects_with_message(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.generate_id = mock.MagicMock(return_value='123') def mock_connect(sid, environ): return {'not': 'allowed'} s.on('connect')(mock_connect) _run(s.handle_request('request')) assert len(s.sockets) == 0 assert a._async['make_response'].call_args[0][0] == '401 UNAUTHORIZED' assert ( a._async['make_response'].call_args[0][2] == b'{"not": "allowed"}' ) @mock.patch('importlib.import_module') def test_method_not_found(self, import_module): a = self.get_async_mock({'REQUEST_METHOD': 'PUT', 'QUERY_STRING': ''}) import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert len(s.sockets) == 0 assert ( a._async['make_response'].call_args[0][0] == '405 METHOD NOT FOUND' ) @mock.patch('importlib.import_module') def test_get_request_with_bad_sid(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert len(s.sockets) == 0 assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' @mock.patch('importlib.import_module') def test_post_request_with_bad_sid(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'POST', 'QUERY_STRING': 'sid=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() _run(s.handle_request('request')) assert len(s.sockets) == 0 assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' @mock.patch('importlib.import_module') def test_send(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.sockets['foo'] = mock_socket = self._get_mock_socket() _run(s.send('foo', 'hello')) assert mock_socket.send.mock.call_count == 1 assert ( mock_socket.send.mock.call_args[0][0].packet_type == packet.MESSAGE ) assert mock_socket.send.mock.call_args[0][0].data == 'hello' @mock.patch('importlib.import_module') def test_send_unknown_socket(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer() # just ensure no exceptions are raised _run(s.send('foo', 'hello')) @mock.patch('importlib.import_module') def test_get_request(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.sockets['foo'] = mock_socket = self._get_mock_socket() mock_socket.handle_get_request.mock.return_value = [ packet.Packet(packet.MESSAGE, data='hello') ] _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' packets = payload.Payload( encoded_payload=a._async['make_response'].call_args[0][2].decode( 'utf-8') ).packets assert len(packets) == 1 assert packets[0].packet_type == packet.MESSAGE @mock.patch('importlib.import_module') def test_get_request_custom_response(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.sockets['foo'] = mock_socket = self._get_mock_socket() mock_socket.handle_get_request.mock.return_value = 'resp' r = _run(s.handle_request('request')) assert r == 'resp' @mock.patch('importlib.import_module') def test_get_request_closes_socket(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.sockets['foo'] = mock_socket = self._get_mock_socket() async def mock_get_request(*args, **kwargs): mock_socket.closed = True return 'resp' mock_socket.handle_get_request = mock_get_request r = _run(s.handle_request('request')) assert r == 'resp' assert 'foo' not in s.sockets @mock.patch('importlib.import_module') def test_get_request_error(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.sockets['foo'] = mock_socket = self._get_mock_socket() async def mock_get_request(*args, **kwargs): raise exceptions.QueueEmpty() mock_socket.handle_get_request = mock_get_request _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' assert len(s.sockets) == 0 @mock.patch('importlib.import_module') def test_post_request(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'POST', 'QUERY_STRING': 'sid=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.sockets['foo'] = self._get_mock_socket() _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '200 OK' @mock.patch('importlib.import_module') def test_post_request_error(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'POST', 'QUERY_STRING': 'sid=foo'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer() s.sockets['foo'] = mock_socket = self._get_mock_socket() async def mock_post_request(*args, **kwargs): raise exceptions.ContentTooLongError() mock_socket.handle_post_request = mock_post_request _run(s.handle_request('request')) assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST' @staticmethod def _gzip_decompress(b): bytesio = io.BytesIO(b) with gzip.GzipFile(fileobj=bytesio, mode='r') as gz: return gz.read() @mock.patch('importlib.import_module') def test_gzip_compression(self, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate', } ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(compression_threshold=0) s.sockets['foo'] = mock_socket = self._get_mock_socket() mock_socket.handle_get_request.mock.return_value = [ packet.Packet(packet.MESSAGE, data='hello') ] _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] assert ('Content-Encoding', 'gzip') in headers self._gzip_decompress(a._async['make_response'].call_args[0][2]) @mock.patch('importlib.import_module') def test_deflate_compression(self, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo', 'HTTP_ACCEPT_ENCODING': 'deflate;q=1,gzip', } ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(compression_threshold=0) s.sockets['foo'] = mock_socket = self._get_mock_socket() mock_socket.handle_get_request.mock.return_value = [ packet.Packet(packet.MESSAGE, data='hello') ] _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] assert ('Content-Encoding', 'deflate') in headers zlib.decompress(a._async['make_response'].call_args[0][2]) @mock.patch('importlib.import_module') def test_gzip_compression_threshold(self, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo', 'HTTP_ACCEPT_ENCODING': 'gzip', } ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(compression_threshold=1000) s.sockets['foo'] = mock_socket = self._get_mock_socket() mock_socket.handle_get_request.mock.return_value = [ packet.Packet(packet.MESSAGE, data='hello') ] _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] for header, value in headers: assert header != 'Content-Encoding' with pytest.raises(IOError): self._gzip_decompress(a._async['make_response'].call_args[0][2]) @mock.patch('importlib.import_module') def test_compression_disabled(self, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo', 'HTTP_ACCEPT_ENCODING': 'gzip', } ) import_module.side_effect = [a] s = asyncio_server.AsyncServer( http_compression=False, compression_threshold=0 ) s.sockets['foo'] = mock_socket = self._get_mock_socket() mock_socket.handle_get_request.mock.return_value = [ packet.Packet(packet.MESSAGE, data='hello') ] _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] for header, value in headers: assert header != 'Content-Encoding' with pytest.raises(IOError): self._gzip_decompress(a._async['make_response'].call_args[0][2]) @mock.patch('importlib.import_module') def test_compression_unknown(self, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo', 'HTTP_ACCEPT_ENCODING': 'rar', } ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(compression_threshold=0) s.sockets['foo'] = mock_socket = self._get_mock_socket() mock_socket.handle_get_request.mock.return_value = [ packet.Packet(packet.MESSAGE, data='hello') ] _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] for header, value in headers: assert header != 'Content-Encoding' with pytest.raises(IOError): self._gzip_decompress(a._async['make_response'].call_args[0][2]) @mock.patch('importlib.import_module') def test_compression_no_encoding(self, import_module): a = self.get_async_mock( { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo', 'HTTP_ACCEPT_ENCODING': '', } ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(compression_threshold=0) s.sockets['foo'] = mock_socket = self._get_mock_socket() mock_socket.handle_get_request.mock.return_value = [ packet.Packet(packet.MESSAGE, data='hello') ] _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] for header, value in headers: assert header != 'Content-Encoding' with pytest.raises(IOError): self._gzip_decompress(a._async['make_response'].call_args[0][2]) @mock.patch('importlib.import_module') def test_cookie(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer(cookie='sid') s.generate_id = mock.MagicMock(return_value='123') _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] assert ('Set-Cookie', 'sid=123; path=/; SameSite=Lax') in headers @mock.patch('importlib.import_module') def test_cookie_dict(self, import_module): def get_path(): return '/a' a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer(cookie={ 'name': 'test', 'path': get_path, 'SameSite': 'None', 'Secure': True, 'HttpOnly': True }) s.generate_id = mock.MagicMock(return_value='123') _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] assert ('Set-Cookie', 'test=123; path=/a; SameSite=None; Secure; ' 'HttpOnly') in headers @mock.patch('importlib.import_module') def test_no_cookie(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer(cookie=None) s.generate_id = mock.MagicMock(return_value='123') _run(s.handle_request('request')) headers = a._async['make_response'].call_args[0][1] for header, value in headers: assert header != 'Set-Cookie' def test_logger(self): s = asyncio_server.AsyncServer(logger=False) assert s.logger.getEffectiveLevel() == logging.ERROR s.logger.setLevel(logging.NOTSET) s = asyncio_server.AsyncServer(logger=True) assert s.logger.getEffectiveLevel() == logging.INFO s.logger.setLevel(logging.WARNING) s = asyncio_server.AsyncServer(logger=True) assert s.logger.getEffectiveLevel() == logging.WARNING s.logger.setLevel(logging.NOTSET) my_logger = logging.Logger('foo') s = asyncio_server.AsyncServer(logger=my_logger) assert s.logger == my_logger def test_custom_json(self): # Warning: this test cannot run in parallel with other tests, as it # changes the JSON encoding/decoding functions class CustomJSON(object): @staticmethod def dumps(*args, **kwargs): return '*** encoded ***' @staticmethod def loads(*args, **kwargs): return '+++ decoded +++' asyncio_server.AsyncServer(json=CustomJSON) pkt = packet.Packet(packet.MESSAGE, data={'foo': 'bar'}) assert pkt.encode() == '4*** encoded ***' pkt2 = packet.Packet(encoded_packet=pkt.encode()) assert pkt2.data == '+++ decoded +++' # restore the default JSON module packet.Packet.json = json def test_background_tasks(self): r = [] async def foo(arg): r.append(arg) s = asyncio_server.AsyncServer() s.start_background_task(foo, 'bar') pending = asyncio.all_tasks(loop=asyncio.get_event_loop()) \ if hasattr(asyncio, 'all_tasks') else asyncio.Task.all_tasks() asyncio.get_event_loop().run_until_complete(asyncio.wait(pending)) assert r == ['bar'] def test_sleep(self): s = asyncio_server.AsyncServer() _run(s.sleep(0)) def test_trigger_event_function(self): result = [] def foo_handler(arg): result.append('ok') result.append(arg) s = asyncio_server.AsyncServer() s.on('message', handler=foo_handler) _run(s._trigger_event('message', 'bar')) assert result == ['ok', 'bar'] def test_trigger_event_coroutine(self): result = [] async def foo_handler(arg): result.append('ok') result.append(arg) s = asyncio_server.AsyncServer() s.on('message', handler=foo_handler) _run(s._trigger_event('message', 'bar')) assert result == ['ok', 'bar'] def test_trigger_event_function_error(self): def connect_handler(arg): return 1 / 0 def foo_handler(arg): return 1 / 0 s = asyncio_server.AsyncServer() s.on('connect', handler=connect_handler) s.on('message', handler=foo_handler) assert not _run(s._trigger_event('connect', '123')) assert _run(s._trigger_event('message', 'bar')) is None def test_trigger_event_coroutine_error(self): async def connect_handler(arg): return 1 / 0 async def foo_handler(arg): return 1 / 0 s = asyncio_server.AsyncServer() s.on('connect', handler=connect_handler) s.on('message', handler=foo_handler) assert not _run(s._trigger_event('connect', '123')) assert _run(s._trigger_event('message', 'bar')) is None def test_trigger_event_function_async(self): result = [] def foo_handler(arg): result.append('ok') result.append(arg) s = asyncio_server.AsyncServer() s.on('message', handler=foo_handler) fut = _run(s._trigger_event('message', 'bar', run_async=True)) asyncio.get_event_loop().run_until_complete(fut) assert result == ['ok', 'bar'] def test_trigger_event_coroutine_async(self): result = [] async def foo_handler(arg): result.append('ok') result.append(arg) s = asyncio_server.AsyncServer() s.on('message', handler=foo_handler) fut = _run(s._trigger_event('message', 'bar', run_async=True)) asyncio.get_event_loop().run_until_complete(fut) assert result == ['ok', 'bar'] def test_trigger_event_function_async_error(self): result = [] def foo_handler(arg): result.append(arg) return 1 / 0 s = asyncio_server.AsyncServer() s.on('message', handler=foo_handler) fut = _run(s._trigger_event('message', 'bar', run_async=True)) with pytest.raises(ZeroDivisionError): asyncio.get_event_loop().run_until_complete(fut) assert result == ['bar'] def test_trigger_event_coroutine_async_error(self): result = [] async def foo_handler(arg): result.append(arg) return 1 / 0 s = asyncio_server.AsyncServer() s.on('message', handler=foo_handler) fut = _run(s._trigger_event('message', 'bar', run_async=True)) with pytest.raises(ZeroDivisionError): asyncio.get_event_loop().run_until_complete(fut) assert result == ['bar'] def test_create_queue(self): s = asyncio_server.AsyncServer() q = s.create_queue() empty = s.get_queue_empty_exception() with pytest.raises(empty): q.get_nowait() def test_create_event(self): s = asyncio_server.AsyncServer() e = s.create_event() assert not e.is_set() e.set() assert e.is_set() @mock.patch('importlib.import_module') def test_service_task_started(self, import_module): a = self.get_async_mock() import_module.side_effect = [a] s = asyncio_server.AsyncServer(monitor_clients=True) s._service_task = AsyncMock() _run(s.handle_request('request')) s._service_task.mock.assert_called_once_with() @mock.patch('importlib.import_module') def test_transports_disallowed(self, import_module): a = self.get_async_mock( {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'transport=polling'} ) import_module.side_effect = [a] s = asyncio_server.AsyncServer(transports='websocket') response = _run(s.handle_request('request')) assert response == 'response' a._async['translate_request'].assert_called_once_with('request') assert a._async['make_response'].call_count == 1 assert a._async['make_response'].call_args[0][0] == '400 BAD REQUEST'
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,454
miguelgrinberg/python-engineio
refs/heads/main
/tests/common/test_socket.py
import io import time import unittest from unittest import mock import pytest from engineio import exceptions from engineio import packet from engineio import payload from engineio import socket class TestSocket(unittest.TestCase): def setUp(self): self.bg_tasks = [] def _get_mock_server(self): mock_server = mock.Mock() mock_server.ping_timeout = 0.2 mock_server.ping_interval = 0.2 mock_server.ping_interval_grace_period = 0.001 mock_server.async_handlers = True mock_server.max_http_buffer_size = 128 try: import queue except ImportError: import Queue as queue import threading mock_server._async = { 'threading': threading.Thread, 'queue': queue.Queue, 'websocket': None, } def bg_task(target, *args, **kwargs): th = threading.Thread(target=target, args=args, kwargs=kwargs) self.bg_tasks.append(th) th.start() return th def create_queue(*args, **kwargs): return queue.Queue(*args, **kwargs) mock_server.start_background_task = bg_task mock_server.create_queue = create_queue mock_server.get_queue_empty_exception.return_value = queue.Empty return mock_server def _join_bg_tasks(self): for task in self.bg_tasks: task.join() def test_create(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') assert s.server == mock_server assert s.sid == 'sid' assert not s.upgraded assert not s.closed assert hasattr(s.queue, 'get') assert hasattr(s.queue, 'put') assert hasattr(s.queue, 'task_done') assert hasattr(s.queue, 'join') def test_empty_poll(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') with pytest.raises(exceptions.QueueEmpty): s.poll() def test_poll(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') pkt1 = packet.Packet(packet.MESSAGE, data='hello') pkt2 = packet.Packet(packet.MESSAGE, data='bye') s.send(pkt1) s.send(pkt2) assert s.poll() == [pkt1, pkt2] def test_poll_none(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.queue.put(None) assert s.poll() == [] def test_poll_none_after_packet(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') pkt = packet.Packet(packet.MESSAGE, data='hello') s.send(pkt) s.queue.put(None) assert s.poll() == [pkt] assert s.poll() == [] def test_schedule_ping(self): mock_server = self._get_mock_server() mock_server.ping_interval = 0.01 s = socket.Socket(mock_server, 'sid') s.send = mock.MagicMock() s.schedule_ping() time.sleep(0.05) assert s.last_ping is not None assert s.send.call_args_list[0][0][0].encode() == '2' def test_schedule_ping_closed_socket(self): mock_server = self._get_mock_server() mock_server.ping_interval = 0.01 s = socket.Socket(mock_server, 'sid') s.send = mock.MagicMock() s.closed = True s.schedule_ping() time.sleep(0.05) assert s.last_ping is None s.send.assert_not_called() def test_pong(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.schedule_ping = mock.MagicMock() s.receive(packet.Packet(packet.PONG)) s.schedule_ping.assert_called_once_with() def test_message_async_handler(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.receive(packet.Packet(packet.MESSAGE, data='foo')) mock_server._trigger_event.assert_called_once_with( 'message', 'sid', 'foo', run_async=True ) def test_message_sync_handler(self): mock_server = self._get_mock_server() mock_server.async_handlers = False s = socket.Socket(mock_server, 'sid') s.receive(packet.Packet(packet.MESSAGE, data='foo')) mock_server._trigger_event.assert_called_once_with( 'message', 'sid', 'foo', run_async=False ) def test_invalid_packet(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') with pytest.raises(exceptions.UnknownPacketError): s.receive(packet.Packet(packet.OPEN)) def test_timeout(self): mock_server = self._get_mock_server() mock_server.ping_interval = 6 mock_server.ping_interval_grace_period = 2 s = socket.Socket(mock_server, 'sid') s.last_ping = time.time() - 9 s.close = mock.MagicMock() s.send('packet') s.close.assert_called_once_with(wait=False, abort=False) def test_polling_read(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'foo') pkt1 = packet.Packet(packet.MESSAGE, data='hello') pkt2 = packet.Packet(packet.MESSAGE, data='bye') s.send(pkt1) s.send(pkt2) environ = {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} start_response = mock.MagicMock() packets = s.handle_get_request(environ, start_response) assert packets == [pkt1, pkt2] def test_polling_read_error(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'foo') environ = {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} start_response = mock.MagicMock() with pytest.raises(exceptions.QueueEmpty): s.handle_get_request(environ, start_response) def test_polling_write(self): mock_server = self._get_mock_server() mock_server.max_http_buffer_size = 1000 pkt1 = packet.Packet(packet.MESSAGE, data='hello') pkt2 = packet.Packet(packet.MESSAGE, data='bye') p = payload.Payload(packets=[pkt1, pkt2]).encode().encode('utf-8') s = socket.Socket(mock_server, 'foo') s.receive = mock.MagicMock() environ = { 'REQUEST_METHOD': 'POST', 'QUERY_STRING': 'sid=foo', 'CONTENT_LENGTH': len(p), 'wsgi.input': io.BytesIO(p), } s.handle_post_request(environ) assert s.receive.call_count == 2 def test_polling_write_too_large(self): mock_server = self._get_mock_server() pkt1 = packet.Packet(packet.MESSAGE, data='hello') pkt2 = packet.Packet(packet.MESSAGE, data='bye') p = payload.Payload(packets=[pkt1, pkt2]).encode().encode('utf-8') mock_server.max_http_buffer_size = len(p) - 1 s = socket.Socket(mock_server, 'foo') s.receive = mock.MagicMock() environ = { 'REQUEST_METHOD': 'POST', 'QUERY_STRING': 'sid=foo', 'CONTENT_LENGTH': len(p), 'wsgi.input': io.BytesIO(p), } with pytest.raises(exceptions.ContentTooLongError): s.handle_post_request(environ) def test_upgrade_handshake(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'foo') s._upgrade_websocket = mock.MagicMock() environ = { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo', 'HTTP_CONNECTION': 'Foo,Upgrade,Bar', 'HTTP_UPGRADE': 'websocket', } start_response = mock.MagicMock() s.handle_get_request(environ, start_response) s._upgrade_websocket.assert_called_once_with(environ, start_response) def test_upgrade(self): mock_server = self._get_mock_server() mock_server._async['websocket'] = mock.MagicMock() mock_ws = mock.MagicMock() mock_server._async['websocket'].return_value = mock_ws s = socket.Socket(mock_server, 'sid') s.connected = True environ = "foo" start_response = "bar" s._upgrade_websocket(environ, start_response) mock_server._async['websocket'].assert_called_once_with( s._websocket_handler, mock_server ) mock_ws.assert_called_once_with(environ, start_response) def test_upgrade_twice(self): mock_server = self._get_mock_server() mock_server._async['websocket'] = mock.MagicMock() s = socket.Socket(mock_server, 'sid') s.connected = True s.upgraded = True environ = "foo" start_response = "bar" with pytest.raises(IOError): s._upgrade_websocket(environ, start_response) def test_upgrade_packet(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = True s.receive(packet.Packet(packet.UPGRADE)) r = s.poll() assert len(r) == 1 assert r[0].encode() == packet.Packet(packet.NOOP).encode() def test_upgrade_no_probe(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = True ws = mock.MagicMock() ws.wait.return_value = packet.Packet(packet.NOOP).encode() s._websocket_handler(ws) assert not s.upgraded def test_upgrade_no_upgrade_packet(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = True s.queue.join = mock.MagicMock(return_value=None) ws = mock.MagicMock() probe = 'probe' ws.wait.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.NOOP).encode(), ] s._websocket_handler(ws) ws.send.assert_called_once_with( packet.Packet(packet.PONG, data=probe).encode() ) assert s.queue.get().packet_type == packet.NOOP assert not s.upgraded def test_close_packet(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = True s.close = mock.MagicMock() s.receive(packet.Packet(packet.CLOSE)) s.close.assert_called_once_with(wait=False, abort=True) def test_invalid_packet_type(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') pkt = packet.Packet(packet_type=99) with pytest.raises(exceptions.UnknownPacketError): s.receive(pkt) def test_upgrade_not_supported(self): mock_server = self._get_mock_server() mock_server._async['websocket'] = None s = socket.Socket(mock_server, 'sid') s.connected = True environ = "foo" start_response = "bar" s._upgrade_websocket(environ, start_response) mock_server._bad_request.assert_called_once_with() def test_websocket_read_write(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = False s.queue.join = mock.MagicMock(return_value=None) foo = 'foo' bar = 'bar' s.poll = mock.MagicMock( side_effect=[ [packet.Packet(packet.MESSAGE, data=bar)], exceptions.QueueEmpty, ] ) ws = mock.MagicMock() ws.wait.side_effect = [ packet.Packet(packet.MESSAGE, data=foo).encode(), None, ] s._websocket_handler(ws) self._join_bg_tasks() assert s.connected assert s.upgraded assert mock_server._trigger_event.call_count == 2 mock_server._trigger_event.assert_has_calls( [ mock.call('message', 'sid', 'foo', run_async=True), mock.call('disconnect', 'sid', run_async=False), ] ) ws.send.assert_called_with('4bar') def test_websocket_upgrade_read_write(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = True s.queue.join = mock.MagicMock(return_value=None) foo = 'foo' bar = 'bar' probe = 'probe' s.poll = mock.MagicMock( side_effect=[ [packet.Packet(packet.MESSAGE, data=bar)], exceptions.QueueEmpty, ] ) ws = mock.MagicMock() ws.wait.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.UPGRADE).encode(), packet.Packet(packet.MESSAGE, data=foo).encode(), None, ] s._websocket_handler(ws) self._join_bg_tasks() assert s.upgraded assert mock_server._trigger_event.call_count == 2 mock_server._trigger_event.assert_has_calls( [ mock.call('message', 'sid', 'foo', run_async=True), mock.call('disconnect', 'sid', run_async=False), ] ) ws.send.assert_called_with('4bar') def test_websocket_upgrade_with_payload(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = True s.queue.join = mock.MagicMock(return_value=None) probe = 'probe' ws = mock.MagicMock() ws.wait.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.UPGRADE, data='2').encode(), ] s._websocket_handler(ws) self._join_bg_tasks() assert s.upgraded def test_websocket_upgrade_with_backlog(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = True s.queue.join = mock.MagicMock(return_value=None) probe = 'probe' foo = 'foo' ws = mock.MagicMock() ws.wait.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.UPGRADE, data='2').encode(), ] s.upgrading = True s.send(packet.Packet(packet.MESSAGE, data=foo)) environ = {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=sid'} start_response = mock.MagicMock() packets = s.handle_get_request(environ, start_response) assert len(packets) == 1 assert packets[0].encode() == '6' packets = s.poll() assert len(packets) == 1 assert packets[0].encode() == '4foo' s._websocket_handler(ws) self._join_bg_tasks() assert s.upgraded assert not s.upgrading packets = s.handle_get_request(environ, start_response) assert len(packets) == 1 assert packets[0].encode() == '6' def test_websocket_read_write_wait_fail(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = False s.queue.join = mock.MagicMock(return_value=None) foo = 'foo' bar = 'bar' s.poll = mock.MagicMock( side_effect=[ [packet.Packet(packet.MESSAGE, data=bar)], [packet.Packet(packet.MESSAGE, data=bar)], exceptions.QueueEmpty, ] ) ws = mock.MagicMock() ws.wait.side_effect = [ packet.Packet(packet.MESSAGE, data=foo).encode(), RuntimeError, ] ws.send.side_effect = [None, RuntimeError] s._websocket_handler(ws) self._join_bg_tasks() assert s.closed def test_websocket_upgrade_with_large_packet(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = True s.queue.join = mock.MagicMock(return_value=None) probe = 'probe' ws = mock.MagicMock() ws.wait.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.UPGRADE, data='2' * 128).encode(), ] with pytest.raises(ValueError): s._websocket_handler(ws) self._join_bg_tasks() assert not s.upgraded def test_websocket_ignore_invalid_packet(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.connected = False s.queue.join = mock.MagicMock(return_value=None) foo = 'foo' bar = 'bar' s.poll = mock.MagicMock( side_effect=[ [packet.Packet(packet.MESSAGE, data=bar)], exceptions.QueueEmpty, ] ) ws = mock.MagicMock() ws.wait.side_effect = [ packet.Packet(packet.OPEN).encode(), packet.Packet(packet.MESSAGE, data=foo).encode(), None, ] s._websocket_handler(ws) self._join_bg_tasks() assert s.connected assert mock_server._trigger_event.call_count == 2 mock_server._trigger_event.assert_has_calls( [ mock.call('message', 'sid', foo, run_async=True), mock.call('disconnect', 'sid', run_async=False), ] ) ws.send.assert_called_with('4bar') def test_send_after_close(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.close(wait=False) with pytest.raises(exceptions.SocketIsClosedError): s.send(packet.Packet(packet.NOOP)) def test_close_after_close(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.close(wait=False) assert s.closed assert mock_server._trigger_event.call_count == 1 mock_server._trigger_event.assert_called_once_with( 'disconnect', 'sid', run_async=False ) s.close() assert mock_server._trigger_event.call_count == 1 def test_close_and_wait(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.queue = mock.MagicMock() s.close(wait=True) s.queue.join.assert_called_once_with() def test_close_without_wait(self): mock_server = self._get_mock_server() s = socket.Socket(mock_server, 'sid') s.queue = mock.MagicMock() s.close(wait=False) assert s.queue.join.call_count == 0
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,455
miguelgrinberg/python-engineio
refs/heads/main
/tests/asyncio/test_asyncio_socket.py
import asyncio import sys import time import unittest from unittest import mock import pytest from engineio import asyncio_socket from engineio import exceptions from engineio import packet from engineio import payload def AsyncMock(*args, **kwargs): """Return a mock asynchronous function.""" m = mock.MagicMock(*args, **kwargs) async def mock_coro(*args, **kwargs): return m(*args, **kwargs) mock_coro.mock = m return mock_coro def _run(coro): """Run the given coroutine.""" return asyncio.get_event_loop().run_until_complete(coro) @unittest.skipIf(sys.version_info < (3, 5), 'only for Python 3.5+') class TestSocket(unittest.TestCase): def _get_read_mock_coro(self, payload): mock_input = mock.MagicMock() mock_input.read = AsyncMock() mock_input.read.mock.return_value = payload return mock_input def _get_mock_server(self): mock_server = mock.Mock() mock_server.ping_timeout = 0.2 mock_server.ping_interval = 0.2 mock_server.ping_interval_grace_period = 0.001 mock_server.async_handlers = False mock_server.max_http_buffer_size = 128 mock_server._async = { 'asyncio': True, 'create_route': mock.MagicMock(), 'translate_request': mock.MagicMock(), 'make_response': mock.MagicMock(), 'websocket': 'w', } mock_server._async['translate_request'].return_value = 'request' mock_server._async['make_response'].return_value = 'response' mock_server._trigger_event = AsyncMock() def bg_task(target, *args, **kwargs): return asyncio.ensure_future(target(*args, **kwargs)) def create_queue(*args, **kwargs): queue = asyncio.Queue(*args, **kwargs) queue.Empty = asyncio.QueueEmpty return queue mock_server.start_background_task = bg_task mock_server.create_queue = create_queue return mock_server def test_create(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') assert s.server == mock_server assert s.sid == 'sid' assert not s.upgraded assert not s.closed assert hasattr(s.queue, 'get') assert hasattr(s.queue, 'put') assert hasattr(s.queue, 'task_done') assert hasattr(s.queue, 'join') def test_empty_poll(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') with pytest.raises(exceptions.QueueEmpty): _run(s.poll()) def test_poll(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') pkt1 = packet.Packet(packet.MESSAGE, data='hello') pkt2 = packet.Packet(packet.MESSAGE, data='bye') _run(s.send(pkt1)) _run(s.send(pkt2)) assert _run(s.poll()) == [pkt1, pkt2] def test_poll_none(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') _run(s.queue.put(None)) assert _run(s.poll()) == [] def test_poll_none_after_packet(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') pkt = packet.Packet(packet.MESSAGE, data='hello') _run(s.send(pkt)) _run(s.queue.put(None)) assert _run(s.poll()) == [pkt] assert _run(s.poll()) == [] def test_schedule_ping(self): mock_server = self._get_mock_server() mock_server.ping_interval = 0.01 s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.send = AsyncMock() async def schedule_ping(): s.schedule_ping() await asyncio.sleep(0.05) _run(schedule_ping()) assert s.last_ping is not None assert s.send.mock.call_args_list[0][0][0].encode() == '2' def test_schedule_ping_closed_socket(self): mock_server = self._get_mock_server() mock_server.ping_interval = 0.01 s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.send = AsyncMock() s.closed = True async def schedule_ping(): s.schedule_ping() await asyncio.sleep(0.05) _run(schedule_ping()) assert s.last_ping is None s.send.mock.assert_not_called() def test_pong(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.schedule_ping = mock.MagicMock() _run(s.receive(packet.Packet(packet.PONG, data='abc'))) s.schedule_ping.assert_called_once_with() def test_message_sync_handler(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') _run(s.receive(packet.Packet(packet.MESSAGE, data='foo'))) mock_server._trigger_event.mock.assert_called_once_with( 'message', 'sid', 'foo', run_async=False ) def test_message_async_handler(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') mock_server.async_handlers = True _run(s.receive(packet.Packet(packet.MESSAGE, data='foo'))) mock_server._trigger_event.mock.assert_called_once_with( 'message', 'sid', 'foo', run_async=True ) def test_invalid_packet(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') with pytest.raises(exceptions.UnknownPacketError): _run(s.receive(packet.Packet(packet.OPEN))) def test_timeout(self): mock_server = self._get_mock_server() mock_server.ping_interval = 6 mock_server.ping_interval_grace_period = 2 s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.last_ping = time.time() - 9 s.close = AsyncMock() _run(s.send('packet')) s.close.mock.assert_called_once_with(wait=False, abort=False) def test_polling_read(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'foo') pkt1 = packet.Packet(packet.MESSAGE, data='hello') pkt2 = packet.Packet(packet.MESSAGE, data='bye') _run(s.send(pkt1)) _run(s.send(pkt2)) environ = {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} packets = _run(s.handle_get_request(environ)) assert packets == [pkt1, pkt2] def test_polling_read_error(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'foo') environ = {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo'} with pytest.raises(exceptions.QueueEmpty): _run(s.handle_get_request(environ)) def test_polling_write(self): mock_server = self._get_mock_server() mock_server.max_http_buffer_size = 1000 pkt1 = packet.Packet(packet.MESSAGE, data='hello') pkt2 = packet.Packet(packet.MESSAGE, data='bye') p = payload.Payload(packets=[pkt1, pkt2]).encode().encode('utf-8') s = asyncio_socket.AsyncSocket(mock_server, 'foo') s.receive = AsyncMock() environ = { 'REQUEST_METHOD': 'POST', 'QUERY_STRING': 'sid=foo', 'CONTENT_LENGTH': len(p), 'wsgi.input': self._get_read_mock_coro(p), } _run(s.handle_post_request(environ)) assert s.receive.mock.call_count == 2 def test_polling_write_too_large(self): mock_server = self._get_mock_server() pkt1 = packet.Packet(packet.MESSAGE, data='hello') pkt2 = packet.Packet(packet.MESSAGE, data='bye') p = payload.Payload(packets=[pkt1, pkt2]).encode().encode('utf-8') mock_server.max_http_buffer_size = len(p) - 1 s = asyncio_socket.AsyncSocket(mock_server, 'foo') s.receive = AsyncMock() environ = { 'REQUEST_METHOD': 'POST', 'QUERY_STRING': 'sid=foo', 'CONTENT_LENGTH': len(p), 'wsgi.input': self._get_read_mock_coro(p), } with pytest.raises(exceptions.ContentTooLongError): _run(s.handle_post_request(environ)) def test_upgrade_handshake(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'foo') s._upgrade_websocket = AsyncMock() environ = { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=foo', 'HTTP_CONNECTION': 'Foo,Upgrade,Bar', 'HTTP_UPGRADE': 'websocket', } _run(s.handle_get_request(environ)) s._upgrade_websocket.mock.assert_called_once_with(environ) def test_upgrade(self): mock_server = self._get_mock_server() mock_server._async['websocket'] = mock.MagicMock() mock_ws = AsyncMock() mock_server._async['websocket'].return_value = mock_ws s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True environ = "foo" _run(s._upgrade_websocket(environ)) mock_server._async['websocket'].assert_called_once_with( s._websocket_handler, mock_server ) mock_ws.mock.assert_called_once_with(environ) def test_upgrade_twice(self): mock_server = self._get_mock_server() mock_server._async['websocket'] = mock.MagicMock() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True s.upgraded = True environ = "foo" with pytest.raises(IOError): _run(s._upgrade_websocket(environ)) def test_upgrade_packet(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True _run(s.receive(packet.Packet(packet.UPGRADE))) r = _run(s.poll()) assert len(r) == 1 assert r[0].encode() == packet.Packet(packet.NOOP).encode() def test_upgrade_no_probe(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True ws = mock.MagicMock() ws.wait = AsyncMock() ws.wait.mock.return_value = packet.Packet(packet.NOOP).encode() _run(s._websocket_handler(ws)) assert not s.upgraded def test_upgrade_no_upgrade_packet(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True s.queue.join = AsyncMock(return_value=None) ws = mock.MagicMock() ws.send = AsyncMock() ws.wait = AsyncMock() probe = 'probe' ws.wait.mock.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.NOOP).encode(), ] _run(s._websocket_handler(ws)) ws.send.mock.assert_called_once_with( packet.Packet(packet.PONG, data=probe).encode() ) assert _run(s.queue.get()).packet_type == packet.NOOP assert not s.upgraded def test_upgrade_not_supported(self): mock_server = self._get_mock_server() mock_server._async['websocket'] = None s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True environ = "foo" _run(s._upgrade_websocket(environ)) mock_server._bad_request.assert_called_once_with() def test_close_packet(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True s.close = AsyncMock() _run(s.receive(packet.Packet(packet.CLOSE))) s.close.mock.assert_called_once_with(wait=False, abort=True) def test_websocket_read_write(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = False s.queue.join = AsyncMock(return_value=None) foo = 'foo' bar = 'bar' s.poll = AsyncMock( side_effect=[[packet.Packet(packet.MESSAGE, data=bar)], None] ) ws = mock.MagicMock() ws.send = AsyncMock() ws.wait = AsyncMock() ws.wait.mock.side_effect = [ packet.Packet(packet.MESSAGE, data=foo).encode(), None, ] ws.close = AsyncMock() _run(s._websocket_handler(ws)) assert s.connected assert s.upgraded assert mock_server._trigger_event.mock.call_count == 2 mock_server._trigger_event.mock.assert_has_calls( [ mock.call('message', 'sid', 'foo', run_async=False), mock.call('disconnect', 'sid'), ] ) ws.send.mock.assert_called_with('4bar') ws.close.mock.assert_called() def test_websocket_upgrade_read_write(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True s.queue.join = AsyncMock(return_value=None) foo = 'foo' bar = 'bar' probe = 'probe' s.poll = AsyncMock( side_effect=[ [packet.Packet(packet.MESSAGE, data=bar)], exceptions.QueueEmpty, ] ) ws = mock.MagicMock() ws.send = AsyncMock() ws.wait = AsyncMock() ws.wait.mock.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.UPGRADE).encode(), packet.Packet(packet.MESSAGE, data=foo).encode(), None, ] ws.close = AsyncMock() _run(s._websocket_handler(ws)) assert s.upgraded assert mock_server._trigger_event.mock.call_count == 2 mock_server._trigger_event.mock.assert_has_calls( [ mock.call('message', 'sid', 'foo', run_async=False), mock.call('disconnect', 'sid'), ] ) ws.send.mock.assert_called_with('4bar') ws.close.mock.assert_called() def test_websocket_upgrade_with_payload(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True s.queue.join = AsyncMock(return_value=None) probe = 'probe' ws = mock.MagicMock() ws.send = AsyncMock() ws.wait = AsyncMock() ws.wait.mock.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.UPGRADE, data='2').encode(), ] ws.close = AsyncMock() _run(s._websocket_handler(ws)) assert s.upgraded def test_websocket_upgrade_with_backlog(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True s.queue.join = AsyncMock(return_value=None) probe = 'probe' foo = 'foo' ws = mock.MagicMock() ws.send = AsyncMock() ws.wait = AsyncMock() ws.wait.mock.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.UPGRADE, data='2').encode(), ] ws.close = AsyncMock() s.upgrading = True _run(s.send(packet.Packet(packet.MESSAGE, data=foo))) environ = {'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'sid=sid'} packets = _run(s.handle_get_request(environ)) assert len(packets) == 1 assert packets[0].encode() == '6' packets = _run(s.poll()) assert len(packets) == 1 assert packets[0].encode() == '4foo' _run(s._websocket_handler(ws)) assert s.upgraded assert not s.upgrading packets = _run(s.handle_get_request(environ)) assert len(packets) == 1 assert packets[0].encode() == '6' def test_websocket_read_write_wait_fail(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = False s.queue.join = AsyncMock(return_value=None) foo = 'foo' bar = 'bar' s.poll = AsyncMock( side_effect=[ [packet.Packet(packet.MESSAGE, data=bar)], [packet.Packet(packet.MESSAGE, data=bar)], exceptions.QueueEmpty, ] ) ws = mock.MagicMock() ws.send = AsyncMock() ws.wait = AsyncMock() ws.wait.mock.side_effect = [ packet.Packet(packet.MESSAGE, data=foo).encode(), RuntimeError, ] ws.send.mock.side_effect = [None, RuntimeError] ws.close = AsyncMock() _run(s._websocket_handler(ws)) assert s.closed def test_websocket_upgrade_with_large_packet(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = True s.queue.join = AsyncMock(return_value=None) probe = 'probe' ws = mock.MagicMock() ws.send = AsyncMock() ws.wait = AsyncMock() ws.wait.mock.side_effect = [ packet.Packet(packet.PING, data=probe).encode(), packet.Packet(packet.UPGRADE, data='2' * 128).encode(), ] with pytest.raises(ValueError): _run(s._websocket_handler(ws)) assert not s.upgraded def test_websocket_ignore_invalid_packet(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.connected = False s.queue.join = AsyncMock(return_value=None) foo = 'foo' bar = 'bar' s.poll = AsyncMock( side_effect=[ [packet.Packet(packet.MESSAGE, data=bar)], exceptions.QueueEmpty, ] ) ws = mock.MagicMock() ws.send = AsyncMock() ws.wait = AsyncMock() ws.wait.mock.side_effect = [ packet.Packet(packet.OPEN).encode(), packet.Packet(packet.MESSAGE, data=foo).encode(), None, ] ws.close = AsyncMock() _run(s._websocket_handler(ws)) assert s.connected assert mock_server._trigger_event.mock.call_count == 2 mock_server._trigger_event.mock.assert_has_calls( [ mock.call('message', 'sid', foo, run_async=False), mock.call('disconnect', 'sid'), ] ) ws.send.mock.assert_called_with('4bar') ws.close.mock.assert_called() def test_send_after_close(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') _run(s.close(wait=False)) with pytest.raises(exceptions.SocketIsClosedError): _run(s.send(packet.Packet(packet.NOOP))) def test_close_after_close(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') _run(s.close(wait=False)) assert s.closed assert mock_server._trigger_event.mock.call_count == 1 mock_server._trigger_event.mock.assert_called_once_with( 'disconnect', 'sid' ) _run(s.close()) assert mock_server._trigger_event.mock.call_count == 1 def test_close_and_wait(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.queue = mock.MagicMock() s.queue.put = AsyncMock() s.queue.join = AsyncMock() _run(s.close(wait=True)) s.queue.join.mock.assert_called_once_with() def test_close_without_wait(self): mock_server = self._get_mock_server() s = asyncio_socket.AsyncSocket(mock_server, 'sid') s.queue = mock.MagicMock() s.queue.put = AsyncMock() s.queue.join = AsyncMock() _run(s.close(wait=False)) assert s.queue.join.mock.call_count == 0
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,456
miguelgrinberg/python-engineio
refs/heads/main
/examples/server/asgi/simple.py
import uvicorn import engineio eio = engineio.AsyncServer(async_mode='asgi') app = engineio.ASGIApp(eio, static_files={ '/': 'simple.html', '/static': 'static', }) @eio.on('connect') def connect(sid, environ): print("connect ", sid) @eio.on('message') async def message(sid, data): print('message from', sid, data) await eio.send(sid, 'Thank you for your message!') @eio.on('disconnect') def disconnect(sid): print('disconnect ', sid) if __name__ == '__main__': uvicorn.run(app, host='127.0.0.1', port=5000)
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,457
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/async_drivers/aiohttp.py
import asyncio import sys from urllib.parse import urlsplit from aiohttp.web import Response, WebSocketResponse def create_route(app, engineio_server, engineio_endpoint): """This function sets up the engine.io endpoint as a route for the application. Note that both GET and POST requests must be hooked up on the engine.io endpoint. """ app.router.add_get(engineio_endpoint, engineio_server.handle_request) app.router.add_post(engineio_endpoint, engineio_server.handle_request) app.router.add_route('OPTIONS', engineio_endpoint, engineio_server.handle_request) def translate_request(request): """This function takes the arguments passed to the request handler and uses them to generate a WSGI compatible environ dictionary. """ message = request._message payload = request._payload uri_parts = urlsplit(message.path) environ = { 'wsgi.input': payload, 'wsgi.errors': sys.stderr, 'wsgi.version': (1, 0), 'wsgi.async': True, 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'SERVER_SOFTWARE': 'aiohttp', 'REQUEST_METHOD': message.method, 'QUERY_STRING': uri_parts.query or '', 'RAW_URI': message.path, 'SERVER_PROTOCOL': 'HTTP/%s.%s' % message.version, 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '0', 'SERVER_NAME': 'aiohttp', 'SERVER_PORT': '0', 'aiohttp.request': request } for hdr_name, hdr_value in message.headers.items(): hdr_name = hdr_name.upper() if hdr_name == 'CONTENT-TYPE': environ['CONTENT_TYPE'] = hdr_value continue elif hdr_name == 'CONTENT-LENGTH': environ['CONTENT_LENGTH'] = hdr_value continue key = 'HTTP_%s' % hdr_name.replace('-', '_') if key in environ: hdr_value = '%s,%s' % (environ[key], hdr_value) environ[key] = hdr_value environ['wsgi.url_scheme'] = environ.get('HTTP_X_FORWARDED_PROTO', 'http') path_info = uri_parts.path environ['PATH_INFO'] = path_info environ['SCRIPT_NAME'] = '' return environ def make_response(status, headers, payload, environ): """This function generates an appropriate response object for this async mode. """ return Response(body=payload, status=int(status.split()[0]), headers=headers) class WebSocket(object): # pragma: no cover """ This wrapper class provides a aiohttp WebSocket interface that is somewhat compatible with eventlet's implementation. """ def __init__(self, handler, server): self.handler = handler self._sock = None async def __call__(self, environ): request = environ['aiohttp.request'] self._sock = WebSocketResponse(max_msg_size=0) await self._sock.prepare(request) self.environ = environ await self.handler(self) return self._sock async def close(self): await self._sock.close() async def send(self, message): if isinstance(message, bytes): f = self._sock.send_bytes else: f = self._sock.send_str if asyncio.iscoroutinefunction(f): await f(message) else: f(message) async def wait(self): msg = await self._sock.receive() if not isinstance(msg.data, bytes) and \ not isinstance(msg.data, str): raise IOError() return msg.data _async = { 'asyncio': True, 'create_route': create_route, 'translate_request': translate_request, 'make_response': make_response, 'websocket': WebSocket, }
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,458
miguelgrinberg/python-engineio
refs/heads/main
/tests/common/test_client.py
import logging import ssl import time import unittest from unittest import mock import pytest import websocket from engineio import client from engineio import exceptions from engineio import json from engineio import packet from engineio import payload class TestClient(unittest.TestCase): def test_is_asyncio_based(self): c = client.Client() assert not c.is_asyncio_based() def test_create(self): c = client.Client() assert c.handlers == {} for attr in [ 'base_url', 'transports', 'sid', 'upgrades', 'ping_interval', 'ping_timeout', 'http', 'ws', 'read_loop_task', 'write_loop_task', 'queue', ]: assert getattr(c, attr) is None, attr + ' is not None' assert c.state == 'disconnected' def test_custon_json(self): client.Client() assert packet.Packet.json == json client.Client(json='foo') assert packet.Packet.json == 'foo' packet.Packet.json = json def test_logger(self): c = client.Client(logger=False) assert c.logger.getEffectiveLevel() == logging.ERROR c.logger.setLevel(logging.NOTSET) c = client.Client(logger=True) assert c.logger.getEffectiveLevel() == logging.INFO c.logger.setLevel(logging.WARNING) c = client.Client(logger=True) assert c.logger.getEffectiveLevel() == logging.WARNING c.logger.setLevel(logging.NOTSET) my_logger = logging.Logger('foo') c = client.Client(logger=my_logger) assert c.logger == my_logger def test_custom_timeout(self): c = client.Client() assert c.request_timeout == 5 c = client.Client(request_timeout=27) assert c.request_timeout == 27 def test_on_event(self): c = client.Client() @c.on('connect') def foo(): pass c.on('disconnect', foo) assert c.handlers['connect'] == foo assert c.handlers['disconnect'] == foo def test_on_event_invalid(self): c = client.Client() with pytest.raises(ValueError): c.on('invalid') def test_already_connected(self): c = client.Client() c.state = 'connected' with pytest.raises(ValueError): c.connect('http://foo') def test_invalid_transports(self): c = client.Client() with pytest.raises(ValueError): c.connect('http://foo', transports=['foo', 'bar']) def test_some_invalid_transports(self): c = client.Client() c._connect_websocket = mock.MagicMock() c.connect('http://foo', transports=['foo', 'websocket', 'bar']) assert c.transports == ['websocket'] def test_connect_polling(self): c = client.Client() c._connect_polling = mock.MagicMock(return_value='foo') assert c.connect('http://foo') == 'foo' c._connect_polling.assert_called_once_with( 'http://foo', {}, 'engine.io' ) c = client.Client() c._connect_polling = mock.MagicMock(return_value='foo') assert c.connect('http://foo', transports=['polling']) == 'foo' c._connect_polling.assert_called_once_with( 'http://foo', {}, 'engine.io' ) c = client.Client() c._connect_polling = mock.MagicMock(return_value='foo') assert ( c.connect('http://foo', transports=['polling', 'websocket']) == 'foo' ) c._connect_polling.assert_called_once_with( 'http://foo', {}, 'engine.io' ) def test_connect_websocket(self): c = client.Client() c._connect_websocket = mock.MagicMock(return_value='foo') assert c.connect('http://foo', transports=['websocket']) == 'foo' c._connect_websocket.assert_called_once_with( 'http://foo', {}, 'engine.io' ) c = client.Client() c._connect_websocket = mock.MagicMock(return_value='foo') assert c.connect('http://foo', transports='websocket') == 'foo' c._connect_websocket.assert_called_once_with( 'http://foo', {}, 'engine.io' ) def test_connect_query_string(self): c = client.Client() c._connect_polling = mock.MagicMock(return_value='foo') assert c.connect('http://foo?bar=baz') == 'foo' c._connect_polling.assert_called_once_with( 'http://foo?bar=baz', {}, 'engine.io' ) def test_connect_custom_headers(self): c = client.Client() c._connect_polling = mock.MagicMock(return_value='foo') assert c.connect('http://foo', headers={'Foo': 'Bar'}) == 'foo' c._connect_polling.assert_called_once_with( 'http://foo', {'Foo': 'Bar'}, 'engine.io' ) def test_wait(self): c = client.Client() c.read_loop_task = mock.MagicMock() c.wait() c.read_loop_task.join.assert_called_once_with() def test_wait_no_task(self): c = client.Client() c.read_loop_task = None c.wait() # should not block def test_send(self): c = client.Client() saved_packets = [] def fake_send_packet(pkt): saved_packets.append(pkt) c._send_packet = fake_send_packet c.send('foo') c.send('foo') c.send(b'foo') assert saved_packets[0].packet_type == packet.MESSAGE assert saved_packets[0].data == 'foo' assert not saved_packets[0].binary assert saved_packets[1].packet_type == packet.MESSAGE assert saved_packets[1].data == 'foo' assert not saved_packets[1].binary assert saved_packets[2].packet_type == packet.MESSAGE assert saved_packets[2].data == b'foo' assert saved_packets[2].binary def test_disconnect_not_connected(self): c = client.Client() c.state = 'foo' c.sid = 'bar' c.disconnect() assert c.state == 'disconnected' assert c.sid is None def test_disconnect_polling(self): c = client.Client() client.connected_clients.append(c) c.state = 'connected' c.current_transport = 'polling' c.queue = mock.MagicMock() c.read_loop_task = mock.MagicMock() c.ws = mock.MagicMock() c._trigger_event = mock.MagicMock() c.disconnect() c.read_loop_task.join.assert_called_once_with() c.ws.mock.assert_not_called() assert c not in client.connected_clients c._trigger_event.assert_called_once_with('disconnect', run_async=False) def test_disconnect_websocket(self): c = client.Client() client.connected_clients.append(c) c.state = 'connected' c.current_transport = 'websocket' c.queue = mock.MagicMock() c.read_loop_task = mock.MagicMock() c.ws = mock.MagicMock() c._trigger_event = mock.MagicMock() c.disconnect() c.read_loop_task.join.assert_called_once_with() c.ws.close.assert_called_once_with() assert c not in client.connected_clients c._trigger_event.assert_called_once_with('disconnect', run_async=False) def test_disconnect_polling_abort(self): c = client.Client() client.connected_clients.append(c) c.state = 'connected' c.current_transport = 'polling' c.queue = mock.MagicMock() c.read_loop_task = mock.MagicMock() c.ws = mock.MagicMock() c.disconnect(abort=True) c.queue.join.assert_not_called() c.read_loop_task.join.assert_not_called() c.ws.mock.assert_not_called() assert c not in client.connected_clients def test_disconnect_websocket_abort(self): c = client.Client() client.connected_clients.append(c) c.state = 'connected' c.current_transport = 'websocket' c.queue = mock.MagicMock() c.read_loop_task = mock.MagicMock() c.ws = mock.MagicMock() c.disconnect(abort=True) c.queue.join.assert_not_called() c.read_loop_task.join.assert_not_called() c.ws.mock.assert_not_called() assert c not in client.connected_clients def test_current_transport(self): c = client.Client() c.current_transport = 'foo' assert c.transport() == 'foo' def test_background_tasks(self): flag = {} def bg_task(): flag['task'] = True c = client.Client() task = c.start_background_task(bg_task) task.join() assert 'task' in flag assert flag['task'] def test_sleep(self): c = client.Client() t = time.time() c.sleep(0.1) assert time.time() - t > 0.1 def test_create_queue(self): c = client.Client() q = c.create_queue() with pytest.raises(q.Empty): q.get(timeout=0.01) def test_create_event(self): c = client.Client() e = c.create_event() assert not e.is_set() e.set() assert e.is_set() @mock.patch('engineio.client.time.time', return_value=123.456) @mock.patch('engineio.client.Client._send_request', return_value=None) def test_polling_connection_failed(self, _send_request, _time): c = client.Client() with pytest.raises(exceptions.ConnectionError): c.connect('http://foo', headers={'Foo': 'Bar'}) _send_request.assert_called_once_with( 'GET', 'http://foo/engine.io/?transport=polling&EIO=4&t=123.456', headers={'Foo': 'Bar'}, timeout=5, ) @mock.patch('engineio.client.Client._send_request') def test_polling_connection_404(self, _send_request): _send_request.return_value.status_code = 404 _send_request.return_value.json.return_value = {'foo': 'bar'} c = client.Client() try: c.connect('http://foo') except exceptions.ConnectionError as exc: assert len(exc.args) == 2 assert ( exc.args[0] == 'Unexpected status code 404 in server response' ) assert exc.args[1] == {'foo': 'bar'} @mock.patch('engineio.client.Client._send_request') def test_polling_connection_404_no_json(self, _send_request): _send_request.return_value.status_code = 404 _send_request.return_value.json.side_effect = json.JSONDecodeError( 'error', '<html></html>', 0) c = client.Client() try: c.connect('http://foo') except exceptions.ConnectionError as exc: assert len(exc.args) == 2 assert ( exc.args[0] == 'Unexpected status code 404 in server response' ) assert exc.args[1] is None @mock.patch('engineio.client.Client._send_request') def test_polling_connection_invalid_packet(self, _send_request): _send_request.return_value.status_code = 200 _send_request.return_value.content = b'foo' c = client.Client() with pytest.raises(exceptions.ConnectionError): c.connect('http://foo') @mock.patch('engineio.client.Client._send_request') def test_polling_connection_no_open_packet(self, _send_request): _send_request.return_value.status_code = 200 _send_request.return_value.content = payload.Payload( packets=[ packet.Packet( packet.CLOSE, { 'sid': '123', 'upgrades': [], 'pingInterval': 10, 'pingTimeout': 20, }, ) ] ).encode().encode('utf-8') c = client.Client() with pytest.raises(exceptions.ConnectionError): c.connect('http://foo') @mock.patch('engineio.client.Client._send_request') def test_polling_connection_successful(self, _send_request): _send_request.return_value.status_code = 200 _send_request.return_value.content = payload.Payload( packets=[ packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ) ] ).encode().encode('utf-8') c = client.Client() c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('http://foo') time.sleep(0.1) c._read_loop_polling.assert_called_once_with() c._read_loop_websocket.assert_not_called() c._write_loop.assert_called_once_with() on_connect.assert_called_once_with() assert c in client.connected_clients assert ( c.base_url == 'http://foo/engine.io/?transport=polling&EIO=4&sid=123' ) assert c.sid == '123' assert c.ping_interval == 1 assert c.ping_timeout == 2 assert c.upgrades == [] assert c.transport() == 'polling' @mock.patch('engineio.client.Client._send_request') def test_polling_https_noverify_connection_successful(self, _send_request): _send_request.return_value.status_code = 200 _send_request.return_value.content = payload.Payload( packets=[ packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ) ] ).encode().encode('utf-8') c = client.Client(ssl_verify=False) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('https://foo') time.sleep(0.1) c._read_loop_polling.assert_called_once_with() c._read_loop_websocket.assert_not_called() c._write_loop.assert_called_once_with() on_connect.assert_called_once_with() assert c in client.connected_clients assert ( c.base_url == 'https://foo/engine.io/?transport=polling&EIO=4&sid=123' ) assert c.sid == '123' assert c.ping_interval == 1 assert c.ping_timeout == 2 assert c.upgrades == [] assert c.transport() == 'polling' @mock.patch('engineio.client.Client._send_request') def test_polling_connection_with_more_packets(self, _send_request): _send_request.return_value.status_code = 200 _send_request.return_value.content = payload.Payload( packets=[ packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ), packet.Packet(packet.NOOP), ] ).encode().encode('utf-8') c = client.Client() c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() c._receive_packet = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('http://foo') time.sleep(0.1) assert c._receive_packet.call_count == 1 assert ( c._receive_packet.call_args_list[0][0][0].packet_type == packet.NOOP ) @mock.patch('engineio.client.Client._send_request') def test_polling_connection_upgraded(self, _send_request): _send_request.return_value.status_code = 200 _send_request.return_value.content = payload.Payload( packets=[ packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': ['websocket'], 'pingInterval': 1000, 'pingTimeout': 2000, }, ) ] ).encode().encode('utf-8') c = client.Client() c._connect_websocket = mock.MagicMock(return_value=True) on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('http://foo') c._connect_websocket.assert_called_once_with( 'http://foo', {}, 'engine.io' ) on_connect.assert_called_once_with() assert c in client.connected_clients assert ( c.base_url == 'http://foo/engine.io/?transport=polling&EIO=4&sid=123' ) assert c.sid == '123' assert c.ping_interval == 1 assert c.ping_timeout == 2 assert c.upgrades == ['websocket'] @mock.patch('engineio.client.Client._send_request') def test_polling_connection_not_upgraded(self, _send_request): _send_request.return_value.status_code = 200 _send_request.return_value.content = payload.Payload( packets=[ packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': ['websocket'], 'pingInterval': 1000, 'pingTimeout': 2000, }, ) ] ).encode().encode('utf-8') c = client.Client() c._connect_websocket = mock.MagicMock(return_value=False) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('http://foo') time.sleep(0.1) c._connect_websocket.assert_called_once_with( 'http://foo', {}, 'engine.io' ) c._read_loop_polling.assert_called_once_with() c._read_loop_websocket.assert_not_called() c._write_loop.assert_called_once_with() on_connect.assert_called_once_with() assert c in client.connected_clients @mock.patch('engineio.client.time.time', return_value=123.456) @mock.patch( 'engineio.client.websocket.create_connection', side_effect=[ConnectionError], ) def test_websocket_connection_failed(self, create_connection, _time): c = client.Client() with pytest.raises(exceptions.ConnectionError): c.connect( 'http://foo', transports=['websocket'], headers={'Foo': 'Bar'} ) create_connection.assert_called_once_with( 'ws://foo/engine.io/?transport=websocket&EIO=4&t=123.456', header={'Foo': 'Bar'}, cookie=None, enable_multithread=True, timeout=5 ) @mock.patch('engineio.client.time.time', return_value=123.456) @mock.patch( 'engineio.client.websocket.create_connection', side_effect=[ConnectionError], ) def test_websocket_connection_extra(self, create_connection, _time): c = client.Client(websocket_extra_options={'header': {'Baz': 'Qux'}, 'timeout': 10}) with pytest.raises(exceptions.ConnectionError): c.connect( 'http://foo', transports=['websocket'], headers={'Foo': 'Bar'} ) create_connection.assert_called_once_with( 'ws://foo/engine.io/?transport=websocket&EIO=4&t=123.456', header={'Foo': 'Bar', 'Baz': 'Qux'}, cookie=None, enable_multithread=True, timeout=10 ) @mock.patch('engineio.client.time.time', return_value=123.456) @mock.patch( 'engineio.client.websocket.create_connection', side_effect=[websocket.WebSocketException], ) def test_websocket_connection_failed_with_websocket_error( self, create_connection, _time ): c = client.Client() with pytest.raises(exceptions.ConnectionError): c.connect( 'http://foo', transports=['websocket'], headers={'Foo': 'Bar'} ) create_connection.assert_called_once_with( 'ws://foo/engine.io/?transport=websocket&EIO=4&t=123.456', header={'Foo': 'Bar'}, cookie=None, enable_multithread=True, timeout=5 ) @mock.patch('engineio.client.time.time', return_value=123.456) @mock.patch( 'engineio.client.websocket.create_connection', side_effect=[ConnectionError], ) def test_websocket_upgrade_failed(self, create_connection, _time): c = client.Client() c.ping_interval = 1 c.ping_timeout = 2 c.sid = '123' assert not c.connect('http://foo', transports=['websocket']) create_connection.assert_called_once_with( 'ws://foo/engine.io/?transport=websocket&EIO=4&sid=123&t=123.456', header={}, cookie=None, enable_multithread=True, timeout=5 ) @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_no_open_packet(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.CLOSE ).encode() c = client.Client() with pytest.raises(exceptions.ConnectionError): c.connect('http://foo', transports=['websocket']) @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_successful(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() c = client.Client() c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('ws://foo', transports=['websocket']) time.sleep(0.1) c._read_loop_polling.assert_not_called() c._read_loop_websocket.assert_called_once_with() c._write_loop.assert_called_once_with() on_connect.assert_called_once_with() assert c in client.connected_clients assert c.base_url == 'ws://foo/engine.io/?transport=websocket&EIO=4' assert c.sid == '123' assert c.ping_interval == 1 assert c.ping_timeout == 2 assert c.upgrades == [] assert c.transport() == 'websocket' assert c.ws == create_connection.return_value assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'header': {}, 'cookie': None, 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_https_noverify_connection_successful( self, create_connection ): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() c = client.Client(ssl_verify=False) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('wss://foo', transports=['websocket']) time.sleep(0.1) c._read_loop_polling.assert_not_called() c._read_loop_websocket.assert_called_once_with() c._write_loop.assert_called_once_with() on_connect.assert_called_once_with() assert c in client.connected_clients assert c.base_url == 'wss://foo/engine.io/?transport=websocket&EIO=4' assert c.sid == '123' assert c.ping_interval == 1 assert c.ping_timeout == 2 assert c.upgrades == [] assert c.transport() == 'websocket' assert c.ws == create_connection.return_value assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'header': {}, 'cookie': None, 'enable_multithread': True, 'timeout': 5, 'sslopt': {'cert_reqs': ssl.CERT_NONE}, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_with_cookies(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [mock.MagicMock(), mock.MagicMock()] http.cookies[0].name = 'key' http.cookies[0].value = 'value' http.cookies[1].name = 'key2' http.cookies[1].value = 'value2' http.auth = None http.proxies = None http.cert = None c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('ws://foo', transports=['websocket']) time.sleep(0.1) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'header': {}, 'cookie': 'key=value; key2=value2', 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_with_cookie_header(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [] http.auth = None http.proxies = None http.cert = None c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect( 'ws://foo', headers={'Foo': 'bar', 'Cookie': 'key=value'}, transports=['websocket'], ) time.sleep(0.1) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'header': {'Foo': 'bar'}, 'cookie': 'key=value', 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_with_cookies_and_headers( self, create_connection ): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [mock.MagicMock(), mock.MagicMock()] http.cookies[0].name = 'key' http.cookies[0].value = 'value' http.cookies[1].name = 'key2' http.cookies[1].value = 'value2' http.auth = None http.proxies = None http.cert = None c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect( 'ws://foo', headers={'Cookie': 'key3=value3'}, transports=['websocket'], ) time.sleep(0.1) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'header': {}, 'enable_multithread': True, 'timeout': 5, 'cookie': 'key=value; key2=value2; key3=value3', } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_with_auth(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [] http.auth = ('foo', 'bar') http.proxies = None http.cert = None c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('ws://foo', transports=['websocket']) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'header': {'Authorization': 'Basic Zm9vOmJhcg=='}, 'cookie': '', 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_with_cert(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [] http.auth = None http.proxies = None http.cert = 'foo.crt' c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('ws://foo', transports=['websocket']) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'sslopt': {'certfile': 'foo.crt'}, 'header': {}, 'cookie': '', 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_with_cert_and_key(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [] http.auth = None http.proxies = None http.cert = ('foo.crt', 'key.pem') c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('ws://foo', transports=['websocket']) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'sslopt': {'certfile': 'foo.crt', 'keyfile': 'key.pem'}, 'header': {}, 'cookie': '', 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_verify_with_cert_and_key( self, create_connection ): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [] http.auth = None http.proxies = None http.cert = ('foo.crt', 'key.pem') http.verify = 'ca-bundle.crt' c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('ws://foo', transports=['websocket']) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'sslopt': { 'certfile': 'foo.crt', 'keyfile': 'key.pem', 'ca_certs': 'ca-bundle.crt' }, 'header': {}, 'cookie': '', 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_with_proxies(self, create_connection): all_urls = [ 'ws://foo', 'ws://foo', 'ws://foo', 'ws://foo', 'ws://foo', 'wss://foo', 'wss://foo', ] all_proxies = [ {'http': 'foo.com:1234'}, {'https': 'foo.com:1234'}, {'http': 'foo.com:1234', 'ws': 'bar.com:4321'}, {}, {'http': 'user:pass@foo.com:1234'}, {'https': 'foo.com:1234'}, {'https': 'foo.com:1234', 'wss': 'bar.com:4321'}, ] all_results = [ ('foo.com', 1234, None), None, ('bar.com', 4321, None), None, ('foo.com', 1234, ('user', 'pass')), ('foo.com', 1234, None), ('bar.com', 4321, None), ] for url, proxies, results in zip(all_urls, all_proxies, all_results): create_connection.reset_mock() create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [] http.auth = None http.proxies = proxies http.cert = None c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect(url, transports=['websocket']) assert len(create_connection.call_args_list) == 1 expected_results = { 'header': {}, 'cookie': '', 'enable_multithread': True, 'timeout': 5, } if results: expected_results.update({ 'http_proxy_host': results[0], 'http_proxy_port': results[1], 'http_proxy_auth': results[2]}) assert create_connection.call_args[1] == expected_results @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_without_verify(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [] http.auth = None http.proxies = None http.cert = None http.verify = False c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('ws://foo', transports=['websocket']) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'sslopt': {"cert_reqs": ssl.CERT_NONE}, 'header': {}, 'cookie': '', 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_connection_with_verify(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() http = mock.MagicMock() http.cookies = [] http.auth = None http.proxies = None http.cert = None http.verify = 'ca-bundle.crt' c = client.Client(http_session=http) c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) c.connect('ws://foo', transports=['websocket']) assert len(create_connection.call_args_list) == 1 assert create_connection.call_args[1] == { 'sslopt': {'ca_certs': 'ca-bundle.crt'}, 'header': {}, 'cookie': '', 'enable_multithread': True, 'timeout': 5, } @mock.patch('engineio.client.websocket.create_connection') def test_websocket_upgrade_no_pong(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.OPEN, { 'sid': '123', 'upgrades': [], 'pingInterval': 1000, 'pingTimeout': 2000, }, ).encode() c = client.Client() c.sid = '123' c.current_transport = 'polling' c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) assert not c.connect('ws://foo', transports=['websocket']) c._read_loop_polling.assert_not_called() c._read_loop_websocket.assert_not_called() c._write_loop.assert_not_called() on_connect.assert_not_called() assert c.transport() == 'polling' @mock.patch('engineio.client.websocket.create_connection') def test_websocket_upgrade_successful(self, create_connection): create_connection.return_value.recv.return_value = packet.Packet( packet.PONG, 'probe').encode() c = client.Client() c.ping_interval = 1 c.ping_timeout = 2 c.sid = '123' c.base_url = 'http://foo' c.current_transport = 'polling' c._read_loop_polling = mock.MagicMock() c._read_loop_websocket = mock.MagicMock() c._write_loop = mock.MagicMock() on_connect = mock.MagicMock() c.on('connect', on_connect) assert c.connect('ws://foo', transports=['websocket']) time.sleep(0.1) c._read_loop_polling.assert_not_called() c._read_loop_websocket.assert_called_once_with() c._write_loop.assert_called_once_with() on_connect.assert_not_called() # was called by polling assert c not in client.connected_clients # was added by polling assert c.base_url == 'http://foo' # not changed assert c.sid == '123' # not changed assert c.transport() == 'websocket' assert c.ws == create_connection.return_value assert create_connection.return_value.send.call_args_list[0] == ( (packet.Packet(packet.PING, 'probe').encode(),), ) # ping assert create_connection.return_value.send.call_args_list[1] == ( (packet.Packet(packet.UPGRADE).encode(),), ) # upgrade def test_receive_unknown_packet(self): c = client.Client() c._receive_packet(packet.Packet(encoded_packet='9')) # should be ignored def test_receive_noop_packet(self): c = client.Client() c._receive_packet(packet.Packet(packet.NOOP)) # should be ignored def test_receive_ping_packet(self): c = client.Client() c._send_packet = mock.MagicMock() c._receive_packet(packet.Packet(packet.PING)) assert c._send_packet.call_args_list[0][0][0].encode() == '3' # PONG def test_receive_message_packet(self): c = client.Client() c._trigger_event = mock.MagicMock() c._receive_packet(packet.Packet(packet.MESSAGE, {'foo': 'bar'})) c._trigger_event.assert_called_once_with( 'message', {'foo': 'bar'}, run_async=True ) def test_receive_close_packet(self): c = client.Client() c.disconnect = mock.MagicMock() c._receive_packet(packet.Packet(packet.CLOSE)) c.disconnect.assert_called_once_with(abort=True) def test_send_packet_disconnected(self): c = client.Client() c.queue = c.create_queue() c.state = 'disconnected' c._send_packet(packet.Packet(packet.NOOP)) assert c.queue.empty() def test_send_packet(self): c = client.Client() c.queue = c.create_queue() c.state = 'connected' c._send_packet(packet.Packet(packet.NOOP)) assert not c.queue.empty() pkt = c.queue.get() assert pkt.packet_type == packet.NOOP def test_trigger_event(self): c = client.Client() f = {} @c.on('connect') def foo(): return 'foo' @c.on('message') def bar(data): f['bar'] = data return 'bar' r = c._trigger_event('connect', run_async=False) assert r == 'foo' r = c._trigger_event('message', 123, run_async=True) r.join() assert f['bar'] == 123 r = c._trigger_event('message', 321) assert r == 'bar' def test_trigger_unknown_event(self): c = client.Client() c._trigger_event('connect', run_async=False) c._trigger_event('message', 123, run_async=True) # should do nothing def test_trigger_event_error(self): c = client.Client() @c.on('connect') def foo(): return 1 / 0 @c.on('message') def bar(data): return 1 / 0 r = c._trigger_event('connect', run_async=False) assert r is None r = c._trigger_event('message', 123, run_async=False) assert r is None def test_engineio_url(self): c = client.Client() assert ( c._get_engineio_url('http://foo', 'bar', 'polling') == 'http://foo/bar/?transport=polling&EIO=4' ) assert ( c._get_engineio_url('http://foo', 'bar', 'websocket') == 'ws://foo/bar/?transport=websocket&EIO=4' ) assert ( c._get_engineio_url('ws://foo', 'bar', 'polling') == 'http://foo/bar/?transport=polling&EIO=4' ) assert ( c._get_engineio_url('ws://foo', 'bar', 'websocket') == 'ws://foo/bar/?transport=websocket&EIO=4' ) assert ( c._get_engineio_url('https://foo', 'bar', 'polling') == 'https://foo/bar/?transport=polling&EIO=4' ) assert ( c._get_engineio_url('https://foo', 'bar', 'websocket') == 'wss://foo/bar/?transport=websocket&EIO=4' ) assert ( c._get_engineio_url('http://foo?baz=1', 'bar', 'polling') == 'http://foo/bar/?baz=1&transport=polling&EIO=4' ) assert ( c._get_engineio_url('http://foo#baz', 'bar', 'polling') == 'http://foo/bar/?transport=polling&EIO=4' ) def test_read_loop_polling_disconnected(self): c = client.Client() c.state = 'disconnected' c._trigger_event = mock.MagicMock() c.write_loop_task = mock.MagicMock() c._read_loop_polling() c.write_loop_task.join.assert_called_once_with() c._trigger_event.assert_not_called() @mock.patch('engineio.client.time.time', return_value=123.456) def test_read_loop_polling_no_response(self, _time): c = client.Client() c.ping_interval = 25 c.ping_timeout = 5 c.state = 'connected' c.base_url = 'http://foo' c.queue = mock.MagicMock() c._send_request = mock.MagicMock(return_value=None) c._trigger_event = mock.MagicMock() c.write_loop_task = mock.MagicMock() c._read_loop_polling() assert c.state == 'disconnected' c.queue.put.assert_called_once_with(None) c.write_loop_task.join.assert_called_once_with() c._send_request.assert_called_once_with( 'GET', 'http://foo&t=123.456', timeout=30 ) c._trigger_event.assert_called_once_with('disconnect', run_async=False) @mock.patch('engineio.client.time.time', return_value=123.456) def test_read_loop_polling_bad_status(self, _time): c = client.Client() c.ping_interval = 25 c.ping_timeout = 5 c.state = 'connected' c.base_url = 'http://foo' c.queue = mock.MagicMock() c._send_request = mock.MagicMock() c._send_request.return_value.status_code = 400 c.write_loop_task = mock.MagicMock() c._read_loop_polling() assert c.state == 'disconnected' c.queue.put.assert_called_once_with(None) c.write_loop_task.join.assert_called_once_with() c._send_request.assert_called_once_with( 'GET', 'http://foo&t=123.456', timeout=30 ) @mock.patch('engineio.client.time.time', return_value=123.456) def test_read_loop_polling_bad_packet(self, _time): c = client.Client() c.ping_interval = 25 c.ping_timeout = 60 c.state = 'connected' c.base_url = 'http://foo' c.queue = mock.MagicMock() c._send_request = mock.MagicMock() c._send_request.return_value.status_code = 200 c._send_request.return_value.content = b'foo' c.write_loop_task = mock.MagicMock() c._read_loop_polling() assert c.state == 'disconnected' c.queue.put.assert_called_once_with(None) c.write_loop_task.join.assert_called_once_with() c._send_request.assert_called_once_with( 'GET', 'http://foo&t=123.456', timeout=65 ) def test_read_loop_polling(self): c = client.Client() c.ping_interval = 25 c.ping_timeout = 5 c.state = 'connected' c.base_url = 'http://foo' c.queue = mock.MagicMock() c._send_request = mock.MagicMock() c._send_request.side_effect = [ mock.MagicMock( status_code=200, content=payload.Payload( packets=[ packet.Packet(packet.PING), packet.Packet(packet.NOOP), ] ).encode().encode('utf-8'), ), None, ] c.write_loop_task = mock.MagicMock() c._receive_packet = mock.MagicMock() c._read_loop_polling() assert c.state == 'disconnected' c.queue.put.assert_called_once_with(None) assert c._send_request.call_count == 2 assert c._receive_packet.call_count == 2 assert c._receive_packet.call_args_list[0][0][0].encode() == '2' assert c._receive_packet.call_args_list[1][0][0].encode() == '6' def test_read_loop_websocket_disconnected(self): c = client.Client() c.state = 'disconnected' c.write_loop_task = mock.MagicMock() c._read_loop_websocket() c.write_loop_task.join.assert_called_once_with() def test_read_loop_websocket_timeout(self): c = client.Client() c.state = 'connected' c.queue = mock.MagicMock() c.ws = mock.MagicMock() c.ws.recv.side_effect = websocket.WebSocketTimeoutException c.write_loop_task = mock.MagicMock() c._read_loop_websocket() assert c.state == 'disconnected' c.queue.put.assert_called_once_with(None) c.write_loop_task.join.assert_called_once_with() def test_read_loop_websocket_no_response(self): c = client.Client() c.state = 'connected' c.queue = mock.MagicMock() c.ws = mock.MagicMock() c.ws.recv.side_effect = websocket.WebSocketConnectionClosedException c.write_loop_task = mock.MagicMock() c._read_loop_websocket() assert c.state == 'disconnected' c.queue.put.assert_called_once_with(None) c.write_loop_task.join.assert_called_once_with() def test_read_loop_websocket_unexpected_error(self): c = client.Client() c.state = 'connected' c.queue = mock.MagicMock() c.ws = mock.MagicMock() c.ws.recv.side_effect = ValueError c.write_loop_task = mock.MagicMock() c._read_loop_websocket() assert c.state == 'disconnected' c.queue.put.assert_called_once_with(None) c.write_loop_task.join.assert_called_once_with() def test_read_loop_websocket(self): c = client.Client() c.ping_interval = 1 c.ping_timeout = 2 c.state = 'connected' c.queue = mock.MagicMock() c.ws = mock.MagicMock() c.ws.recv.side_effect = [ packet.Packet(packet.PING).encode(), ValueError, ] c.write_loop_task = mock.MagicMock() c._receive_packet = mock.MagicMock() c._read_loop_websocket() assert c.state == 'disconnected' c.queue.put.assert_called_once_with(None) c.write_loop_task.join.assert_called_once_with() assert c._receive_packet.call_args_list[0][0][0].encode() == '2' def test_write_loop_disconnected(self): c = client.Client() c.state = 'disconnected' c._write_loop() # should not block def test_write_loop_no_packets(self): c = client.Client() c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.queue = mock.MagicMock() c.queue.get.return_value = None c._write_loop() c.queue.task_done.assert_called_once_with() c.queue.get.assert_called_once_with(timeout=7) def test_write_loop_empty_queue(self): c = client.Client() c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = RuntimeError c._write_loop() c.queue.get.assert_called_once_with(timeout=7) def test_write_loop_polling_one_packet(self): c = client.Client() c.base_url = 'http://foo' c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'polling' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), RuntimeError, RuntimeError, ] c._send_request = mock.MagicMock() c._send_request.return_value.status_code = 200 c._write_loop() assert c.queue.task_done.call_count == 1 p = payload.Payload( packets=[packet.Packet(packet.MESSAGE, {'foo': 'bar'})] ) c._send_request.assert_called_once_with( 'POST', 'http://foo', body=p.encode(), headers={'Content-Type': 'text/plain'}, timeout=5, ) def test_write_loop_polling_three_packets(self): c = client.Client() c.base_url = 'http://foo' c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'polling' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), packet.Packet(packet.PING), packet.Packet(packet.NOOP), RuntimeError, RuntimeError, ] c._send_request = mock.MagicMock() c._send_request.return_value.status_code = 200 c._write_loop() assert c.queue.task_done.call_count == 3 p = payload.Payload( packets=[ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), packet.Packet(packet.PING), packet.Packet(packet.NOOP), ] ) c._send_request.assert_called_once_with( 'POST', 'http://foo', body=p.encode(), headers={'Content-Type': 'text/plain'}, timeout=5, ) def test_write_loop_polling_two_packets_done(self): c = client.Client() c.base_url = 'http://foo' c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'polling' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), packet.Packet(packet.PING), None, RuntimeError, ] c._send_request = mock.MagicMock() c._send_request.return_value.status_code = 200 c._write_loop() assert c.queue.task_done.call_count == 3 p = payload.Payload( packets=[ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), packet.Packet(packet.PING), ] ) c._send_request.assert_called_once_with( 'POST', 'http://foo', body=p.encode(), headers={'Content-Type': 'text/plain'}, timeout=5, ) assert c.state == 'connected' def test_write_loop_polling_bad_connection(self): c = client.Client() c.base_url = 'http://foo' c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'polling' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), RuntimeError, ] c._send_request = mock.MagicMock() c._send_request.return_value = None c._write_loop() assert c.queue.task_done.call_count == 1 p = payload.Payload( packets=[packet.Packet(packet.MESSAGE, {'foo': 'bar'})] ) c._send_request.assert_called_once_with( 'POST', 'http://foo', body=p.encode(), headers={'Content-Type': 'text/plain'}, timeout=5, ) assert c.state == 'connected' def test_write_loop_polling_bad_status(self): c = client.Client() c.base_url = 'http://foo' c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'polling' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), RuntimeError, ] c._send_request = mock.MagicMock() c._send_request.return_value.status_code = 500 c._write_loop() assert c.queue.task_done.call_count == 1 p = payload.Payload( packets=[packet.Packet(packet.MESSAGE, {'foo': 'bar'})] ) c._send_request.assert_called_once_with( 'POST', 'http://foo', body=p.encode(), headers={'Content-Type': 'text/plain'}, timeout=5, ) assert c.state == 'disconnected' def test_write_loop_websocket_one_packet(self): c = client.Client() c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'websocket' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), RuntimeError, RuntimeError, ] c.ws = mock.MagicMock() c._write_loop() assert c.queue.task_done.call_count == 1 assert c.ws.send.call_count == 1 assert c.ws.send_binary.call_count == 0 c.ws.send.assert_called_once_with('4{"foo":"bar"}') def test_write_loop_websocket_three_packets(self): c = client.Client() c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'websocket' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), packet.Packet(packet.PING), packet.Packet(packet.NOOP), RuntimeError, RuntimeError, ] c.ws = mock.MagicMock() c._write_loop() assert c.queue.task_done.call_count == 3 assert c.ws.send.call_count == 3 assert c.ws.send_binary.call_count == 0 assert c.ws.send.call_args_list[0][0][0] == '4{"foo":"bar"}' assert c.ws.send.call_args_list[1][0][0] == '2' assert c.ws.send.call_args_list[2][0][0] == '6' def test_write_loop_websocket_one_packet_binary(self): c = client.Client() c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'websocket' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, b'foo'), RuntimeError, RuntimeError, ] c.ws = mock.MagicMock() c._write_loop() assert c.queue.task_done.call_count == 1 assert c.ws.send.call_count == 0 assert c.ws.send_binary.call_count == 1 c.ws.send_binary.assert_called_once_with(b'foo') def test_write_loop_websocket_bad_connection(self): c = client.Client() c.state = 'connected' c.ping_interval = 1 c.ping_timeout = 2 c.current_transport = 'websocket' c.queue = mock.MagicMock() c.queue.Empty = RuntimeError c.queue.get.side_effect = [ packet.Packet(packet.MESSAGE, {'foo': 'bar'}), RuntimeError, RuntimeError, ] c.ws = mock.MagicMock() c.ws.send.side_effect = websocket.WebSocketConnectionClosedException c._write_loop() assert c.state == 'connected' @mock.patch('engineio.client.original_signal_handler') def test_signal_handler(self, original_handler): clients = [mock.MagicMock(), mock.MagicMock()] client.connected_clients = clients[:] client.connected_clients[0].is_asyncio_based.return_value = False client.connected_clients[1].is_asyncio_based.return_value = True client.signal_handler('sig', 'frame') clients[0].disconnect.assert_called_once_with() clients[1].disconnect.assert_not_called()
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,459
miguelgrinberg/python-engineio
refs/heads/main
/examples/client/asyncio/latency_client.py
import asyncio import time import engineio loop = asyncio.get_event_loop() eio = engineio.AsyncClient() start_timer = None async def send_ping(): global start_timer start_timer = time.time() await eio.send('ping') @eio.on('connect') async def on_connect(): print('connected to server') await send_ping() @eio.on('message') async def on_message(data): global start_timer latency = time.time() - start_timer print('latency is {0:.2f} ms'.format(latency * 1000)) await eio.sleep(1) await send_ping() async def start_client(): await eio.connect('http://localhost:5000') await eio.wait() if __name__ == '__main__': loop.run_until_complete(start_client())
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,460
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/socket.py
import sys import time from . import exceptions from . import packet from . import payload class Socket(object): """An Engine.IO socket.""" upgrade_protocols = ['websocket'] def __init__(self, server, sid): self.server = server self.sid = sid self.queue = self.server.create_queue() self.last_ping = None self.connected = False self.upgrading = False self.upgraded = False self.closing = False self.closed = False self.session = {} def poll(self): """Wait for packets to send to the client.""" queue_empty = self.server.get_queue_empty_exception() try: packets = [self.queue.get( timeout=self.server.ping_interval + self.server.ping_timeout)] self.queue.task_done() except queue_empty: raise exceptions.QueueEmpty() if packets == [None]: return [] while True: try: pkt = self.queue.get(block=False) self.queue.task_done() if pkt is None: self.queue.put(None) break packets.append(pkt) except queue_empty: break return packets def receive(self, pkt): """Receive packet from the client.""" packet_name = packet.packet_names[pkt.packet_type] \ if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN' self.server.logger.info('%s: Received packet %s data %s', self.sid, packet_name, pkt.data if not isinstance(pkt.data, bytes) else '<binary>') if pkt.packet_type == packet.PONG: self.schedule_ping() elif pkt.packet_type == packet.MESSAGE: self.server._trigger_event('message', self.sid, pkt.data, run_async=self.server.async_handlers) elif pkt.packet_type == packet.UPGRADE: self.send(packet.Packet(packet.NOOP)) elif pkt.packet_type == packet.CLOSE: self.close(wait=False, abort=True) else: raise exceptions.UnknownPacketError() def check_ping_timeout(self): """Make sure the client is still responding to pings.""" if self.closed: raise exceptions.SocketIsClosedError() if self.last_ping and \ time.time() - self.last_ping > self.server.ping_timeout: self.server.logger.info('%s: Client is gone, closing socket', self.sid) # Passing abort=False here will cause close() to write a # CLOSE packet. This has the effect of updating half-open sockets # to their correct state of disconnected self.close(wait=False, abort=False) return False return True def send(self, pkt): """Send a packet to the client.""" if not self.check_ping_timeout(): return else: self.queue.put(pkt) self.server.logger.info('%s: Sending packet %s data %s', self.sid, packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>') def handle_get_request(self, environ, start_response): """Handle a long-polling GET request from the client.""" connections = [ s.strip() for s in environ.get('HTTP_CONNECTION', '').lower().split(',')] transport = environ.get('HTTP_UPGRADE', '').lower() if 'upgrade' in connections and transport in self.upgrade_protocols: self.server.logger.info('%s: Received request to upgrade to %s', self.sid, transport) return getattr(self, '_upgrade_' + transport)(environ, start_response) if self.upgrading or self.upgraded: # we are upgrading to WebSocket, do not return any more packets # through the polling endpoint return [packet.Packet(packet.NOOP)] try: packets = self.poll() except exceptions.QueueEmpty: exc = sys.exc_info() self.close(wait=False) raise exc[1].with_traceback(exc[2]) return packets def handle_post_request(self, environ): """Handle a long-polling POST request from the client.""" length = int(environ.get('CONTENT_LENGTH', '0')) if length > self.server.max_http_buffer_size: raise exceptions.ContentTooLongError() else: body = environ['wsgi.input'].read(length).decode('utf-8') p = payload.Payload(encoded_payload=body) for pkt in p.packets: self.receive(pkt) def close(self, wait=True, abort=False): """Close the socket connection.""" if not self.closed and not self.closing: self.closing = True self.server._trigger_event('disconnect', self.sid, run_async=False) if not abort: self.send(packet.Packet(packet.CLOSE)) self.closed = True self.queue.put(None) if wait: self.queue.join() def schedule_ping(self): def send_ping(): self.last_ping = None self.server.sleep(self.server.ping_interval) if not self.closing and not self.closed: self.last_ping = time.time() self.send(packet.Packet(packet.PING)) self.server.start_background_task(send_ping) def _upgrade_websocket(self, environ, start_response): """Upgrade the connection from polling to websocket.""" if self.upgraded: raise IOError('Socket has been upgraded already') if self.server._async['websocket'] is None: # the selected async mode does not support websocket return self.server._bad_request() ws = self.server._async['websocket']( self._websocket_handler, self.server) return ws(environ, start_response) def _websocket_handler(self, ws): """Engine.IO handler for websocket transport.""" def websocket_wait(): data = ws.wait() if data and len(data) > self.server.max_http_buffer_size: raise ValueError('packet is too large') return data # try to set a socket timeout matching the configured ping interval # and timeout for attr in ['_sock', 'socket']: # pragma: no cover if hasattr(ws, attr) and hasattr(getattr(ws, attr), 'settimeout'): getattr(ws, attr).settimeout( self.server.ping_interval + self.server.ping_timeout) if self.connected: # the socket was already connected, so this is an upgrade self.upgrading = True # hold packet sends during the upgrade pkt = websocket_wait() decoded_pkt = packet.Packet(encoded_packet=pkt) if decoded_pkt.packet_type != packet.PING or \ decoded_pkt.data != 'probe': self.server.logger.info( '%s: Failed websocket upgrade, no PING packet', self.sid) self.upgrading = False return [] ws.send(packet.Packet(packet.PONG, data='probe').encode()) self.queue.put(packet.Packet(packet.NOOP)) # end poll pkt = websocket_wait() decoded_pkt = packet.Packet(encoded_packet=pkt) if decoded_pkt.packet_type != packet.UPGRADE: self.upgraded = False self.server.logger.info( ('%s: Failed websocket upgrade, expected UPGRADE packet, ' 'received %s instead.'), self.sid, pkt) self.upgrading = False return [] self.upgraded = True self.upgrading = False else: self.connected = True self.upgraded = True # start separate writer thread def writer(): while True: packets = None try: packets = self.poll() except exceptions.QueueEmpty: break if not packets: # empty packet list returned -> connection closed break try: for pkt in packets: ws.send(pkt.encode()) except: break ws.close() writer_task = self.server.start_background_task(writer) self.server.logger.info( '%s: Upgrade to websocket successful', self.sid) while True: p = None try: p = websocket_wait() except Exception as e: # if the socket is already closed, we can assume this is a # downstream error of that if not self.closed: # pragma: no cover self.server.logger.info( '%s: Unexpected error "%s", closing connection', self.sid, str(e)) break if p is None: # connection closed by client break pkt = packet.Packet(encoded_packet=p) try: self.receive(pkt) except exceptions.UnknownPacketError: # pragma: no cover pass except exceptions.SocketIsClosedError: # pragma: no cover self.server.logger.info('Receive error -- socket is closed') break except: # pragma: no cover # if we get an unexpected exception we log the error and exit # the connection properly self.server.logger.exception('Unknown receive error') break self.queue.put(None) # unlock the writer task so that it can exit writer_task.join() self.close(wait=False, abort=True) return []
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,461
miguelgrinberg/python-engineio
refs/heads/main
/tests/performance/server_receive.py
import io import sys import time import engineio def test(eio_version, payload): s = engineio.Server() start = time.time() count = 0 s.handle_request({ 'REQUEST_METHOD': 'GET', 'QUERY_STRING': eio_version, }, lambda s, h: None) sid = list(s.sockets.keys())[0] while True: environ = { 'REQUEST_METHOD': 'POST', 'QUERY_STRING': eio_version + '&sid=' + sid, 'CONTENT_LENGTH': '6', 'wsgi.input': io.BytesIO(payload) } s.handle_request(environ, lambda s, h: None) count += 1 if time.time() - start >= 5: break return count if __name__ == '__main__': eio_version = 'EIO=4' payload = b'4hello' if len(sys.argv) > 1 and sys.argv[1] == '3': eio_version = 'EIO=3' payload = b'\x00\x06\xff4hello' count = test(eio_version, payload) print('server_receive:', count, 'packets received.')
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,462
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/asyncio_server.py
import asyncio import urllib from . import exceptions from . import packet from . import server from . import asyncio_socket class AsyncServer(server.Server): """An Engine.IO server for asyncio. This class implements a fully compliant Engine.IO web server with support for websocket and long-polling transports, compatible with the asyncio framework on Python 3.5 or newer. :param async_mode: The asynchronous model to use. See the Deployment section in the documentation for a description of the available options. Valid async modes are "aiohttp", "sanic", "tornado" and "asgi". If this argument is not given, "aiohttp" is tried first, followed by "sanic", "tornado", and finally "asgi". The first async mode that has all its dependencies installed is the one that is chosen. :param ping_interval: The interval in seconds at which the server pings the client. The default is 25 seconds. For advanced control, a two element tuple can be given, where the first number is the ping interval and the second is a grace period added by the server. :param ping_timeout: The time in seconds that the client waits for the server to respond before disconnecting. The default is 20 seconds. :param max_http_buffer_size: The maximum size of a message. The default is 1,000,000 bytes. :param allow_upgrades: Whether to allow transport upgrades or not. :param http_compression: Whether to compress packages when using the polling transport. :param compression_threshold: Only compress messages when their byte size is greater than this value. :param cookie: If set to a string, it is the name of the HTTP cookie the server sends back tot he client containing the client session id. If set to a dictionary, the ``'name'`` key contains the cookie name and other keys define cookie attributes, where the value of each attribute can be a string, a callable with no arguments, or a boolean. If set to ``None`` (the default), a cookie is not sent to the client. :param cors_allowed_origins: Origin or list of origins that are allowed to connect to this server. Only the same origin is allowed by default. Set this argument to ``'*'`` to allow all origins, or to ``[]`` to disable CORS handling. :param cors_credentials: Whether credentials (cookies, authentication) are allowed in requests to this server. :param logger: To enable logging set to ``True`` or pass a logger object to use. To disable logging set to ``False``. Note that fatal errors are logged even when ``logger`` is ``False``. :param json: An alternative json module to use for encoding and decoding packets. Custom json modules must have ``dumps`` and ``loads`` functions that are compatible with the standard library versions. :param async_handlers: If set to ``True``, run message event handlers in non-blocking threads. To run handlers synchronously, set to ``False``. The default is ``True``. :param transports: The list of allowed transports. Valid transports are ``'polling'`` and ``'websocket'``. Defaults to ``['polling', 'websocket']``. :param kwargs: Reserved for future extensions, any additional parameters given as keyword arguments will be silently ignored. """ def is_asyncio_based(self): return True def async_modes(self): return ['aiohttp', 'sanic', 'tornado', 'asgi'] def attach(self, app, engineio_path='engine.io'): """Attach the Engine.IO server to an application.""" engineio_path = engineio_path.strip('/') self._async['create_route'](app, self, '/{}/'.format(engineio_path)) async def send(self, sid, data): """Send a message to a client. :param sid: The session id of the recipient client. :param data: The data to send to the client. Data can be of type ``str``, ``bytes``, ``list`` or ``dict``. If a ``list`` or ``dict``, the data will be serialized as JSON. Note: this method is a coroutine. """ try: socket = self._get_socket(sid) except KeyError: # the socket is not available self.logger.warning('Cannot send to sid %s', sid) return await socket.send(packet.Packet(packet.MESSAGE, data=data)) async def get_session(self, sid): """Return the user session for a client. :param sid: The session id of the client. The return value is a dictionary. Modifications made to this dictionary are not guaranteed to be preserved. If you want to modify the user session, use the ``session`` context manager instead. """ socket = self._get_socket(sid) return socket.session async def save_session(self, sid, session): """Store the user session for a client. :param sid: The session id of the client. :param session: The session dictionary. """ socket = self._get_socket(sid) socket.session = session def session(self, sid): """Return the user session for a client with context manager syntax. :param sid: The session id of the client. This is a context manager that returns the user session dictionary for the client. Any changes that are made to this dictionary inside the context manager block are saved back to the session. Example usage:: @eio.on('connect') def on_connect(sid, environ): username = authenticate_user(environ) if not username: return False with eio.session(sid) as session: session['username'] = username @eio.on('message') def on_message(sid, msg): async with eio.session(sid) as session: print('received message from ', session['username']) """ class _session_context_manager(object): def __init__(self, server, sid): self.server = server self.sid = sid self.session = None async def __aenter__(self): self.session = await self.server.get_session(sid) return self.session async def __aexit__(self, *args): await self.server.save_session(sid, self.session) return _session_context_manager(self, sid) async def disconnect(self, sid=None): """Disconnect a client. :param sid: The session id of the client to close. If this parameter is not given, then all clients are closed. Note: this method is a coroutine. """ if sid is not None: try: socket = self._get_socket(sid) except KeyError: # pragma: no cover # the socket was already closed or gone pass else: await socket.close() if sid in self.sockets: # pragma: no cover del self.sockets[sid] else: await asyncio.wait([asyncio.create_task(client.close()) for client in self.sockets.values()]) self.sockets = {} async def handle_request(self, *args, **kwargs): """Handle an HTTP request from the client. This is the entry point of the Engine.IO application. This function returns the HTTP response to deliver to the client. Note: this method is a coroutine. """ translate_request = self._async['translate_request'] if asyncio.iscoroutinefunction(translate_request): environ = await translate_request(*args, **kwargs) else: environ = translate_request(*args, **kwargs) if self.cors_allowed_origins != []: # Validate the origin header if present # This is important for WebSocket more than for HTTP, since # browsers only apply CORS controls to HTTP. origin = environ.get('HTTP_ORIGIN') if origin: allowed_origins = self._cors_allowed_origins(environ) if allowed_origins is not None and origin not in \ allowed_origins: self._log_error_once( origin + ' is not an accepted origin.', 'bad-origin') return await self._make_response( self._bad_request( origin + ' is not an accepted origin.'), environ) method = environ['REQUEST_METHOD'] query = urllib.parse.parse_qs(environ.get('QUERY_STRING', '')) sid = query['sid'][0] if 'sid' in query else None jsonp = False jsonp_index = None # make sure the client uses an allowed transport transport = query.get('transport', ['polling'])[0] if transport not in self.transports: self._log_error_once('Invalid transport', 'bad-transport') return await self._make_response( self._bad_request('Invalid transport'), environ) # make sure the client speaks a compatible Engine.IO version sid = query['sid'][0] if 'sid' in query else None if sid is None and query.get('EIO') != ['4']: self._log_error_once( 'The client is using an unsupported version of the Socket.IO ' 'or Engine.IO protocols', 'bad-version' ) return await self._make_response(self._bad_request( 'The client is using an unsupported version of the Socket.IO ' 'or Engine.IO protocols' ), environ) if 'j' in query: jsonp = True try: jsonp_index = int(query['j'][0]) except (ValueError, KeyError, IndexError): # Invalid JSONP index number pass if jsonp and jsonp_index is None: self._log_error_once('Invalid JSONP index number', 'bad-jsonp-index') r = self._bad_request('Invalid JSONP index number') elif method == 'GET': if sid is None: # transport must be one of 'polling' or 'websocket'. # if 'websocket', the HTTP_UPGRADE header must match. upgrade_header = environ.get('HTTP_UPGRADE').lower() \ if 'HTTP_UPGRADE' in environ else None if transport == 'polling' \ or transport == upgrade_header == 'websocket': r = await self._handle_connect(environ, transport, jsonp_index) else: self._log_error_once('Invalid websocket upgrade', 'bad-upgrade') r = self._bad_request('Invalid websocket upgrade') else: if sid not in self.sockets: self._log_error_once('Invalid session ' + sid, 'bad-sid') r = self._bad_request('Invalid session ' + sid) else: socket = self._get_socket(sid) try: packets = await socket.handle_get_request(environ) if isinstance(packets, list): r = self._ok(packets, jsonp_index=jsonp_index) else: r = packets except exceptions.EngineIOError: if sid in self.sockets: # pragma: no cover await self.disconnect(sid) r = self._bad_request() if sid in self.sockets and self.sockets[sid].closed: del self.sockets[sid] elif method == 'POST': if sid is None or sid not in self.sockets: self._log_error_once('Invalid session ' + sid, 'bad-sid') r = self._bad_request('Invalid session ' + sid) else: socket = self._get_socket(sid) try: await socket.handle_post_request(environ) r = self._ok(jsonp_index=jsonp_index) except exceptions.EngineIOError: if sid in self.sockets: # pragma: no cover await self.disconnect(sid) r = self._bad_request() except: # pragma: no cover # for any other unexpected errors, we log the error # and keep going self.logger.exception('post request handler error') r = self._ok(jsonp_index=jsonp_index) elif method == 'OPTIONS': r = self._ok() else: self.logger.warning('Method %s not supported', method) r = self._method_not_found() if not isinstance(r, dict): return r if self.http_compression and \ len(r['response']) >= self.compression_threshold: encodings = [e.split(';')[0].strip() for e in environ.get('HTTP_ACCEPT_ENCODING', '').split(',')] for encoding in encodings: if encoding in self.compression_methods: r['response'] = \ getattr(self, '_' + encoding)(r['response']) r['headers'] += [('Content-Encoding', encoding)] break return await self._make_response(r, environ) def start_background_task(self, target, *args, **kwargs): """Start a background task using the appropriate async model. This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode. :param target: the target function to execute. :param args: arguments to pass to the function. :param kwargs: keyword arguments to pass to the function. The return value is a ``asyncio.Task`` object. """ return asyncio.ensure_future(target(*args, **kwargs)) async def sleep(self, seconds=0): """Sleep for the requested amount of time using the appropriate async model. This is a utility function that applications can use to put a task to sleep without having to worry about using the correct call for the selected async mode. Note: this method is a coroutine. """ return await asyncio.sleep(seconds) def create_queue(self, *args, **kwargs): """Create a queue object using the appropriate async model. This is a utility function that applications can use to create a queue without having to worry about using the correct call for the selected async mode. For asyncio based async modes, this returns an instance of ``asyncio.Queue``. """ return asyncio.Queue(*args, **kwargs) def get_queue_empty_exception(self): """Return the queue empty exception for the appropriate async model. This is a utility function that applications can use to work with a queue without having to worry about using the correct call for the selected async mode. For asyncio based async modes, this returns an instance of ``asyncio.QueueEmpty``. """ return asyncio.QueueEmpty def create_event(self, *args, **kwargs): """Create an event object using the appropriate async model. This is a utility function that applications can use to create an event without having to worry about using the correct call for the selected async mode. For asyncio based async modes, this returns an instance of ``asyncio.Event``. """ return asyncio.Event(*args, **kwargs) async def _make_response(self, response_dict, environ): cors_headers = self._cors_headers(environ) make_response = self._async['make_response'] if asyncio.iscoroutinefunction(make_response): response = await make_response( response_dict['status'], response_dict['headers'] + cors_headers, response_dict['response'], environ) else: response = make_response( response_dict['status'], response_dict['headers'] + cors_headers, response_dict['response'], environ) return response async def _handle_connect(self, environ, transport, jsonp_index=None): """Handle a client connection request.""" if self.start_service_task: # start the service task to monitor connected clients self.start_service_task = False self.start_background_task(self._service_task) sid = self.generate_id() s = asyncio_socket.AsyncSocket(self, sid) self.sockets[sid] = s pkt = packet.Packet( packet.OPEN, {'sid': sid, 'upgrades': self._upgrades(sid, transport), 'pingTimeout': int(self.ping_timeout * 1000), 'pingInterval': int(self.ping_interval * 1000)}) await s.send(pkt) s.schedule_ping() ret = await self._trigger_event('connect', sid, environ, run_async=False) if ret is not None and ret is not True: del self.sockets[sid] self.logger.warning('Application rejected connection') return self._unauthorized(ret or None) if transport == 'websocket': ret = await s.handle_get_request(environ) if s.closed and sid in self.sockets: # websocket connection ended, so we are done del self.sockets[sid] return ret else: s.connected = True headers = None if self.cookie: if isinstance(self.cookie, dict): headers = [( 'Set-Cookie', self._generate_sid_cookie(sid, self.cookie) )] else: headers = [( 'Set-Cookie', self._generate_sid_cookie(sid, { 'name': self.cookie, 'path': '/', 'SameSite': 'Lax' }) )] try: return self._ok(await s.poll(), headers=headers, jsonp_index=jsonp_index) except exceptions.QueueEmpty: return self._bad_request() async def _trigger_event(self, event, *args, **kwargs): """Invoke an event handler.""" run_async = kwargs.pop('run_async', False) ret = None if event in self.handlers: if asyncio.iscoroutinefunction(self.handlers[event]) is True: if run_async: return self.start_background_task(self.handlers[event], *args) else: try: ret = await self.handlers[event](*args) except asyncio.CancelledError: # pragma: no cover pass except: self.logger.exception(event + ' async handler error') if event == 'connect': # if connect handler raised error we reject the # connection return False else: if run_async: async def async_handler(): return self.handlers[event](*args) return self.start_background_task(async_handler) else: try: ret = self.handlers[event](*args) except: self.logger.exception(event + ' handler error') if event == 'connect': # if connect handler raised error we reject the # connection return False return ret async def _service_task(self): # pragma: no cover """Monitor connected clients and clean up those that time out.""" while True: if len(self.sockets) == 0: # nothing to do await self.sleep(self.ping_timeout) continue # go through the entire client list in a ping interval cycle sleep_interval = self.ping_timeout / len(self.sockets) try: # iterate over the current clients for socket in self.sockets.copy().values(): if not socket.closing and not socket.closed: await socket.check_ping_timeout() await self.sleep(sleep_interval) except ( SystemExit, KeyboardInterrupt, asyncio.CancelledError, GeneratorExit, ): self.logger.info('service task canceled') break except: if asyncio.get_event_loop().is_closed(): self.logger.info('event loop is closed, exiting service ' 'task') break # an unexpected exception has occurred, log it and continue self.logger.exception('service task exception')
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,463
miguelgrinberg/python-engineio
refs/heads/main
/tests/asyncio/test_async_sanic.py
from engineio.async_drivers import sanic as async_sanic # noqa: F401
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,464
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/middleware.py
import os from engineio.static_files import get_static_file class WSGIApp(object): """WSGI application middleware for Engine.IO. This middleware dispatches traffic to an Engine.IO application. It can also serve a list of static files to the client, or forward unrelated HTTP traffic to another WSGI application. :param engineio_app: The Engine.IO server. Must be an instance of the ``engineio.Server`` class. :param wsgi_app: The WSGI app that receives all other traffic. :param static_files: A dictionary with static file mapping rules. See the documentation for details on this argument. :param engineio_path: The endpoint where the Engine.IO application should be installed. The default value is appropriate for most cases. Example usage:: import engineio import eventlet eio = engineio.Server() app = engineio.WSGIApp(eio, static_files={ '/': {'content_type': 'text/html', 'filename': 'index.html'}, '/index.html': {'content_type': 'text/html', 'filename': 'index.html'}, }) eventlet.wsgi.server(eventlet.listen(('', 8000)), app) """ def __init__(self, engineio_app, wsgi_app=None, static_files=None, engineio_path='engine.io'): self.engineio_app = engineio_app self.wsgi_app = wsgi_app self.engineio_path = engineio_path if not self.engineio_path.startswith('/'): self.engineio_path = '/' + self.engineio_path if not self.engineio_path.endswith('/'): self.engineio_path += '/' self.static_files = static_files or {} def __call__(self, environ, start_response): if 'gunicorn.socket' in environ: # gunicorn saves the socket under environ['gunicorn.socket'], while # eventlet saves it under environ['eventlet.input']. Eventlet also # stores the socket inside a wrapper class, while gunicon writes it # directly into the environment. To give eventlet's WebSocket # module access to this socket when running under gunicorn, here we # copy the socket to the eventlet format. class Input(object): def __init__(self, socket): self.socket = socket def get_socket(self): return self.socket environ['eventlet.input'] = Input(environ['gunicorn.socket']) path = environ['PATH_INFO'] if path is not None and path.startswith(self.engineio_path): return self.engineio_app.handle_request(environ, start_response) else: static_file = get_static_file(path, self.static_files) \ if self.static_files else None if static_file and os.path.exists(static_file['filename']): start_response( '200 OK', [('Content-Type', static_file['content_type'])]) with open(static_file['filename'], 'rb') as f: return [f.read()] elif self.wsgi_app is not None: return self.wsgi_app(environ, start_response) return self.not_found(start_response) def not_found(self, start_response): start_response("404 Not Found", [('Content-Type', 'text/plain')]) return [b'Not Found'] class Middleware(WSGIApp): """This class has been renamed to ``WSGIApp`` and is now deprecated.""" def __init__(self, engineio_app, wsgi_app=None, engineio_path='engine.io'): super().__init__(engineio_app, wsgi_app, engineio_path=engineio_path)
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,465
miguelgrinberg/python-engineio
refs/heads/main
/examples/server/aiohttp/latency.py
from aiohttp import web import engineio eio = engineio.AsyncServer(async_mode='aiohttp') app = web.Application() eio.attach(app) async def index(request): with open('latency.html') as f: return web.Response(text=f.read(), content_type='text/html') @eio.on('message') async def message(sid, data): await eio.send(sid, 'pong') app.router.add_static('/static', 'static') app.router.add_get('/', index) if __name__ == '__main__': web.run_app(app)
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,466
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/async_drivers/gevent.py
from __future__ import absolute_import import gevent from gevent import queue from gevent.event import Event try: import geventwebsocket # noqa _websocket_available = True except ImportError: _websocket_available = False class Thread(gevent.Greenlet): # pragma: no cover """ This wrapper class provides gevent Greenlet interface that is compatible with the standard library's Thread class. """ def __init__(self, target, args=[], kwargs={}): super().__init__(target, *args, **kwargs) def _run(self): return self.run() class WebSocketWSGI(object): # pragma: no cover """ This wrapper class provides a gevent WebSocket interface that is compatible with eventlet's implementation. """ def __init__(self, handler, server): self.app = handler def __call__(self, environ, start_response): if 'wsgi.websocket' not in environ: raise RuntimeError('You need to use the gevent-websocket server. ' 'See the Deployment section of the ' 'documentation for more information.') self._sock = environ['wsgi.websocket'] self.environ = environ self.version = self._sock.version self.path = self._sock.path self.origin = self._sock.origin self.protocol = self._sock.protocol return self.app(self) def close(self): return self._sock.close() def send(self, message): return self._sock.send(message) def wait(self): return self._sock.receive() _async = { 'thread': Thread, 'queue': queue.JoinableQueue, 'queue_empty': queue.Empty, 'event': Event, 'websocket': WebSocketWSGI if _websocket_available else None, 'sleep': gevent.sleep, }
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,467
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/exceptions.py
class EngineIOError(Exception): pass class ContentTooLongError(EngineIOError): pass class UnknownPacketError(EngineIOError): pass class QueueEmpty(EngineIOError): pass class SocketIsClosedError(EngineIOError): pass class ConnectionError(EngineIOError): pass
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,468
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/async_drivers/sanic.py
import sys from urllib.parse import urlsplit try: # pragma: no cover from sanic.response import HTTPResponse try: from sanic.server.protocols.websocket_protocol import WebSocketProtocol except ImportError: print('yay') from sanic.websocket import WebSocketProtocol except ImportError: HTTPResponse = None WebSocketProtocol = None def create_route(app, engineio_server, engineio_endpoint): # pragma: no cover """This function sets up the engine.io endpoint as a route for the application. Note that both GET and POST requests must be hooked up on the engine.io endpoint. """ app.add_route(engineio_server.handle_request, engineio_endpoint, methods=['GET', 'POST', 'OPTIONS']) try: app.enable_websocket() except AttributeError: # ignore, this version does not support websocket pass def translate_request(request): # pragma: no cover """This function takes the arguments passed to the request handler and uses them to generate a WSGI compatible environ dictionary. """ class AwaitablePayload(object): def __init__(self, payload): self.payload = payload or b'' async def read(self, length=None): if length is None: r = self.payload self.payload = b'' else: r = self.payload[:length] self.payload = self.payload[length:] return r uri_parts = urlsplit(request.url) environ = { 'wsgi.input': AwaitablePayload(request.body), 'wsgi.errors': sys.stderr, 'wsgi.version': (1, 0), 'wsgi.async': True, 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'SERVER_SOFTWARE': 'sanic', 'REQUEST_METHOD': request.method, 'QUERY_STRING': uri_parts.query or '', 'RAW_URI': request.url, 'SERVER_PROTOCOL': 'HTTP/' + request.version, 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '0', 'SERVER_NAME': 'sanic', 'SERVER_PORT': '0', 'sanic.request': request } for hdr_name, hdr_value in request.headers.items(): hdr_name = hdr_name.upper() if hdr_name == 'CONTENT-TYPE': environ['CONTENT_TYPE'] = hdr_value continue elif hdr_name == 'CONTENT-LENGTH': environ['CONTENT_LENGTH'] = hdr_value continue key = 'HTTP_%s' % hdr_name.replace('-', '_') if key in environ: hdr_value = '%s,%s' % (environ[key], hdr_value) environ[key] = hdr_value environ['wsgi.url_scheme'] = environ.get('HTTP_X_FORWARDED_PROTO', 'http') path_info = uri_parts.path environ['PATH_INFO'] = path_info environ['SCRIPT_NAME'] = '' return environ def make_response(status, headers, payload, environ): # pragma: no cover """This function generates an appropriate response object for this async mode. """ headers_dict = {} content_type = None for h in headers: if h[0].lower() == 'content-type': content_type = h[1] else: headers_dict[h[0]] = h[1] return HTTPResponse(body=payload, content_type=content_type, status=int(status.split()[0]), headers=headers_dict) class WebSocket(object): # pragma: no cover """ This wrapper class provides a sanic WebSocket interface that is somewhat compatible with eventlet's implementation. """ def __init__(self, handler, server): self.handler = handler self._sock = None async def __call__(self, environ): request = environ['sanic.request'] protocol = request.transport.get_protocol() self._sock = await protocol.websocket_handshake(request) self.environ = environ await self.handler(self) async def close(self): await self._sock.close() async def send(self, message): await self._sock.send(message) async def wait(self): data = await self._sock.recv() if not isinstance(data, bytes) and \ not isinstance(data, str): raise IOError() return data _async = { 'asyncio': True, 'create_route': create_route, 'translate_request': translate_request, 'make_response': make_response, 'websocket': WebSocket if WebSocketProtocol else None, }
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,469
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/async_drivers/tornado.py
import asyncio import sys from urllib.parse import urlsplit from .. import exceptions import tornado.web import tornado.websocket def get_tornado_handler(engineio_server): class Handler(tornado.websocket.WebSocketHandler): # pragma: no cover def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if isinstance(engineio_server.cors_allowed_origins, str): if engineio_server.cors_allowed_origins == '*': self.allowed_origins = None else: self.allowed_origins = [ engineio_server.cors_allowed_origins] else: self.allowed_origins = engineio_server.cors_allowed_origins self.receive_queue = asyncio.Queue() async def get(self, *args, **kwargs): if self.request.headers.get('Upgrade', '').lower() == 'websocket': ret = super().get(*args, **kwargs) if asyncio.iscoroutine(ret): await ret else: await engineio_server.handle_request(self) async def open(self, *args, **kwargs): # this is the handler for the websocket request asyncio.ensure_future(engineio_server.handle_request(self)) async def post(self, *args, **kwargs): await engineio_server.handle_request(self) async def options(self, *args, **kwargs): await engineio_server.handle_request(self) async def on_message(self, message): await self.receive_queue.put(message) async def get_next_message(self): return await self.receive_queue.get() def on_close(self): self.receive_queue.put_nowait(None) def check_origin(self, origin): if self.allowed_origins is None or origin in self.allowed_origins: return True return super().check_origin(origin) def get_compression_options(self): # enable compression return {} return Handler def translate_request(handler): """This function takes the arguments passed to the request handler and uses them to generate a WSGI compatible environ dictionary. """ class AwaitablePayload(object): def __init__(self, payload): self.payload = payload or b'' async def read(self, length=None): if length is None: r = self.payload self.payload = b'' else: r = self.payload[:length] self.payload = self.payload[length:] return r payload = handler.request.body uri_parts = urlsplit(handler.request.path) full_uri = handler.request.path if handler.request.query: # pragma: no cover full_uri += '?' + handler.request.query environ = { 'wsgi.input': AwaitablePayload(payload), 'wsgi.errors': sys.stderr, 'wsgi.version': (1, 0), 'wsgi.async': True, 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'SERVER_SOFTWARE': 'aiohttp', 'REQUEST_METHOD': handler.request.method, 'QUERY_STRING': handler.request.query or '', 'RAW_URI': full_uri, 'SERVER_PROTOCOL': 'HTTP/%s' % handler.request.version, 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '0', 'SERVER_NAME': 'aiohttp', 'SERVER_PORT': '0', 'tornado.handler': handler } for hdr_name, hdr_value in handler.request.headers.items(): hdr_name = hdr_name.upper() if hdr_name == 'CONTENT-TYPE': environ['CONTENT_TYPE'] = hdr_value continue elif hdr_name == 'CONTENT-LENGTH': environ['CONTENT_LENGTH'] = hdr_value continue key = 'HTTP_%s' % hdr_name.replace('-', '_') environ[key] = hdr_value environ['wsgi.url_scheme'] = environ.get('HTTP_X_FORWARDED_PROTO', 'http') path_info = uri_parts.path environ['PATH_INFO'] = path_info environ['SCRIPT_NAME'] = '' return environ def make_response(status, headers, payload, environ): """This function generates an appropriate response object for this async mode. """ tornado_handler = environ['tornado.handler'] try: tornado_handler.set_status(int(status.split()[0])) except RuntimeError: # pragma: no cover # for websocket connections Tornado does not accept a response, since # it already emitted the 101 status code return for header, value in headers: tornado_handler.set_header(header, value) tornado_handler.write(payload) tornado_handler.finish() class WebSocket(object): # pragma: no cover """ This wrapper class provides a tornado WebSocket interface that is somewhat compatible with eventlet's implementation. """ def __init__(self, handler, server): self.handler = handler self.tornado_handler = None async def __call__(self, environ): self.tornado_handler = environ['tornado.handler'] self.environ = environ await self.handler(self) async def close(self): self.tornado_handler.close() async def send(self, message): try: self.tornado_handler.write_message( message, binary=isinstance(message, bytes)) except tornado.websocket.WebSocketClosedError: raise exceptions.EngineIOError() async def wait(self): msg = await self.tornado_handler.get_next_message() if not isinstance(msg, bytes) and \ not isinstance(msg, str): raise IOError() return msg _async = { 'asyncio': True, 'translate_request': translate_request, 'make_response': make_response, 'websocket': WebSocket, }
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,393,470
miguelgrinberg/python-engineio
refs/heads/main
/src/engineio/async_drivers/eventlet.py
from __future__ import absolute_import from eventlet.green.threading import Thread, Event from eventlet import queue from eventlet import sleep from eventlet.websocket import WebSocketWSGI as _WebSocketWSGI class WebSocketWSGI(_WebSocketWSGI): def __init__(self, handler, server): try: super().__init__( handler, max_frame_length=int(server.max_http_buffer_size)) except TypeError: # pragma: no cover # older versions of eventlet do not support a max frame size super().__init__(handler) self._sock = None def __call__(self, environ, start_response): if 'eventlet.input' not in environ: raise RuntimeError('You need to use the eventlet server. ' 'See the Deployment section of the ' 'documentation for more information.') self._sock = environ['eventlet.input'].get_socket() return super().__call__(environ, start_response) _async = { 'thread': Thread, 'queue': queue.Queue, 'queue_empty': queue.Empty, 'event': Event, 'websocket': WebSocketWSGI, 'sleep': sleep, }
{"/src/engineio/asyncio_client.py": ["/src/engineio/__init__.py"], "/src/engineio/client.py": ["/src/engineio/__init__.py"], "/src/engineio/__init__.py": ["/src/engineio/client.py", "/src/engineio/middleware.py", "/src/engineio/server.py", "/src/engineio/asyncio_server.py", "/src/engineio/asyncio_client.py", "/src/engineio/async_drivers/asgi.py", "/src/engineio/async_drivers/tornado.py"], "/src/engineio/server.py": ["/src/engineio/__init__.py"], "/src/engineio/payload.py": ["/src/engineio/__init__.py"], "/src/engineio/socket.py": ["/src/engineio/__init__.py"], "/src/engineio/asyncio_server.py": ["/src/engineio/__init__.py"], "/src/engineio/async_drivers/tornado.py": ["/src/engineio/__init__.py"]}
21,524,377
cvanderkolk/spotitube
refs/heads/master
/app.py
import functools import json import os import random import time from datetime import datetime import spotipy from spotipy.oauth2 import SpotifyClientCredentials import flask import google.oauth2.credentials import google_auth import youtube import googleapiclient.discovery from authlib.client import OAuth2Session from flask import Flask, render_template, request, redirect # from flask_sqlalchemy import SQLAlchemy from pyyoutube import Api app = flask.Flask(__name__) app.secret_key = os.environ.get("FN_FLASK_SECRET_KEY", default=False) app.register_blueprint(google_auth.app) app.register_blueprint(youtube.app) # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' # db = SQLAlchemy(app) SPOTIFY_CLIENT_ID = os.environ.get("SPOTIFY_CLIENT_ID") SPOTIFY_CLIENT_SECRET = os.environ.get("SPOTIFY_CLIENT_SECRET") YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY") youtube_api = Api(api_key=YOUTUBE_API_KEY) spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(SPOTIFY_CLIENT_ID,SPOTIFY_CLIENT_SECRET)) # test_playlist_uri = 'spotify:playlist:0FGCDjzPQA0TgzEvT9cTFC' # zack_playlist_uri = 'spotify:playlist:3AvzARrfmI3EiSi2PBTTjq' def get_spotify_playlist(playlist_uri): playlist_items = spotify.playlist_items(playlist_uri) playlist = spotify.playlist(playlist_uri, fields='name,description') name = playlist.get('name') description = playlist.get('description') songs = [] ## TODO: paginate thru so we get ALL songs goddamnit for track in playlist_items['items']: song_name = track['track']['name'] artists = track['track']['artists'] artist_names = ', '.join([artist['name'] for artist in artists]) songs.append('{} {}'.format(artist_names, song_name)) return (songs, name, description) def search_youtube_for_song(query): search_result = youtube_api.search_by_keywords(q=query, search_type=["video"], count=1, limit=1).to_dict() # if there are results, return the first one if len(search_result.get('items')) > 0: return search_result['items'][0] else: return None def add_songs_to_playlist(songs, youtube_playlist_id): for song in songs: youtube_video = search_youtube_for_song(song) if youtube_video: video_id = youtube_video['id']['videoId'] response = youtube.add_video_to_playlist(video_id, youtube_playlist_id) # let's wait a moment so we don't get rate limited print('Added {} to your playlist!'.format(response['snippet']['title'])) time.sleep(1) else: print('No video found for {}. \n Video info: {}'.format(song, youtube_video)) @app.route('/') def index(): if google_auth.is_logged_in(): user_info = google_auth.get_user_info() return render_template('index.html', user_info=google_auth.get_user_info()) return 'You are not currently logged in.' from flask import request @app.route('/dothing', methods=['POST']) def do_thing(): playlist_uri = request.form['playlist_uri'] songs, name, description = get_spotify_playlist(playlist_uri) data = { 'playlist_uri': playlist_uri, 'songs': songs, 'name': name, 'description': description, } return render_template('songs.html', data=data) @app.route('/makePlaylist', methods=['POST']) def make_playlist(): playlist_uri = request.form['playlist_uri'] songs, name, description = get_spotify_playlist(playlist_uri) now = datetime.now() if not name: name = 'SpotifyToYoutube Playlist {}'.format(now.strftime('%m/%d/%Y')) if not description: description = '' description += '\n Generated by SpotifyToYoutube on {}'.format(now.strftime('%m/%d/%Y, %H:%M:%S')) # youtube_playlist = youtube.create_playlist(title=name, description=description) youtube_playlist = { 'id': 'PLR0TUXxwTRCoEU_67jo1IENOav5kIj45p' } add_songs_to_playlist(songs[11:15], youtube_playlist['id']) print('doing the thing') return redirect('https://www.youtube.com/playlist?list={}'.format(youtube_playlist['id']))
{"/youtube.py": ["/google_auth.py"], "/app.py": ["/google_auth.py", "/youtube.py"]}
21,689,685
yungsalami/linuxtest
refs/heads/main
/V103_code.py
# -*- coding: utf-8 -*- """ Created on Mon Jun 28 10:42:30 2021 @author: salem """ import uncertainties import math as m from scipy.optimize import curve_fit from scipy.signal import argrelmin from scipy.signal import find_peaks import os import pandas as pd import numpy as np import matplotlib as plt import csv import matplotlib.pyplot as plt # Daten ziehen # ============================================================================= # ============================================================================= # # # Daten einspeisen # ============================================================================= # ============================================================================= class stab: def __init__( self, no, data, gewichte, masse, length, area): self.name = no self.data = data def latex(a): print(a.to_latex(decimal = ",", index=False)) ## Daten pa = np.arange(5,50,5)*10**(-2) pa = np.append(pa,49*10**(-2)) #linke Seite beim beidseitigem pbl = np.array([50.5, 45.5, 40.5, 35.5, 30.5])*10**(-2) pbr = np.array([5, 10, 15, 20, 25])*10**(-2) ## Stab: stab# = [einseitig, links, rechts] stab1a = np.array([ 130, 430, 870, 1450, 2120, 2870, 3715, 4630, 5630, 6180])*10**(-6) stab1b = np.array( [ [ 210, 400, 540, 650, 690], [ 60, 190, 355, 505, 640] ])*10**(-6) # eckig, silber stab1_length = 59.1*10**(-2) # m stab1_area = 3.61*10**(-4) # m^2 stab1_volume = stab1_length*stab1_area # m^3 stab1_weight = 0.1634 # kg stab1_mass = [ 0.85, 2.357] # [einseitig, zweiseitig] ################################## stab2a = np.array([ 70, 90, 380, 645, 920, 1235, 1530, 2010, 2400, 2785])*10**(-6) stab2b = np.array([[ 130, 250, 345, 405, 430], [ 40, 120, 230, 330, 400]])*10**(-6) # eckig, braun stab2_length = 60.3*10**(-2) # m stab2_area = 1.15*10**(-4) # m^2 stab2_volume = stab2_length*stab2_area # m^3 stab2_weight = 0.604 # kg stab2_mass = np.array([0.850, 3.515]) ################################ stab3a = np.array([50, 160, 340, 555, 820, 1140, 1500, 1940, 2245, 2455])*10**(-6) stab3b = np.array([[ 270, 520, 730, 870, 945], [90, 260, 490, 710, 860]])*10**(-6) # rund, golden stab3_length = 60*10**(-2) # m stab3_area = 0.5*0.5*np.pi*10**(-4) # m^2 stab3_volume = stab3_length*stab3_area # m^3 stab3_weight = 0.393 # kg stab3_mass = np.array([0.25, 2.357]) ############################### stab4a = np.array([60, 155, 340, 530, 830, 1125, 1470, 1850, 2115, 2510])*10**(-6) stab4b = np.array([[160, 300, 440, 545, 600], [60, 155, 295, 440, 530]])*10**(-6) # braun, rund stab4_length = 60*10**(-2) # m stab4_area = 0.5*0.5*np.pi*10**(-4) # m^2 stab4_volume = stab4_length*stab4_area # m^3 stab4_weight = 0.364 # kg stab4_mass = np.array([0.55, 3.515]) # ============================================================================= # plots # ============================================================================= ### stab 1 a = ((0.5*10**(-2))**4)*(np.pi/4) b = ((1.9*10**(-2))**4)/12 def xaxis(L, x): return L*(x**2) - (x**3)/3 # darf man ohne weiteres annehmen, dass die neutrale Phase die geometrische Mitte ist?? I = np.array([1.086, 1.086, 0.049, 0.049 ])*10**(-8) # stab1, stab2,... ; keine richtigen Daten für stab2 def E(m, mass, I ): F = 9.81*mass dE = abs(F/(2*I*m[0]*m[0]))*m[1] return round(F/(2*I*m[0]), 2), round(dE,2) # ============================================================================= # ============================================================================= # # Auswertung (einseitig) # ============================================================================= # ============================================================================= #stab 1 mit plot x1a = xaxis(0.52, pa) fit1a, cov1a = np.polyfit(x1a,stab1a,1, cov=True) poly1d_fn = np.poly1d(fit1a) m1a = np.array([fit1a[0], np.sqrt(cov1a[0,0])]) plt.figure() plt.plot(x1a, stab1a, 'x') plt.plot(x1a, poly1d_fn(x1a),'--k') # stab 2 fit2a, cov2a = np.polyfit(x1a, stab2a, 1, cov=True) m2a = np.array([fit2a[0], np.sqrt(cov2a[0,0])]) # stab 3 fit3a, cov3a = np.polyfit(x1a, stab3a, 1, cov=True) m3a = np.array([fit3a[0], np.sqrt(cov3a[0,0])]) # stab 4 fit4a, cov4a = np.polyfit(x1a, stab4a, 1, cov=True) m4a = np.array([fit4a[0], np.sqrt(cov4a[0,0])]) ma = np.array([m1a, m2a, m3a, m4a]) E1a = E(m1a, stab1_mass[0], I[0]) E2a = E(m2a, stab2_mass[0], I[1]) E3a = E(m3a, stab3_mass[0], I[2]) E4a = E(m4a, stab4_mass[0], I[3]) Ea = np.array([E1a, E2a, E3a, E4a]) for i in range(4): print("Elastitzitätsmodul",i+1 ,":", Ea[i]) # ============================================================================= # Auswertung (zweisitig) # ============================================================================= def xaxis2(L, x): return 4*x**3 - 12*L*x**2 + 9*x*L**2 - L**3 #def E2 # L = 55.5 cm also gesamtlänge des einspanns ### stab 1 mit plot x2 = np.array([xaxis2(0.55, pbl), xaxis2(0.55, pbr)]) fit1bl, cov1bl = np.polyfit(x2[0], stab1b[0], 1, cov=True) poly1d_2 = np.poly1d(fit1bl) m1bl = np.array([fit1bl[0], np.sqrt(cov1bl[0,0])]) fit1br, cov1br = np.polyfit(x2[1], stab1b[1], 1, cov=True) poly1d_2r = np.poly1d(fit1br) m1br = np.array([fit1br[0], np.sqrt(cov1br[0,0])]) fig, ax = plt.subplots(ncols= 2, sharey=True, sharex =True) fig.suptitle("Doppelseitige Einspannung") ax[0].plot(x2[0], stab1b[0]*10**6, 'x',x2[0], poly1d_2(x2[0])*10**6, 'k--') ax[1].plot(x2[1], stab1b[1]*10**6, 'x',x2[1], poly1d_2r(x2[1])*10**6, 'k--') ax[0].title.set_text('linkseitig') ax[1].title.set_text('rechtsseitig') ax[0].set_ylabel(r'$\mu m$') #ax[1].set_ylabel(r'$\mu m$') ax[0].set_xlabel(r'$(Lx^3 - 12Lx^2 + 9xL^2 - L^3)$') ax[1].set_xlabel(r'$(Lx^3 - 12Lx^2 + 9xL^2 - L^3)$') #ax[0].set(adjustable = "box-forced", aspect ="equal") #ax[1].set(adjustable = "box-forced", aspect ="equal") plt.tight_layout() # stab 2 fit2bl, cov2bl = np.polyfit(x2[0], stab2b[0], 1, cov=True) m2bl = np.array([fit2bl[0], np.sqrt(cov2bl[0,0])]) fit2br, cov2br = np.polyfit(x2[1], stab2b[1], 1, cov=True) m2br = np.array([fit2br[0], np.sqrt(cov2br[0,0])]) # stab 3 fit3bl, cov3bl = np.polyfit(x2[0], stab3b[0], 1, cov=True) m3bl = np.array([fit2bl[0], np.sqrt(cov3bl[0,0])]) fit3br, cov3br = np.polyfit(x2[1], stab3b[1], 1, cov=True) m3br = np.array([fit3br[0], np.sqrt(cov3br[0,0])]) # stab 4 fit4bl, cov4bl = np.polyfit(x2[0], stab4b[0], 1, cov=True) m4bl = np.array([fit4bl[0], np.sqrt(cov4bl[0,0])]) fit4br, cov4br = np.polyfit(x2[1], stab4b[1], 1, cov=True) m4br = np.array([fit4br[0], np.sqrt(cov4br[0,0])]) mbl = np.array([m1bl, m2bl, m3bl, m4bl]) ## Berechnung des Elastizitätsmoduls def E2(m, mass, I): F = 9.81*mass dE = abs(F/(48*I*m[0]*m[0]))*m[1] return ufloat([round(F/(48*I*m[0]),2), round(dE,2)]) E1bl = E2(m1bl, stab1_mass[1], I[0]) E2bl = E2(m2bl, stab2_mass[1], I[1]) E3bl = E2(m3bl, stab3_mass[1], I[2]) E4bl = E2(m4bl, stab4_mass[1], I[3]) Ebl = np.array([E1bl, E2bl, E3bl, E4bl]) for i in range(4): print("Elastitzitätsmodul_2_links",i+1 ,":", Ebl[i]) E1br = E2(m1br, stab1_mass[1], I[0]) E2br = E2(m2br, stab2_mass[1], I[1]) E3br = E2(m3br, stab3_mass[1], I[2]) E4br = E2(m4br, stab4_mass[1], I[3]) Ebr = np.array([E1br, E2br, E3br, E4br]) for i in range(4): print("Elastitzitätsmodul_2_rechts",i+1 ,":", Ebr[i]) Eb = np.array([Ebl, Ebr]) # ============================================================================= # ============================================================================= # # DataFrames # ============================================================================= # ============================================================================= data_a = pd.DataFrame({"x": pa, "stab1": stab1a, "stab2": stab2a, "stab3": stab3a, "stab4": stab4a }) latex(data_a) data_bl = pd.DataFrame({"x": pbl, "stab1": stab1b[0], "stab2": stab2b[0], "stab3": stab3b[0], "stab4": stab4b[0] }) latex(data_bl) data_br = pd.DataFrame({"x": pbr, "stab1": stab1b[1], "stab2": stab2b[1], "stab3": stab3b[1], "stab4": stab4b[1] }) latex(data_br) data_Ea = pd.DataFrame({ "stab1": np.array([E1a, E1bl, E1br]), "stab2": np.array([E2a, E2bl, E2br]), "stab3": np.array([E3a, E3bl, E3br]), "stab4": np.array([E4a , E4bl, E4br]) }) data_Ea.transform(lambda x : x*10**(-7)) latex(data_Ea)
{"/tests/test_io.py": ["/project_a5/simulation/detector/__init__.py", "/project_a5/simulation/particle/__init__.py", "/project_a5/io.py"], "/project_a5/simulation/generator/vertex_generator.py": ["/project_a5/simulation/particle/__init__.py", "/project_a5/simulation/generator/__init__.py"], "/exercises/mc_multiple_scattering.py": ["/project_a5/simulation/detector/angle_dist.py", "/project_a5/simulation/detector/exp_angle_dist.py"], "/project_a5/reconstruction/machine_learning/__init__.py": ["/project_a5/reconstruction/machine_learning/energy_regression.py"], "/project_a5/simulation/__init__.py": ["/project_a5/simulation/detector/__init__.py", "/project_a5/simulation/generator/__init__.py", "/project_a5/simulation/particle/__init__.py"], "/tests/simulation/particle/test_cascade.py": ["/project_a5/simulation/particle/__init__.py"], "/project_a5/simulation/particle/__init__.py": ["/project_a5/simulation/particle/base_particle.py", "/project_a5/simulation/particle/cascade.py", "/project_a5/simulation/particle/track.py", "/project_a5/simulation/particle/multiple_scattering.py"], "/exercises/testen.py": ["/project_a5/stats.py"], "/project_a5/simulation/particle/track.py": ["/project_a5/simulation/particle/__init__.py"], "/project_a5/simulation/detector/detector.py": ["/project_a5/simulation/detector/angle_dist.py", "/project_a5/simulation/detector/event.py", "/project_a5/simulation/particle/__init__.py"], "/project_a5/simulation/generator/__init__.py": ["/project_a5/simulation/generator/base_generator.py", "/project_a5/simulation/generator/vertex_generator.py"], "/exercises/energy_regression.py": ["/project_a5/simulation/__init__.py", "/project_a5/simulation/particle/__init__.py", "/project_a5/reconstruction/preprocessing/__init__.py", "/project_a5/reconstruction/machine_learning/__init__.py"], "/project_a5/reconstruction/preprocessing/__init__.py": ["/project_a5/reconstruction/preprocessing/feature_generation.py", "/project_a5/reconstruction/preprocessing/target_scaling.py"], "/exercises/feature_generation.py": ["/project_a5/simulation/__init__.py", "/project_a5/simulation/particle/__init__.py", "/project_a5/reconstruction/preprocessing/__init__.py"], "/exercises/utils/__init__.py": ["/exercises/utils/load_class.py"], "/tests/simulation/particle/test_base_particle.py": ["/project_a5/simulation/particle/__init__.py"], "/project_a5/reconstruction/likelihood/cascade_direction.py": ["/project_a5/simulation/particle/__init__.py"], "/project_a5/visualization.py": ["/project_a5/simulation/detector/event.py"], "/project_a5/simulation/detector/__init__.py": ["/project_a5/simulation/detector/detector.py", "/project_a5/simulation/detector/angle_dist.py", "/project_a5/simulation/detector/exp_angle_dist.py"], "/project_a5/simulation/particle/cascade.py": ["/project_a5/simulation/particle/__init__.py"], "/tests/simulation/generator/test_vertex_generator.py": ["/project_a5/simulation/particle/__init__.py", "/project_a5/simulation/generator/__init__.py"], "/exercises/unfolding.py": ["/project_a5/reconstruction/unfolding/__init__.py"], "/examples/create_dataset.py": ["/project_a5/io.py", "/project_a5/simulation/__init__.py", "/project_a5/simulation/particle/__init__.py"], "/project_a5/reconstruction/unfolding/__init__.py": ["/project_a5/reconstruction/unfolding/newton.py"], "/tests/simulation/generator/test_base_generator.py": ["/project_a5/simulation/particle/__init__.py", "/project_a5/simulation/generator/__init__.py"], "/scripts/analyse_dataset.py": ["/project_a5/io.py"], "/tests/simulation/detector/test_detector.py": ["/project_a5/simulation/particle/__init__.py", "/project_a5/simulation/detector/__init__.py"], "/project_a5/reconstruction/likelihood/__init__.py": ["/project_a5/reconstruction/likelihood/cascade_direction.py", "/project_a5/reconstruction/likelihood/resimulations.py"], "/tests/test_random.py": ["/project_a5/simulation/generator/__init__.py"], "/tests/simulation/detector/test_angle_dist.py": ["/project_a5/simulation/detector/angle_dist.py", "/project_a5/simulation/detector/exp_angle_dist.py"], "/project_a5/simulation/particle/multiple_scattering.py": ["/project_a5/simulation/particle/__init__.py", "/project_a5/simulation/detector/angle_dist.py"], "/examples/likelihood_reconstruction.py": ["/project_a5/visualization.py", "/project_a5/simulation/__init__.py", "/project_a5/simulation/particle/__init__.py", "/project_a5/reconstruction/likelihood/__init__.py"], "/scripts/create_dataset.py": ["/project_a5/io.py", "/project_a5/simulation/__init__.py", "/project_a5/simulation/particle/__init__.py", "/project_a5/reconstruction/preprocessing/__init__.py"], "/examples/plot_events.py": ["/project_a5/visualization.py", "/project_a5/simulation/__init__.py"], "/project_a5/simulation/generator/base_generator.py": ["/project_a5/simulation/particle/__init__.py"]}
21,744,651
Omulosi/iReporter
refs/heads/master
/instance/config.py
""" config ~~~~~~ Creates an object with configuration variables """ class Config: pass class TestConfig(Config): TESTING = True DEBUG = True
{"/tests/v2/test_users.py": ["/app/helpers.py", "/app/models.py"], "/tests/v2/test_auth.py": ["/app/models.py", "/app/helpers.py"], "/app/__init__.py": ["/config.py", "/app/api/v1/__init__.py", "/app/api/v2/__init__.py", "/instance/config.py"], "/app/decorators.py": ["/app/models.py", "/app/utils.py"], "/app/api/v1/views.py": ["/app/api/v1/__init__.py", "/app/api/v1/models.py", "/app/utils.py", "/app/api/v1/errors.py"], "/app/api/v2/common/errors.py": ["/app/__init__.py", "/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/auth.py": ["/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/incidents.py": ["/app/utils.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/__init__.py": ["/app/api/v2/auth.py", "/app/api/v2/incidents.py", "/app/api/v2/users.py"], "/tests/v2/test_models.py": ["/app/models.py", "/app/helpers.py"], "/tests/v2/test_incidents.py": ["/app/helpers.py", "/app/models.py"], "/app/db/db.py": ["/config.py"], "/tests/v2/test_helpers.py": ["/app/helpers.py"], "/app/helpers.py": ["/app/__init__.py"], "/tests/v2/test_factory.py": ["/app/__init__.py", "/config.py"], "/app/models.py": ["/app/db/db.py"], "/tests/v1/test_views.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/tests/v2/conftest.py": ["/app/__init__.py", "/config.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/users.py": ["/app/models.py", "/app/decorators.py", "/app/utils.py"], "/tests/v1/conftest.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/app/utils.py": ["/app/__init__.py", "/app/models.py"], "/tests/v1/test_models.py": ["/app/api/v1/models.py"], "/app/tests/v1/test_views.py": ["/app/__init__.py", "/instance/config.py", "/app/api/v1/models.py"]}
21,744,652
Omulosi/iReporter
refs/heads/master
/app/__init__.py
""" app ~~~~ A flask application that implements a RESTful API for the iReporter application. """ from flask import Flask from instance.config import Config def create_app(config_class=Config): """ An application factory function for creating a flask app instance and registering blueprints """ app = Flask(__name__) app.config.from_object(config_class) from app.api.v1 import bp as api_v1 app.register_blueprint(api_v1, url_prefix='/api/v1') return app
{"/tests/v2/test_users.py": ["/app/helpers.py", "/app/models.py"], "/tests/v2/test_auth.py": ["/app/models.py", "/app/helpers.py"], "/app/__init__.py": ["/config.py", "/app/api/v1/__init__.py", "/app/api/v2/__init__.py", "/instance/config.py"], "/app/decorators.py": ["/app/models.py", "/app/utils.py"], "/app/api/v1/views.py": ["/app/api/v1/__init__.py", "/app/api/v1/models.py", "/app/utils.py", "/app/api/v1/errors.py"], "/app/api/v2/common/errors.py": ["/app/__init__.py", "/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/auth.py": ["/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/incidents.py": ["/app/utils.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/__init__.py": ["/app/api/v2/auth.py", "/app/api/v2/incidents.py", "/app/api/v2/users.py"], "/tests/v2/test_models.py": ["/app/models.py", "/app/helpers.py"], "/tests/v2/test_incidents.py": ["/app/helpers.py", "/app/models.py"], "/app/db/db.py": ["/config.py"], "/tests/v2/test_helpers.py": ["/app/helpers.py"], "/app/helpers.py": ["/app/__init__.py"], "/tests/v2/test_factory.py": ["/app/__init__.py", "/config.py"], "/app/models.py": ["/app/db/db.py"], "/tests/v1/test_views.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/tests/v2/conftest.py": ["/app/__init__.py", "/config.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/users.py": ["/app/models.py", "/app/decorators.py", "/app/utils.py"], "/tests/v1/conftest.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/app/utils.py": ["/app/__init__.py", "/app/models.py"], "/tests/v1/test_models.py": ["/app/api/v1/models.py"], "/app/tests/v1/test_views.py": ["/app/__init__.py", "/instance/config.py", "/app/api/v1/models.py"]}
21,744,653
Omulosi/iReporter
refs/heads/master
/app/api/v1/errors.py
""" app.api.v1.errors ~~~~~~~~~~~~~~~~~ """ from flask import jsonify def raise_error(status_code, message): """ Returns a template for generating a custom error message """ response = jsonify({"status": status_code, "error": message}) response.status_code = status_code return response
{"/tests/v2/test_users.py": ["/app/helpers.py", "/app/models.py"], "/tests/v2/test_auth.py": ["/app/models.py", "/app/helpers.py"], "/app/__init__.py": ["/config.py", "/app/api/v1/__init__.py", "/app/api/v2/__init__.py", "/instance/config.py"], "/app/decorators.py": ["/app/models.py", "/app/utils.py"], "/app/api/v1/views.py": ["/app/api/v1/__init__.py", "/app/api/v1/models.py", "/app/utils.py", "/app/api/v1/errors.py"], "/app/api/v2/common/errors.py": ["/app/__init__.py", "/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/auth.py": ["/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/incidents.py": ["/app/utils.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/__init__.py": ["/app/api/v2/auth.py", "/app/api/v2/incidents.py", "/app/api/v2/users.py"], "/tests/v2/test_models.py": ["/app/models.py", "/app/helpers.py"], "/tests/v2/test_incidents.py": ["/app/helpers.py", "/app/models.py"], "/app/db/db.py": ["/config.py"], "/tests/v2/test_helpers.py": ["/app/helpers.py"], "/app/helpers.py": ["/app/__init__.py"], "/tests/v2/test_factory.py": ["/app/__init__.py", "/config.py"], "/app/models.py": ["/app/db/db.py"], "/tests/v1/test_views.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/tests/v2/conftest.py": ["/app/__init__.py", "/config.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/users.py": ["/app/models.py", "/app/decorators.py", "/app/utils.py"], "/tests/v1/conftest.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/app/utils.py": ["/app/__init__.py", "/app/models.py"], "/tests/v1/test_models.py": ["/app/api/v1/models.py"], "/app/tests/v1/test_views.py": ["/app/__init__.py", "/instance/config.py", "/app/api/v1/models.py"]}
21,744,654
Omulosi/iReporter
refs/heads/master
/app/api/v1/views.py
""" app.api.v1.views ~~~~~~~~~~~~~~~~~ Implements API endpoints """ from flask_restful import Resource, reqparse, url_for from . import api_bp from .models import Record from .errors import raise_error class RedflagListAPI(Resource): """ Implements methods for creating a record and returning a collection of records. """ def __init__(self): self.parser = reqparse.RequestParser() self.parser.add_argument('comment', type=str, required=True, help='comment not provided') self.parser.add_argument('location', type=str, required=True, help='location not provided') super(RedflagListAPI, self).__init__() def get(self): """ Returns a collection of all red-flag records """ records = Record.all() output = {'status': 200, 'data': Record.all()} return output def post(self): """ Creates a new red-flag record """ data = self.parser.parse_args() # Dictionary of input data record = Record(location=data['location'], comment=data['comment']) uri = url_for('v1.redflag', _id=record.data_id, _external=True) record.add_field('uri', uri) Record.put(record) output = {'status': 201, 'data': [{"id": record.data_id, "message": "Created a red-flag record"}] } return output, 201, {'Location': uri} class RedflagAPI(Resource): """ Implements methods for manipulating a particular record """ def get(self, _id): """ Returns a single red-flag record """ if not _id.isnumeric(): return raise_error(404, "Invalid ID") _id = int(_id) record = Record.by_id(_id) if record is None: return raise_error(404, "Record record not found") output = {'status': 200, 'data': [record.serialize] } return output def delete(self, _id): """ Deletes a red-flag record """ if not _id.isnumeric(): return raise_error(404, "Invalid ID") _id = int(_id) record = Record.by_id(_id) if record is None: return raise_error(404, "Record does not exist") Record.delete(_id) out = {} out['status'] = 200 out['data'] = [{'id':_id, 'message': 'red-flag record deleted'}] return out class RedflagUpdateAPI(Resource): """ Updates the location or comment field of red-flag record """ def __init__(self): self.parser = reqparse.RequestParser() self.parser.add_argument('comment', type=str) self.parser.add_argument('location', type=str) super(RedflagUpdateAPI, self).__init__() def patch(self, _id, field): """ Updates a field of a red-flag record """ if not _id.isnumeric(): return raise_error(404, "Invalid ID") _id = int(_id) record = Record.by_id(_id) if record is None: return raise_error(404, "Record does not exist") data = self.parser.parse_args() if field == 'location': new_location = data.get('location') if new_location is not None: record.location = new_location elif field == 'comment': new_comment = data.get('comment') if new_comment is not None: record.comment = new_comment Record.put(record) output = {} output['status'] = 200 output['data'] = [{"id": _id, "message": "Updated red-flag record's " + field}] return output, 200 # # API resource routing # api_bp.add_resource(RedflagListAPI, '/red-flags', endpoint='redflags') api_bp.add_resource(RedflagAPI, '/red-flags/<_id>', endpoint='redflag') api_bp.add_resource(RedflagUpdateAPI, '/red-flags/<_id>/<field>', endpoint='update_redflag')
{"/tests/v2/test_users.py": ["/app/helpers.py", "/app/models.py"], "/tests/v2/test_auth.py": ["/app/models.py", "/app/helpers.py"], "/app/__init__.py": ["/config.py", "/app/api/v1/__init__.py", "/app/api/v2/__init__.py", "/instance/config.py"], "/app/decorators.py": ["/app/models.py", "/app/utils.py"], "/app/api/v1/views.py": ["/app/api/v1/__init__.py", "/app/api/v1/models.py", "/app/utils.py", "/app/api/v1/errors.py"], "/app/api/v2/common/errors.py": ["/app/__init__.py", "/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/auth.py": ["/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/incidents.py": ["/app/utils.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/__init__.py": ["/app/api/v2/auth.py", "/app/api/v2/incidents.py", "/app/api/v2/users.py"], "/tests/v2/test_models.py": ["/app/models.py", "/app/helpers.py"], "/tests/v2/test_incidents.py": ["/app/helpers.py", "/app/models.py"], "/app/db/db.py": ["/config.py"], "/tests/v2/test_helpers.py": ["/app/helpers.py"], "/app/helpers.py": ["/app/__init__.py"], "/tests/v2/test_factory.py": ["/app/__init__.py", "/config.py"], "/app/models.py": ["/app/db/db.py"], "/tests/v1/test_views.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/tests/v2/conftest.py": ["/app/__init__.py", "/config.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/users.py": ["/app/models.py", "/app/decorators.py", "/app/utils.py"], "/tests/v1/conftest.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/app/utils.py": ["/app/__init__.py", "/app/models.py"], "/tests/v1/test_models.py": ["/app/api/v1/models.py"], "/app/tests/v1/test_views.py": ["/app/__init__.py", "/instance/config.py", "/app/api/v1/models.py"]}
21,744,655
Omulosi/iReporter
refs/heads/master
/app/tests/v1/test_views.py
""" app.tests.v1.views ~~~~~~~~~~~~~~~~~~~ Tests for the API endpoints """ from app import create_app from instance.config import TestConfig from app.api.v1.models import Record as db import pytest import json @pytest.fixture def client(): """ Configures the application for testing. This fixture is called for each individual test. """ app = create_app(TestConfig) client = app.test_client() # Create an application context before running the tests ctx = app.app_context() ctx.push() yield client db.clear_all() ctx.pop() user_input = {'location': '-1.23, 36.5', 'comment':'crooked tendering processes'} def test_get_all(client): """ Tests endpoint for getting all requests """ # Initially no data present. Request should still be successful resp = client.get('/api/v1/red-flags') assert resp.status_code == 200 data = json.loads(resp.data.decode('utf-8')) assert len(data['data']) == 0 resp = client.post('/api/v1/red-flags', data=user_input) resp = client.get('/api/v1/red-flags') assert resp.status_code == 200 assert b'data'in resp.data assert b'status' in resp.data data = json.loads(resp.data.decode('utf-8')) assert len(data['data']) == 1 def test_post(client): """ Tests the create red-flag endpoint """ resp = client.post('/api/v1/red-flags', data=user_input) assert resp.status_code == 201 assert b'data' in resp.data assert b'status' in resp.data data = json.loads(resp.data.decode('utf-8')) assert 'red-flag record' in data['data'][0]['message'] assert resp.mimetype == 'application/json' assert resp.headers['Location'] is not None # Missing fields in request resp = client.post('/api/v1/red-flags', data={'location': '23,23'}) assert resp.status_code == 400 resp = client.post('/api/v1/red-flags', data={'comment': 'thief'}) assert resp.status_code == 400 resp = client.post('/api/v1/red-flags', data=None) assert resp.status_code == 400 def test_get_one(client): resp = client.post('/api/v1/red-flags', data=user_input) assert resp.status_code == 201 start = resp.headers['Location'].find('api') uri = '/' + resp.headers['Location'][start:] resp = client.get(uri) assert resp.status_code == 200 assert resp.headers['Content-Type'] == 'application/json' assert b'data' in resp.data assert b'status' in resp.data # Item not found resp = client.get('/api/v1/red-flags/999') assert resp.status_code == 404 assert resp.headers['Content-Type'] == 'application/json' # Invalid ID resp = client.get('/api/v1/red-flags/data-id') assert resp.status_code == 404 assert resp.headers['Content-Type'] == 'application/json' def test_delete_one(client): # create a red-flag to use for testing deletion resp = client.post('/api/v1/red-flags', data=user_input) assert resp.status_code == 201 start = resp.headers['Location'].find('api') uri = '/' + resp.headers['Location'][start:] # resp = client.delete(uri) assert resp.status_code == 200 assert b'data' in resp.data assert b'status' in resp.data # check that deletion is successful resp = client.get(uri) assert resp.status_code == 404 assert resp.headers['Content-Type'] == 'application/json' # Item not present resp = client.delete('/api/v1/red-flags/9999') assert resp.status_code == 404 assert resp.headers['Content-Type'] == 'application/json' # Invalid ID resp = client.delete('/api/v1/red-flags/data-id') assert resp.status_code == 404 assert resp.headers['Content-Type'] == 'application/json' def test_patch_location_and_comment(client): def update_field(field): resp = client.post('/api/v1/red-flags', data=user_input) assert resp.status_code == 201 start = resp.headers['Location'].find('api') uri = '/' + resp.headers['Location'][start:] update_uri = uri + '/' + field # check update of location field is successful if field == 'location': update = {'location': '-15.7, 77.2'} if field == 'comment': update = {'comment': 'new updated comment'} resp = client.patch(update_uri, data=update) assert resp.status_code == 200 assert b'data' in resp.data assert b'status' in resp.data data = json.loads(resp.data.decode('utf-8')) assert 'Updated' in data['data'][0]['message'] # Item not present resp = client.patch('/api/v1/red-flags/10000/' + field) assert resp.status_code == 404 assert resp.headers['Content-Type'] == 'application/json' # Invalid ID resp = client.patch('/api/v1/red-flags/that-record/' + field) assert resp.status_code == 404 assert resp.headers['Content-Type'] == 'application/json' update_field('location') update_field('comment')
{"/tests/v2/test_users.py": ["/app/helpers.py", "/app/models.py"], "/tests/v2/test_auth.py": ["/app/models.py", "/app/helpers.py"], "/app/__init__.py": ["/config.py", "/app/api/v1/__init__.py", "/app/api/v2/__init__.py", "/instance/config.py"], "/app/decorators.py": ["/app/models.py", "/app/utils.py"], "/app/api/v1/views.py": ["/app/api/v1/__init__.py", "/app/api/v1/models.py", "/app/utils.py", "/app/api/v1/errors.py"], "/app/api/v2/common/errors.py": ["/app/__init__.py", "/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/auth.py": ["/app/utils.py", "/app/models.py", "/app/api/v2/__init__.py"], "/app/api/v2/incidents.py": ["/app/utils.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/__init__.py": ["/app/api/v2/auth.py", "/app/api/v2/incidents.py", "/app/api/v2/users.py"], "/tests/v2/test_models.py": ["/app/models.py", "/app/helpers.py"], "/tests/v2/test_incidents.py": ["/app/helpers.py", "/app/models.py"], "/app/db/db.py": ["/config.py"], "/tests/v2/test_helpers.py": ["/app/helpers.py"], "/app/helpers.py": ["/app/__init__.py"], "/tests/v2/test_factory.py": ["/app/__init__.py", "/config.py"], "/app/models.py": ["/app/db/db.py"], "/tests/v1/test_views.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/tests/v2/conftest.py": ["/app/__init__.py", "/config.py", "/app/helpers.py", "/app/models.py"], "/app/api/v2/users.py": ["/app/models.py", "/app/decorators.py", "/app/utils.py"], "/tests/v1/conftest.py": ["/app/__init__.py", "/config.py", "/app/api/v1/models.py"], "/app/utils.py": ["/app/__init__.py", "/app/models.py"], "/tests/v1/test_models.py": ["/app/api/v1/models.py"], "/app/tests/v1/test_views.py": ["/app/__init__.py", "/instance/config.py", "/app/api/v1/models.py"]}
21,757,749
SCCWRP/BLM_data_reformatter
refs/heads/main
/blm_data_cleaning.py
import pandas as pd from pandasgui import show relationships_analytes = pd.ExcelFile("C:/Users/toled/Desktop/SCCWRP/RelationshipMap.xlsx").parse('Analytes') relationships_columns = pd.ExcelFile("C:/Users/toled/Desktop/SCCWRP/RelationshipMap.xlsx").parse('Columns') # this is the original dataset sccwrp_xls = pd.ExcelFile("C:/Users/toled/Desktop/SCCWRP/SCCWRP_SWAMP_FieldDataSheet.xlsx") sccwrp_field_results = sccwrp_xls.parse('sccwrp_swamp_fielddatasheet_0') # create field analytes field_filter = relationships_analytes["AnalyteNameType"] == "Field" Field_matrix_dict = relationships_analytes.loc[field_filter, ['OriginalAnalyteName', 'MatrixName']].set_index('OriginalAnalyteName').to_dict() Field_analytes_dict = relationships_analytes.loc[field_filter, ['OriginalAnalyteName', 'AnalyteName']].set_index('OriginalAnalyteName').to_dict() Field_unitname_dict = relationships_analytes.loc[field_filter, ['OriginalAnalyteName', 'UnitName']].set_index('OriginalAnalyteName').to_dict() Field_Matrix_Name = Field_matrix_dict['MatrixName'] Field_Analytes = Field_analytes_dict['AnalyteName'] Field_UnitName = Field_unitname_dict['UnitName'] # create habitat analytes habitat_filter = relationships_analytes["AnalyteNameType"] == "Habitat" Habitat_matrix_dict = relationships_analytes.loc[habitat_filter, ['OriginalAnalyteName', 'MatrixName']].set_index('OriginalAnalyteName').to_dict() Habitat_analytes_dict = relationships_analytes.loc[habitat_filter, ['OriginalAnalyteName', 'AnalyteName']].set_index('OriginalAnalyteName').to_dict() Habitat_unitname_dict = relationships_analytes.loc[habitat_filter, ['OriginalAnalyteName', 'UnitName']].set_index('OriginalAnalyteName').to_dict() Habitat_Matrix_Name = Habitat_matrix_dict['MatrixName'] Habitat_Analytes = Habitat_analytes_dict['AnalyteName'] Habitat_UnitName = Habitat_unitname_dict['UnitName'] # create melted field data field_tabs = ['All', 'FieldResults'] field_IDvars = relationships_columns.loc[relationships_columns['Tab'].isin(field_tabs), 'OriginalColumn'] field_melt_dat = pd.melt(sccwrp_field_results, id_vars=field_IDvars, value_vars=list(Field_Analytes)) field_melt_dat['MatrixName'] = field_melt_dat['variable'] field_melt_dat['MatrixName'].replace(Field_Matrix_Name, inplace=True) field_melt_dat['UnitName'] = field_melt_dat['variable'] field_melt_dat['UnitName'].replace(Field_UnitName, inplace=True) field_melt_dat["variable"].replace(Field_Analytes, inplace=True) field_melt_dat.rename(columns= {'variable': 'Analyte', 'value': 'Result'}, inplace=True) # create melted habitat data habitat_tabs = ['All', 'HabitatResults'] habitat_IDvars = relationships_columns.loc[relationships_columns['Tab'].isin(habitat_tabs), 'OriginalColumn'] habitat_melt_dat = pd.melt(sccwrp_field_results, id_vars=habitat_IDvars, value_vars=list(Habitat_Analytes)) habitat_melt_dat["variable"].replace(Habitat_Analytes, inplace=True) habitat_melt_dat['MatrixName'] = habitat_melt_dat['variable'] habitat_melt_dat['MatrixName'].replace(Habitat_Matrix_Name, inplace=True) habitat_melt_dat['UnitName'] = habitat_melt_dat['variable'] habitat_melt_dat['UnitName'].replace(Habitat_UnitName, inplace=True) habitat_melt_dat["variable"].replace(Habitat_Analytes, inplace=True) habitat_melt_dat.rename(columns= {'variable': 'Analyte', 'value': 'Result'}, inplace=True) blm_swampformat = pd.ExcelWriter('blm_swampformat.xlsx', engine='xlsxwriter') field_melt_dat.to_excel(blm_swampformat, sheet_name='FieldResults') habitat_melt_dat.to_excel(blm_swampformat, sheet_name='HabitatResults') blm_swampformat.save()
{"/sampleinfo.py": ["/globalvariables.py"], "/field.py": ["/globalvariables.py"], "/main.py": ["/field.py", "/habitat.py", "/sampleinfo.py", "/globalvariables.py"], "/habitat.py": ["/globalvariables.py"]}
21,951,903
AbdelbassetKABOU/OpenQCM
refs/heads/main
/api.py
# # /===============\ # | api.py | # \===============/ # # This is the tip of the icebirg for our proposed architecture. # The current module, along with data access/management, authentification # and logic modules, constitute the basic components of an n-tier architecture. # This architecture (referred to as multi-tier arch also) is an architectural # pattern in which presentation, application processing (logic) and data # management functions are separated [1]. More details are provided later. # # This module # # The current module consists on a set of functions accessible via a restful API. # The implementation is based mainly on FastAPI [2], the new emerged frameword # that is causing a considerable amount of buzz these days. # # AbdelbasetKABOU # # [1] https://fastapi.tiangolo.com/ # [2] https://en.wikipedia.org/wiki/Multitier_architecture # from fastapi import FastAPI, Depends, Query, HTTPException, status from typing import List, Optional import database as db import authentification as auth import qcm # ------------- api = FastAPI( title = 'OpenQCM API', description=' A simple HTTP RESTful API interecting with a database and \ returning a set of Multiple Choice Question (MCQ)', version='0.1' ) # -------------------------------------------------------------------------------------------- # -------------------------------------- # - Verify that the API is functional. # ------------------------ @api.get('/status') async def status(): return { 'response_code':0, 'results': 1 } # ------------------------ # ---- # ------------------------ # - Get the current user : # ------------------------ @api.get("/users/me") async def authenticate_user(username: str = Depends(auth.get_current_username)): return { 'response_code':0, 'results': username } #----------------------------- # --- # ---------------------------------------- # List available uses in the database # -------------------------------------------- @api.get("/uses") async def get_uses(username: str = Depends(auth.get_current_username)): available_uses = db.get_uses() return { 'response_code':0, 'results': available_uses } # --------------------- # ---------------------------------------- # List available subjects in the database # -------------------------------------------- @api.get("/subjects") async def get_subjects(username: str = Depends(auth.get_current_username)): available_subjects = db.get_subjects() return { 'response_code':0, 'results': available_subjects } # --------------------- # ---------------------------- # - Get a MCQ from database : # ---------------------------- # # - Containing 5,10 or 20 questions # - Related to one or more subject # (category) # - Related to one use (e.g. Test de # positionnement, Test de validation, etc) # # + It include a random rendering making results # differ each time # ----------------------------------------------- @api.get("/qcm/") async def get_qcm( number: int = Query( 5, title = "Number (Nombre de questions)", description = "Please choose among [5, 10, 20]", #max_length = 1, #min_length = 1, ), use: str = Query( #db.get_uses(), "Test de positionnement", title = "Use (type de questions)", description = f"Available Cases from database, <br> \ {db.get_uses()}", #max_length = 2, #min_length = 1, ), subjects: Optional[List[str]] = Query( db.get_subjects(), title = "Subject (Catégories de questions)", description = "Available subjects are provided bellow. <br>\ Choose the one to delete using <h1> - </h1>", #max_length = 3, ) ): if not (qcm.is_validated(number, use, subjects)): raise HTTPException( status_code = 422, detail = "Incorrect (Unprocessable) parameter, please check again", headers={"X-Error": "There goes my error"}, ) results = qcm.get_qcm_random(use, subjects, int(number)) return { 'response_code':0, 'results':{ "use": use, "subject": subjects, "number": int(number), "results": results } } # ----------------- # - More details on # https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query- # parameter-list-multiple-values-with-defaults # - Python fastapi.Query() Examples --> # https://www.programcreek.com/python/example/113514/fastapi.Query # ----------------------------------------------------------------- # -------------------------- # - Create a new question # ------------------------- # # (requires admin privileges). # # ----------------------------------------------- @api.post("/qcm/add/") async def add_qcm( question: str, subject: str, correct: str, use: str,\ responseA: str, responseB: str, responseC: str, responseD: str, \ username: str = Depends(auth.is_admin)) : request = qcm.add_question(question, subject, correct, use, \ responseA, responseB, responseC, responseD) if request : return { 'response_code' : 0, 'results' : { 'username': username, 'question':question, 'subject':subject, 'correct':correct, 'use':use, 'responseA': responseA, 'responseB': responseB, 'responseC': responseC, 'responseD': responseD } } # -------------------------------------------- # ---------- # ---------------------------- # - Get a MCQ from database : # - The same thing as the previous route, however # it's now consist on simple (not random) request # ----------------------------------------------- async def get_qcm_simple(use, subjects, number): #results = qcm.get_qcm_random('Test de validation', 'BDD', 11) if type(subjects) == str : subjects = [subjects] #results = qcm.get_qcm_random(use, subjects, int(number)) results = qcm.get_qcm(use, subjects, int(number)) return { 'response_code' : 0, 'results': { "use": use, "subject": subjects, "number": number, "results": results } } # -------------------------- #------ ''' if __name__ == '__main__': import uvicorn uvicorn.run(app, host="localhost", port=8100) '''
{"/qcm.py": ["/database.py"], "/api.py": ["/database.py", "/authentification.py", "/qcm.py"]}
21,951,904
AbdelbassetKABOU/OpenQCM
refs/heads/main
/database.py
# # /===============\ # | Database.py | # \===============/ # # This module is responsable for data access/management in the context of multitier # architecture [1]. A multitier architecture or n-tier arch is architectural pattern # in which presentation, application processing and data management functions are # separated. # This provides a model by which developers can create flexible and reusable app. # By segregating an application into tiers, developers acquire the option of modifying # or adding a specific layer, instead of reworking the entire applicationi [1]. # # In the context of this project, we are concerned by a database in forms of csv file. # This means the requirement of a set of functions regarding download, load/reload, # and preparation of the database. # Once data is here, we make use of "pandas" library, the de facto standard for # datascience. # # As a Comming soon, we can add data models to our proposal which is quite simpler # using FastAPI. You find the first intuitions commented in the end of this file. # # AbdelbasetKABOU # # [1] https://en.wikipedia.org/wiki/Multitier_architecture # ----------------------------------------------------------------- import os import pandas as pd import numpy as np from pydantic import BaseModel from typing import Optional def export_df(df, file_name): if os.path.isfile(file_name): os.remove(file_name) df.to_csv(file_name) return True def prepare_dataset(file_name: str): df = pd.read_csv(file_name) if 'Unnamed: 0.1' not in df.columns : return True else : df.rename(columns={'Unnamed: 0':'index'}, inplace=True) df.drop('Unnamed: 0.1', axis=1, inplace=True) export_state = export_df(df, file_name) return export_state def initialise_df() -> bool: df = pd.read_csv('questions.csv') return df def get_df(): try: df except NameError: prepare_dataset('questions.csv') df = initialise_df() return df def add_question(question: str, subject: str, use: str, correct: str,\ responseA: str, responseB: str, responseC: str, responseD: str) -> bool: df = get_df() new_row = {'question':question, 'subject':subject, 'use':use, 'correct':correct,\ 'responseA': responseA, 'responseB': responseB, \ 'responseC': responseC, 'responseD': responseD, 'remark':''} df = df.append(new_row, ignore_index=True) export_state = export_df(df, 'questions.csv') return True def get_uses(): df = get_df() return np.unique(df.use.values).tolist() def get_subjects(): df = pd.read_csv('questions.csv') return np.unique(df.subject.values).tolist() def get_questions(use: str, subjects: list) -> list: df = pd.read_csv('questions.csv') mylist = df[(df.use == use) & (df.subject.isin(subjects)) ].question.tolist() return mylist ''' class Question (BaseModel): question: str subject: str correct: str use: str responseA: str responseB: str responseC: str responseD: str class Request (BaseModel): use: str subject: str number: Optional[int] = None '''
{"/qcm.py": ["/database.py"], "/api.py": ["/database.py", "/authentification.py", "/qcm.py"]}
21,951,905
AbdelbassetKABOU/OpenQCM
refs/heads/main
/authentification.py
# ------------------------------------------------------------------ # /=====================\ # | authentification.py | # \=====================/ # # For authentification, we opted for a simplest scenario. The app expects a # header containing a username and password. # If not the case, it returns an HTTP 401 "Unauthorized" error. # The app returns a header WWW-Authenticate with a value of Basic and optional # realm parameter telling the browser to show the integrated prompt for # a username/password --> when you type username/passwd, the browser sends them # in header automatically ... More details in [1] # # We use the Python standard module secrets to check the username and password. # More specefically, using secrets.compare_digest() would be an efficient way to # secure against "timing attacks", c.f. [1]. # [1] https://fastapi.tiangolo.com/advanced/security/http-basic-auth/ # ----------------------------------------------------------------- import secrets from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials identified = { "alice": "wonderland", "bob": "builder", "clementine": "mandarine", "admin": "4dm1N" } security = HTTPBasic() def is_identified(credentials: HTTPBasicCredentials = Depends(security)): for user, passwd in identified.items(): if secrets.compare_digest(credentials.username, user): if secrets.compare_digest(credentials.password, passwd): return True return False def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): if not (is_identified(credentials)): raise HTTPException( status_code = status.HTTP_401_UNAUTHORIZED, detail = "Incorrect email or password", headers = {"WWW-Authenticate" : "Basic"}, ) return credentials.username def is_admin(credentials: HTTPBasicCredentials = Depends(security)): if not secrets.compare_digest(credentials.username, "admin"): raise HTTPException( status_code = status.HTTP_403_FORBIDDEN, detail = "Access to the requested resource is forbidden for the current user", headers = {"WWW-Authenticate" : "Basic"}, ) else : if not is_identified(credentials) : raise HTTPException( status_code = status.HTTP_401_UNAUTHORIZED, detail = "Incorrect email or password", headers = {"WWW-Authenticate" : "Basic"}, ) return credentials.username
{"/qcm.py": ["/database.py"], "/api.py": ["/database.py", "/authentification.py", "/qcm.py"]}
21,951,906
AbdelbassetKABOU/OpenQCM
refs/heads/main
/qcm.py
# /===============\ # | qcm.py | # \===============/ # # This module consist on the logic part of a multitier architecture [1]. # A multitier architecture or n-tier arch is architectural pattern in which # presentation, application processing (logic) and data management functions are # separated [x]. # # This provides a model by which developers can create flexible and reusable app. # By segregating an application into tiers, developers acquire the option of modifying # or adding a specific layer, instead of reworking the entire applicationi [x]. # # This is a supplementary layer added to our arch to avoid being stuck to how data # is presented/staured (which is in our case a csv file). The goal being, in addition # to other choices, to enhance the scalability (evolutivity) of the solution. Other # measures may be the separation of concerns inplemented using n-tier architecture as # discussed above. # # AbdelbasetKABOU # # [x] https://en.wikipedia.org/wiki/Multitier_architecture import database as db import random def add_question(question: str, subject: str, use: str, correct: str, \ responseA: str, responseB: str, responseC: str, responseD: str) -> bool: request = db.add_question(question, subject, use, correct, \ responseA, responseB, responseC, responseD) return request def get_qcm(use: str, subjects: list, nbr: int) -> list: mylist = db.get_questions(use, subjects) print (' get_qcm', use, subjects, nbr) return mylist[:nbr] def get_qcm_random (use: str, subjects: list, nbr: int) -> list: print (' get_qcm_random ', use, subjects, nbr) mylist = db.get_questions(use, subjects) if len(mylist)>nbr: return random.sample(mylist, nbr) else : return mylist def is_validated(number: int, use: str, subjects: list) -> bool: authorized_numbers = [5, 10, 20] authorized_uses = db.get_uses() authorized_subjects = db.get_subjects() if (number in authorized_numbers) and\ (use in authorized_uses) and\ (set(subjects).issubset(set(authorized_subjects))): return True else : return False
{"/qcm.py": ["/database.py"], "/api.py": ["/database.py", "/authentification.py", "/qcm.py"]}
21,968,614
sirdedz/mysite
refs/heads/main
/config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SECRET_KEY = os.environ.get('SECRET_KEY') or 'temp_key' SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): ENV='production' SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') class DevelopmentConfig(Config): DEBUG=True FLASK_ENV='development' SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') class TestingConfig(Config): ENV='testing' #SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') #<-- location of test database #SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' #will use an in memory database
{"/mysite/populate_db.py": ["/app/__init__.py"], "/mysite/app/controllers.py": ["/app/__init__.py"], "/mysite/app/models.py": ["/app/__init__.py"], "/mysite/app/__init__.py": ["/config.py", "/app/__init__.py"], "/mysite/app/routes.py": ["/app/__init__.py"], "/mysite/db_test.py": ["/app/__init__.py"], "/app/routes.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py"]}
21,968,615
sirdedz/mysite
refs/heads/main
/app/routes.py
from app import app from flask import render_template @app.route('/') @app.route('/index') def index(): return render_template('index.html', home=1) @app.route('/citi') def citi(): return render_template('citi.html', home=0) @app.route('/sharkstakes') def sharkstakes(): return render_template('sharkstakes.html', home=0) @app.route('/python_game') def python_game(): return render_template('python_game.html', home=0)
{"/mysite/populate_db.py": ["/app/__init__.py"], "/mysite/app/controllers.py": ["/app/__init__.py"], "/mysite/app/models.py": ["/app/__init__.py"], "/mysite/app/__init__.py": ["/config.py", "/app/__init__.py"], "/mysite/app/routes.py": ["/app/__init__.py"], "/mysite/db_test.py": ["/app/__init__.py"], "/app/routes.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py"]}
21,968,616
sirdedz/mysite
refs/heads/main
/app/__init__.py
from flask import Flask, session from config import Config app = Flask(__name__) app.config.from_object(Config) #app.config.from_object('config.DevelopmentConfig') #use for changing config types from app import routes
{"/mysite/populate_db.py": ["/app/__init__.py"], "/mysite/app/controllers.py": ["/app/__init__.py"], "/mysite/app/models.py": ["/app/__init__.py"], "/mysite/app/__init__.py": ["/config.py", "/app/__init__.py"], "/mysite/app/routes.py": ["/app/__init__.py"], "/mysite/db_test.py": ["/app/__init__.py"], "/app/routes.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py"]}
21,985,699
Roktober/spyder
refs/heads/master
/src/parser/Parser.py
from .data import Data from lxml import html import urllib.parse import re import logging class Parser: """ Parser for html and url filter """ logger = logging.getLogger(__name__) @staticmethod def parse(source_html: str, url: str) -> Data: data: Data = None try: base_url = urllib.parse.urlparse(url) data = HTMLParser.parse(source_html, url) data.urls = URLParser.process_urls(base_url, data.urls) except Exception as e: Parser.logger.error(f"Parse error url: {url}", exc_info=True) return data class HTMLParser: @staticmethod def parse(source_html: str, url: str) -> Data: parsed_html = html.fromstring(source_html) title = parsed_html.xpath('//title/text()') if len(title) < 1: title = "" Parser.logger.warning(f"URL: {url} haven't title") else: title = title[0] urls = set(parsed_html.xpath('//a/@href')) title_data = Data.Data(source_html, url, title, urls) return title_data class URLParser: ALLOW_SCHEME = ("http", "https") AVOID_HTML_LINK_PATTERN = re.compile("#.*") ALLOW_ANOTHER_NETLOC = True # TODO: type filter @staticmethod def parse(base_url: urllib.parse.ParseResult, url: str) -> str: if "#" in url: url = URLParser.AVOID_HTML_LINK_PATTERN.sub(url, "") parsed_url = urllib.parse.urlparse(url) if parsed_url.scheme not in URLParser.ALLOW_SCHEME: return None if not URLParser.ALLOW_ANOTHER_NETLOC and parsed_url.netloc: if parsed_url.netloc == base_url.netloc: return urllib.parse.urljoin(base_url.geturl(), parsed_url.geturl()) else: return None return urllib.parse.urljoin(base_url.geturl(), parsed_url.geturl()) @staticmethod def process_urls(base_url: urllib.parse.ParseResult, urls: set) -> set: return set(filter(lambda u: u is not None, map(lambda u: URLParser.parse(base_url, u), urls)))
{"/src/spyder/dao/DataDAO.py": ["/src/spyder/dao/Base.py"], "/src/spyder/parser/Parser.py": ["/src/spyder/parser/HTMLParser.py", "/src/spyder/parser/URLProcessor.py"], "/src/spyder/dao/TaskDAO.py": ["/src/spyder/dao/Base.py"]}
21,985,700
Roktober/spyder
refs/heads/master
/src/dao/TaskDAO.py
from typing import List from .base import DB from .TaskModel import Task from .DataModel import ParseData class TaskDAO: def __init__(self, db: DB): self.__db = db def save_data(self, data: Task) -> int: """Return inserted key""" return self.__db.get_session().add_get_key(data) def get_by_url(self, url: str) -> List[Task]: return self.__db.get_session().query(Task).filter(Task.url == url).all()
{"/src/spyder/dao/DataDAO.py": ["/src/spyder/dao/Base.py"], "/src/spyder/parser/Parser.py": ["/src/spyder/parser/HTMLParser.py", "/src/spyder/parser/URLProcessor.py"], "/src/spyder/dao/TaskDAO.py": ["/src/spyder/dao/Base.py"]}
21,985,701
Roktober/spyder
refs/heads/master
/src/cli.py
import logging import time import click import memory_profiler from spyder import Spyder pass_app = click.make_pass_decorator(Spyder) @click.group() @click.version_option("0.1", prog_name="spyder") @click.help_option("--help", help="use COMMAND --help for more information") @click.pass_context def cli(ctx): logging.basicConfig(format="%(asctime)s - %(name)s " "- %(levelname)s - %(message)s", level=logging.INFO) ctx.obj = Spyder() @cli.command(name="load", help="load html recursive") @click.argument("url", type=str) @click.option("--depth", default=2, help="Parsing depth.", type=int, show_default=True) @pass_app def load(app: Spyder, url: str, depth: int): start_time = time.time() mem = int(memory_profiler.memory_usage(proc=(app.start, (url, depth)), max_usage=True)) start_time = int(time.time() - start_time) click.echo(f"ok, execution time: {start_time}s," f" peak memory usage: {mem} Mb") @cli.command(name="get", help="load URL TITLE from storage") @click.argument("url", type=str) @click.option("--limit", default=10, help="Number of load rows.", type=int, show_default=True) @pass_app def get(app: Spyder, url: str, limit: int): click.echo(app.get_parsed_data(url, limit))
{"/src/spyder/dao/DataDAO.py": ["/src/spyder/dao/Base.py"], "/src/spyder/parser/Parser.py": ["/src/spyder/parser/HTMLParser.py", "/src/spyder/parser/URLProcessor.py"], "/src/spyder/dao/TaskDAO.py": ["/src/spyder/dao/Base.py"]}
21,985,702
Roktober/spyder
refs/heads/master
/src/spyder.py
from typing import Set, Coroutine, Union import asyncio from concurrent.futures import ThreadPoolExecutor import os import logging from datetime import datetime import time import aiohttp from parser.Parser import Parser from parser.data.Data import Data from dao.base import DB from dao.DataDAO import DataDAO from dao.TaskDAO import TaskDAO from dao.TaskModel import Task from dao.DataModel import ParseData class Spyder: logger = logging.getLogger(__name__) MAX_DEPTH = 2 # max parse depth, throw exception def __init__(self): self.__db = DB() self.__task_dao = TaskDAO(self.__db) self.__data_dao = DataDAO(self.__db) self.parsed_urls: Set[str] = set() self.__loop = asyncio.get_event_loop() self.__pool: ThreadPoolExecutor = None self.__client: aiohttp.ClientSession = None self._depth: int = 0 self.__task_id: int = None def parse(self, result: str, url: str) -> Data: """ Get title and links from html Save parsed data to DB :param result: html :param url: source url :return: parsed data """ data: Data = None if result: data = Parser.parse(result, url) if data: self.__data_dao.save_data( ParseData(url=data.uri, title=data.title, html=data.html, created=datetime.now(), task_id=self.__task_id)) return data async def request(self, url: str) -> (str, str): html: str = None try: result = await self.__client.get(url) if result.status == 200: html = await result.text() except Exception: Spyder.logger.error(f"Request error url: {url}", exc_info=True) return html, url async def worker(self, future: Union[Coroutine, asyncio.Future], depth: int) -> None: """ Make request to url async and parse data in thread Start new workers for parsed urls :param future: result of self.parse function :param depth: current depth """ futures = [] if depth < self._depth: data = await future if data: urls_to_parse = data.urls - self.parsed_urls self.parsed_urls |= data.urls for request_future in asyncio.as_completed( [self.request(url) for url in urls_to_parse]): parse_future = \ self.__loop.run_in_executor(self.__pool, self.parse, *(await request_future)) futures.append( asyncio.ensure_future( self.worker(parse_future, depth + 1))) if futures: await asyncio.wait(futures) async def start_worker(self, url: str) -> None: with ThreadPoolExecutor(max_workers=os.cpu_count()) as pool: self.__pool = pool async with aiohttp.ClientSession() as client: self.__client = client initial_future = self.__loop.create_future() initial_future.set_result(Data(None, None, None, {url})) await self.worker(initial_future, -1) def set_depth(self, depth: int): if depth > Spyder.MAX_DEPTH: raise ValueError(f"Depth should be less then {Spyder.MAX_DEPTH}") self._depth = depth def start(self, url: str, depth: int): """ Entry point :param url: start url :param depth: """ self.set_depth(depth) self.__task_id = self.__task_dao.save_data(Task(url=url, created=datetime.now())) try: self.__loop.run_until_complete( self.start_worker(url)) except Exception as e: Spyder.logger.error("Spyder error", exc_info=True) finally: self.__loop.close() Spyder.logger.info(f"Parse complete, parsed urls count: " f"{len(self.parsed_urls)}") def get_parsed_data(self, url: str, limit: int) -> str: tasks = self.__task_dao.get_by_url(url) if tasks: id = tasks[0].id result = self.__data_dao.get_data_by_task_id(id, limit) return "\n".join([r.url + " " + r.title for r in result]) else: return "Empty result"
{"/src/spyder/dao/DataDAO.py": ["/src/spyder/dao/Base.py"], "/src/spyder/parser/Parser.py": ["/src/spyder/parser/HTMLParser.py", "/src/spyder/parser/URLProcessor.py"], "/src/spyder/dao/TaskDAO.py": ["/src/spyder/dao/Base.py"]}
22,029,282
NExPlain/cs224n
refs/heads/master
/augmenter.py
import count from pathlib import Path # ['data'][0]['paragraphs'][0] # - ['context'] # - ['qas'][0] # - ['questions'] # - ['answers'][0] # - ['text'] # - ['answer_start'] def read(path): # 1D, context where the model finds answer from. contexts = [] # 2D, for each context, there is a list of questions regarding this context. questions_list = [] # 3D, for each question, there is a list of potential answers. Each of the answer has a character level starting # index in the context. answers_starts_list_list = [] # 3D, for each question, there is a list of potential answers. This is the text of the answer. texts_list_list = [] # 3D f = open(path) j = json.load(f) for x in j['data']: print(x['paragraphs']) for y in x['paragraphs']: contexts.append(y['context']) questions = [] answers_starts_list = [] texts_list = [] for z in y['qas']: questions.append(z['question']) answers_starts = [] texts = [] for a in z['answers']: answers_starts.append(a['answer_start']) texts.append(a['text']) answers_starts_list.append(answers_starts) texts_list.append(texts) questions_list.append(questions) answers_starts_list_list.append(answers_starts_list) texts_list_list.append(texts_list) return contexts, questions_list, answers_starts_list_list, texts_list_list def main(): print("Generating augment data") file_paths = Path('robustqa/datasets/oodomain_train').glob('*') for file_path in file_paths: print("Processing: " + str(file_path)) count.read(file_path) if __name__ == '__main__': main()
{"/augmenter.py": ["/count.py"]}
22,094,644
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/dialog/about.py
"""About Dialog""" import sys from pathlib import Path from PyQt5 import QtGui, QtWidgets import ui.functions from ui.window.ui_about import Ui_AboutDialog class AboutDialog(QtWidgets.QDialog, Ui_AboutDialog): def __init__(self, parent=None): super(AboutDialog, self).__init__(parent) self.setupUi(self) ui.functions.set_window_icon(self) self._setup_ui_buttons() self._setup_logo() def _setup_ui_buttons(self): self.buttonBox.clicked.connect(self.close) def _setup_logo(self): """Setup Logo""" logo = Path.cwd() / 'ui' / 'icons' / 'about.png' self.labelGraphic.setPixmap(QtGui.QPixmap(str(logo))) def show_dialog(): dialog = AboutDialog() dialog.exec_() if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = AboutDialog() window.show() sys.exit(app.exec_())
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,645
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/window/ui_about.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'K:\Library\Python\AssetsBrowser\ui\window\about.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_AboutDialog(object): def setupUi(self, AboutDialog): AboutDialog.setObjectName("AboutDialog") AboutDialog.resize(260, 270) AboutDialog.setMinimumSize(QtCore.QSize(260, 270)) AboutDialog.setMaximumSize(QtCore.QSize(260, 270)) AboutDialog.setFocusPolicy(QtCore.Qt.StrongFocus) self.verticalLayout = QtWidgets.QVBoxLayout(AboutDialog) self.verticalLayout.setObjectName("verticalLayout") self.labelGraphic = QtWidgets.QLabel(AboutDialog) self.labelGraphic.setText("") self.labelGraphic.setTextFormat(QtCore.Qt.AutoText) self.labelGraphic.setPixmap(QtGui.QPixmap("K:\\Library\\Python\\AssetsBrowser\\ui\\window\\../ui/icons/about.png")) self.labelGraphic.setAlignment(QtCore.Qt.AlignCenter) self.labelGraphic.setObjectName("labelGraphic") self.verticalLayout.addWidget(self.labelGraphic) self.labelAbout = QtWidgets.QLabel(AboutDialog) self.labelAbout.setAlignment(QtCore.Qt.AlignCenter) self.labelAbout.setWordWrap(True) self.labelAbout.setObjectName("labelAbout") self.verticalLayout.addWidget(self.labelAbout) self.buttonBox = QtWidgets.QDialogButtonBox(AboutDialog) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setCenterButtons(True) self.buttonBox.setObjectName("buttonBox") self.verticalLayout.addWidget(self.buttonBox) self.retranslateUi(AboutDialog) QtCore.QMetaObject.connectSlotsByName(AboutDialog) def retranslateUi(self, AboutDialog): _translate = QtCore.QCoreApplication.translate AboutDialog.setWindowTitle(_translate("AboutDialog", "About")) self.labelAbout.setText(_translate("AboutDialog", "<html><head/><body><p><span style=\" font-weight:600;\">Assets Browser<br/>Version 0.1.0</span></p><p>A Python based browser to manage various assets in a 3DCG/VFX production.</p></body></html>"))
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,646
hueyyeng/AssetsBrowser
refs/heads/develop
/tests/database/test_assets.py
import peewee as pw from pytest import mark from database.db import Database from database.models import ( Asset, Category, Project, ) class TestAssets: def setup(self): self.test_db = Database() self.category_data = { "name": "FX", "description": "Effects", } self.project_data = { "name": "Super Good", "short_name": "SG", "description": "Sequel to Good", } self.category = Category.create(**self.category_data) self.project = Project.create(**self.project_data) def test_create_asset(self): asset_name = "Explosion" asset_desc = "Fire Magic" asset_short_name = "EXP" asset_data = { "category": self.category.id, "description": asset_desc, "name": asset_name, "short_name": asset_short_name, "project": self.project.id, } Asset.create(**asset_data) a = Asset.get(**asset_data) assert a.name == asset_name assert a.description == asset_desc assert a.short_name == asset_short_name assert a.category.name == "FX" assert a.project.name == "Super Good" assert str(a) == "fEXP"
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,647
hueyyeng/AssetsBrowser
refs/heads/develop
/helpers/functions.py
"""Assets Browser Functions""" import logging import os import sys from PyQt5 import QtWidgets logger = logging.getLogger(__name__) def clear_layout(layout): """Clear layout?""" while layout.count(): child = layout.takeAt(0) if child.widget(): child.widget().deleteLater() def show_cwd(): """Show CWD (Current Work Directory) as a QMessageBox.""" widget = QtWidgets.QWidget() cwd = os.getcwd() QtWidgets.QMessageBox.information(widget, "Information", cwd) def close_app(): """Terminate/Close App.""" sys.exit() def restart_app(): """Restart App. 99% it doesn't restart in an IDE like PyCharm for complex script but it has been tested to work when execute through Python interpreter. """ # QtWidgets.qApp.exit(-123) os.execv(sys.executable, [sys.executable] + sys.argv) def ham(): """When testing or in doubt, it's HAM time!""" print('HAM! HAM! HAM!')
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,648
hueyyeng/AssetsBrowser
refs/heads/develop
/database/constants.py
"""Database Constants""" from database.models import ( Application, Asset, AssetItem, AssetItemFormat, Category, Project, ) DEFAULT_MODELS = [ Application, Asset, AssetItem, AssetItemFormat, Category, Project, ]
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,649
hueyyeng/AssetsBrowser
refs/heads/develop
/tests/database/test_categories.py
import peewee as pw from pytest import mark from database.db import Database from database.models import ( Asset, Category, Project, ) class TestCategories: def setup(self): self.test_db = Database() self.category_data_1 = { "name": "FX", "description": "Effects", } self.category_data_2 = { "name": "BG", "description": "Background", } def test_create_category(self): Category.create(**self.category_data_1) c1 = Category.get(**self.category_data_1) assert c1.name == self.category_data_1['name'] assert c1.description == self.category_data_1['description'] Category.create(**self.category_data_2) c2 = Category.get(**self.category_data_2) assert c2.name == self.category_data_2['name'] assert c2.description == self.category_data_2['description']
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,650
hueyyeng/AssetsBrowser
refs/heads/develop
/tests/database/test_db_schema.py
from pytest import mark import peewee as pw from database.models import ( Asset, Category, Project, ) from database.constants import DEFAULT_MODELS from database.db import Database def test_create_db_schema(): test_db = Database() test_db.create_db_schema() for model in DEFAULT_MODELS: result = test_db.db.table_exists(model._meta.table_name) assert result is True @mark.parametrize("model,fields", [ (Asset, [ 'category', 'project', 'short_name', 'created_dt', 'modified_dt', 'name', 'description', ]), (Category, [ 'name', 'description', ]), (Project, [ 'name', 'short_name', 'description', 'created_dt', 'modified_dt', ]), ]) def test_db_model_fields( model, fields, ): for field in fields: result = hasattr(model, field) assert result
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,651
hueyyeng/AssetsBrowser
refs/heads/develop
/tests/database/test_db.py
import logging import os import pytest from peewee import SqliteDatabase from database.db import Database from database.models import BaseModel class DummyModel(BaseModel): pass def test_use_default_db(): test_db = Database(use_default_db=True) assert isinstance(test_db.db, SqliteDatabase) def test_insert_single_table(): test_db = Database() test_db.create_db_tables(DummyModel) def test_validate_db_with_valid_db_path( tmp_path, caplog, ): caplog.set_level(logging.INFO) db = tmp_path / "dummy.db" db.write_text("") test_db = Database() test_db.validate_db(db) assert f"DB file found" in caplog.text def test_validate_db_with_non_exist_db_path( tmp_path, caplog, ): caplog.set_level(logging.ERROR) db = tmp_path / "aloha.db" test_db = Database() test_db.validate_db(db) assert f"DB file not found! Creating new empty DB at" in caplog.text @pytest.mark.parametrize("db_name,success", [ ("success.db", True), ("failure.db", False), ]) def test_delete_db( success, db_name, tmp_path, caplog, ): db = tmp_path / db_name test_db = Database() if success: caplog.set_level(logging.INFO) username = os.getlogin() db.write_text("Test") test_db.delete_db(db) assert os.path.exists(db) is False assert "Database deleted by user" in caplog.text assert username in caplog.text else: caplog.set_level(logging.ERROR) test_db.delete_db(db) assert "Error deleting database" in caplog.text assert db_name in caplog.text
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,652
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/dialog/preferences.py
"""Preferences Dialog""" import logging import sys from pathlib import Path from PyQt5 import QtCore, QtWidgets import helpers.functions import ui.functions from config import configurations from ui.enums import ( FontRadio, FontSize, IconRadio, PrefixRadio, PreviewRadio, SeparatorCombo, SuffixRadio, ThemeRadio, ) from ui.window.ui_preferences import ( Ui_PrefsDialog, ) logger = logging.getLogger(__name__) class PreferencesDialog(QtWidgets.QDialog, Ui_PrefsDialog): def __init__(self, parent=None): super(PreferencesDialog, self).__init__(parent) self.setupUi(self) ui.functions.set_window_icon(self) self._setup_ui_buttons() self._setup_description_check() self._setup_project_path() self._setup_theme() self._setup_font() self._setup_assets_config() self._setup_preview() self._setup_log() def _setup_ui_buttons(self): self.btnDialogBox.button(QtWidgets.QDialogButtonBox.RestoreDefaults).setToolTip('Restore Defaults') self.btnDialogBox.button(QtWidgets.QDialogButtonBox.RestoreDefaults).clicked.connect(helpers.functions.ham) self.btnDialogBox.button(QtWidgets.QDialogButtonBox.Apply).setToolTip('Apply') self.btnDialogBox.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect(helpers.functions.ham) self.btnDialogBox.accepted.connect(self.apply) self.btnDialogBox.rejected.connect(self.reject) def _setup_description_check(self): """Setup Description Check""" self.descCheck.setChecked(configurations.get_setting('Settings', 'ShowDescriptionPanel')) def _setup_project_path(self): """Setup Project Path""" self.project_path = configurations.get_setting('Settings', 'ProjectPath') self.default_path = self.project_path self.projectPathLine.setText(self.project_path) self.projectPathTool.clicked.connect(self.project_path_dialog) def _setup_theme(self): """Setup Theme""" theme = getattr(ThemeRadio, configurations.get_setting('UI', 'Theme').upper()) theme_radios = { "LIGHT": self.themeRadioLight, "DARK": self.themeRadioDark, } ui.functions.checked_radio(theme, theme_radios) def _setup_font(self): """Setup Font""" font_mode = FontRadio(configurations.get_setting('UI', 'FontMode')) font_radios = { "DEFAULT": self.fontRadioDefault, "MONOSPACE": self.fontRadioMonospace, "CUSTOM": self.fontRadioCustom, } ui.functions.checked_radio(font_mode, font_radios) self.fontSizeComboBox.setCurrentIndex( self.fontSizeComboBox.findText( FontSize(configurations.get_setting('UI', 'FontSize')).name, QtCore.Qt.MatchContains, ) ) # Show blank in dropdown list if font not found self.fontListComboBox.setCurrentIndex( self.fontListComboBox.findText( configurations.get_setting('UI', 'Font'), QtCore.Qt.MatchContains, ) ) def _setup_assets_config(self): """Setup Assets Config""" self.maxCharSpinner.setValue(configurations.get_setting('Assets', 'MaxChars')) self.separatorCombo.setCurrentIndex( self.separatorCombo.findText( configurations.get_setting('Assets', 'Separator'), QtCore.Qt.MatchContains, ) ) self.boxPrefix.setChecked(configurations.get_setting('Assets', 'UsePrefix')) prefix_type = PrefixRadio(configurations.get_setting('Assets', 'PrefixType')) prefix_radios = { "FIRST": self.prefixRadioFirst, "WHOLE": self.prefixRadioWhole, } ui.functions.checked_radio(prefix_type, prefix_radios) self.boxSuffix.setChecked(configurations.get_setting('Assets', 'UseSuffix')) suffix_type = SuffixRadio(configurations.get_setting('Assets', 'SuffixType')) suffix_radios = { "VERSION": self.suffixRadioVersion, "CUSTOM": self.suffixRadioCustomName, } ui.functions.checked_radio(suffix_type, suffix_radios) self.suffixVersionCombo.setCurrentIndex(configurations.get_setting('Assets', 'SuffixVersionMode')) self.suffixCustomName.setText(configurations.get_setting('Assets', 'SuffixCustomName')) self.populate_list_value(self.categoryList, "Assets", "CategoryList") self.categoryBtnAdd.clicked.connect(lambda: self.add_item_list(self.categoryList, "Category")) self.categoryBtnRemove.clicked.connect(lambda: self.remove_item_list(self.categoryList)) self.populate_list_value(self.subfolderList, "Assets", "SubfolderList") self.subfolderBtnAdd.clicked.connect(lambda: self.add_item_list(self.subfolderList, "Subfolder")) self.subfolderBtnRemove.clicked.connect(lambda: self.remove_item_list(self.subfolderList)) def _setup_preview(self): """Setup Preview""" preview = PreviewRadio(configurations.get_setting('Advanced', 'Preview')) preview_radios = { "SMALL": self.previewRadioSmall, "BIG": self.previewRadioBig, "CUSTOM": self.previewRadioCustom, } ui.functions.checked_radio(preview, preview_radios) icon = IconRadio(configurations.get_setting('Advanced', 'IconThumbnails')) icon_radios = { "ENABLE": self.iconRadioEnable, "DISABLE": self.iconRadioDisable, "GENERIC": self.iconRadioGeneric, } ui.functions.checked_radio(icon, icon_radios) self.previewSpinnerCustom.setValue(configurations.get_setting('Advanced', 'PreviewCustomMaxSize')) def _setup_log(self): """Setup Log""" self.logButtonOpen.clicked.connect(helpers.functions.ham) self.logButtonClear.clicked.connect(helpers.functions.ham) self.logDebugCheck.setChecked(configurations.get_setting('Advanced', 'UseDebugLog')) def add_item_list(self, widget: QtWidgets.QListWidget, title="..."): """Add item to QListWidget. Parameters ---------- widget : QtWidgets.QListWidget QListWidget instance title : str Suffix for input dialog's title. """ item = QtWidgets.QListWidgetItem() text, ok = QtWidgets.QInputDialog.getText( self, f"Add {title}", "Name:", QtWidgets.QLineEdit.Normal, "", ) if ok and text: item.setText(str(text)) widget.addItem(item) def remove_item_list(self, widget: QtWidgets.QListWidget): """Remove items from QListWidget. Parameters ---------- widget : QtWidgets.QListWidget QListWidget instance """ items = widget.selectedItems() # Exit early if there is no selected items! if not items: return for item in items: widget.takeItem(widget.row(item)) def populate_list_value( self, list_widget: QtWidgets.QListWidget, section: str, setting: str, ): value_list = configurations.get_setting(section, setting) # 1. Exit early and log error if not a valid list object if not isinstance(value_list, list): logger.error("Not a valid list: %s", value_list) return # 2. Loop through list object and populate target list for value in value_list: item = QtWidgets.QListWidgetItem() item.setText(str(value)) list_widget.addItem(item) def project_path_dialog(self): """Opens Project Path Dialog. Uses QFileDialog for user to choose the directory for their project path. """ existing_path = Path(self.projectPathLine.text()).as_posix() # 1. Initialize selected directory path through QFileDialog path = QtWidgets.QFileDialog.getExistingDirectory( self, 'Choose Directory', Path.home().as_posix(), # Defaults to home directory QtWidgets.QFileDialog.ShowDirsOnly, # Filter list to Directory only ) # 2. If user cancel, revert to original value if not path: path = existing_path # 3. Set Project Path Line text field with new_path value logger.info("Selected Project Path: %s", path) self.projectPathLine.setText(path) def get_checkbox_value(self, widget: QtWidgets.QCheckBox, setting: str): value = widget.isChecked() config = {setting: value} return config def get_line_value(self, widget: QtWidgets.QLineEdit, setting: str): value = widget.text() config = {setting: value} return config def get_list_value(self, widget: QtWidgets.QListWidget, setting: str): items = [] for x in range(widget.count()): value = widget.item(x).text() items.append(value) config = {setting: items} return config def get_font(self): selection = self.fontBtnGrp.checkedId() if selection == -4: return self.fontListComboBox.currentText() return FontRadio(selection).font() def get_font_size(self): font_size = getattr(FontSize, self.fontSizeComboBox.currentText().upper()) return font_size.value def apply(self): checkboxes = ( (self.descCheck, "ShowDescriptionPanel"), (self.logDebugCheck, "UseDebugLog"), (self.boxPrefix, "UsePrefix"), (self.boxSuffix, "UseSuffix"), ) lines = ( (self.projectPathLine, "ProjectPath"), (self.suffixCustomName, "SuffixCustomName"), ) lists = ( (self.categoryList, "CategoryList"), (self.subfolderList, "SubfolderList"), ) config = {} for widget, setting in checkboxes: config.update( self.get_checkbox_value(widget, setting) ) for widget, setting in lines: config.update( self.get_line_value(widget, setting) ) for widget, setting in lists: config.update( self.get_list_value(widget, setting) ) config.update({ "Theme": ThemeRadio(self.themeBtnGrp.checkedId()).name, "Font": self.get_font(), "FontMode": self.fontBtnGrp.checkedId(), "FontSize": self.get_font_size(), "Preview": self.previewBtnGrp.checkedId(), "Separator": SeparatorCombo(self.separatorCombo.currentIndex()).name, "IconThumbnails": self.iconBtnGrp.checkedId(), "PrefixType": self.prefixBtnGrp.checkedId(), "SuffixType": self.suffixBtnGrp.checkedId(), "SuffixVersionMode": self.suffixVersionCombo.currentIndex(), "MaxChars": self.maxCharSpinner.value(), "PreviewCustomMaxSize": self.previewSpinnerCustom.value(), }) configurations.bulk_update_settings(config) ui.functions.generate_stylesheet( font=configurations.get_setting('UI', 'Font'), size=self.get_font_size(), ) self.accept() # Execute restart_app when OK def show_dialog(): dialog = PreferencesDialog() if dialog.exec_(): # Restart app to reinitialize new INI settings helpers.functions.restart_app() if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = PreferencesDialog() window.show() sys.exit(app.exec_())
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,653
hueyyeng/AssetsBrowser
refs/heads/develop
/tests/config/test_config.py
"""Test Config""" import pytest from config.configurations import ( create_config, get_config, get_setting, update_setting, bulk_update_settings, ) from config.exceptions import ConfigNotFoundException def test_create_config_successful(tmpdir): # 1. Create INI in temp directory toml_file = tmpdir.mkdir("create_config").join('test.toml') create_config(toml_file) # 2. List of expected tuples expected_sections_options = [ ('Settings', 'ProjectPath'), ('Settings', 'ShowDescriptionPanel'), ('Settings', 'CurrentProject'), ('UI', 'Font'), ('UI', 'Theme'), ('Assets', 'CategoryList'), ('Assets', 'MaxChars'), ('Assets', 'SubfolderList'), ] # 3. Check if the value is valid. config = get_config(toml_file) for section, option in expected_sections_options: assert option in config[section] def test_load_list(tmpdir): test_toml = tmpdir.mkdir("load_list").join('test.toml') create_config(test_toml) existing_assets = get_setting('Assets', 'CategoryList', test_toml) existing_qty = len(existing_assets) expected_assets = [ "BG", "CH", "FX", "Props", "Vehicles", ] expected_qty = len(expected_assets) assert existing_qty == expected_qty for asset in expected_assets: assert asset in existing_assets def test_config_not_found(): invalid_path = "foo/bar/spam.toml" with pytest.raises(ConfigNotFoundException): get_config(invalid_path) def test_update_config(tmpdir): test_toml = tmpdir.mkdir("update_config").join('test.toml') create_config(test_toml) default_font = get_setting('UI', 'Font', test_toml) assert default_font == 'sans-serif' update_setting('UI', 'Font', 'Comic Sans MS', test_toml) new_font = get_setting('UI', 'Font', test_toml) assert new_font == 'Comic Sans MS' def test_bulk_update_settings(tmpdir): test_toml = tmpdir.mkdir('bulk_update_settings').join('test.toml') create_config(test_toml) new_config = { 'Font': 'Times New Roman', 'MaxChars': 666, } bulk_update_settings(new_config, test_toml) font = get_setting('UI', 'Font', test_toml) assert font == 'Times New Roman' max_chars = get_setting('Assets', 'MaxChars', test_toml) assert max_chars == 666
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,654
hueyyeng/AssetsBrowser
refs/heads/develop
/database/models.py
"""Database Models""" import peewee as pw from database.mixins import ( DateTimeMixin, NameDescriptionMixin, ) from database.validators import ModelValidator SQLITE_DB = pw.SqliteDatabase(None) class BaseModel(pw.Model, ModelValidator): class Meta: database = SQLITE_DB class Project( BaseModel, DateTimeMixin, NameDescriptionMixin, ): short_name = pw.FixedCharField( max_length=4, verbose_name='Short Name', unique=True, ) def __str__(self): if self.name: return f"{self.short_name} - {self.name}" return self.short_name class Category( BaseModel, NameDescriptionMixin, ): def __str__(self): return str(self.name) class Asset( BaseModel, DateTimeMixin, NameDescriptionMixin, ): category = pw.ForeignKeyField( Category, backref='assets', verbose_name='Category', ) project = pw.ForeignKeyField( Project, backref='assets', verbose_name='Project', ) short_name = pw.FixedCharField( max_length=12, verbose_name='Short Name', ) def __str__(self): return f"{self.category.name[0].lower()}{self.short_name}" class Application( BaseModel, NameDescriptionMixin, ): # Max path length for older Windows API is 260 chars path = pw.CharField( null=True, max_length=260, verbose_name='Path', ) def __str__(self): return f"{self.name}" class AssetItemFormat( BaseModel, ): name = pw.CharField( max_length=50, verbose_name='Name', ) format = pw.CharField( max_length=100, verbose_name='Format', ) application = pw.ForeignKeyField( Application, null=True, backref='asset_formats', verbose_name='Application', ) def __str__(self): return self.short_name class AssetItem( BaseModel, DateTimeMixin, NameDescriptionMixin, ): asset = pw.ForeignKeyField( Asset, backref='asset_items', verbose_name='Asset', ) category = pw.ForeignKeyField( Category, backref='asset_items', verbose_name='Category', ) project = pw.ForeignKeyField( Project, backref='asset_items', verbose_name='Project', ) format = pw.ForeignKeyField( AssetItemFormat, null=True, backref='asset_items', verbose_name='Format', ) short_name = pw.FixedCharField( max_length=12, verbose_name='Short Name', ) version = pw.SmallIntegerField( default=1, verbose_name='Version', ) def __str__(self): return f"{self.category.name[0].lower()}{self.short_name}_v{self.version:03}"
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,655
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/dialog/asset_item_format.py
"""Asset Item Format Dialog""" import logging import sys from PyQt5 import QtWidgets import ui.functions from database.db import Database from helpers.functions import ham from ui.window.ui_asset_item_format import ( Ui_AssetItemFormatDialog, ) logger = logging.getLogger(__name__) class AssetItemFormatDialog(QtWidgets.QDialog, Ui_AssetItemFormatDialog): def __init__(self, parent=None): super(AssetItemFormatDialog, self).__init__(parent) self.setupUi(self) self.db = Database(use_default_db=True) ui.functions.set_window_icon(self) self._setup_ui_buttons() def _setup_ui_buttons(self): self.btnPushAdd.clicked.connect(ham) self.btnPushRemove.clicked.connect(ham) self.btnPushClear.clicked.connect(ham) def show_dialog(): dialog = AssetItemFormatDialog() if not dialog.exec_(): logger.debug('Aborting Manage Asset Item Format...') if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = AssetItemFormatDialog() window.show() sys.exit(app.exec_())
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,656
hueyyeng/AssetsBrowser
refs/heads/develop
/config/configurations.py
"""Configurations""" import logging import os from pathlib import Path from typing import Any import toml from config.constants import ( DEFAULT_CATEGORY, DEFAULT_SUBFOLDER, TOML_PATH, ) from config.exceptions import ( ConfigNotFoundException, ) logger = logging.getLogger(__name__) def create_config(path: str): """Create TOML config file Parameters ---------- path : str Path to TOML config file """ config = {} # 1.1 Settings settings = config['Settings'] = {} settings['ProjectPath'] = Path.home().as_posix() # Defaults to home directory settings['ShowDescriptionPanel'] = False settings['CurrentProject'] = '.nodefaultvalue' ui = config['UI'] = {} ui['Font'] = 'sans-serif' ui['FontMode'] = -2 ui['FontSize'] = 12 ui['Theme'] = 'LIGHT' assets = config['Assets'] = {} assets['UsePrefix'] = True assets['PrefixType'] = -2 assets['UseSuffix'] = False assets['SuffixType'] = -2 assets['SuffixVersionMode'] = -2 assets['SuffixCustomName'] = '' assets['MaxChars'] = 3 assets['Separator'] = "UNDERSCORE" assets['CategoryList'] = DEFAULT_CATEGORY assets['SubfolderList'] = DEFAULT_SUBFOLDER advanced = config['Advanced'] = {} advanced['Preview'] = -2 advanced['PreviewCustomMaxSize'] = 150 advanced['IconThumbnails'] = -2 advanced['UseDebugLog'] = False # 2. Write to TOML file try: with open(path, 'w') as config_file: toml.dump(config, config_file) except PermissionError as e: logger.error(e) def get_config(path: str) -> dict: """Returns dict from parsed TOML config file. Parameters ---------- path : str Directory path for TOML file. Returns ------- dict Dict from TOML config file. """ if not os.path.exists(path): logger.error('ERROR: TOML FILE NOT FOUND AT %s', path) raise ConfigNotFoundException config = toml.load(path) return config def get_setting(section: str, setting: str, path=None) -> Any: """Returns a setting from the TOML file. Parameters ---------- section : str Section name. setting : str Setting name. path : str or None Directory path for TOML file. If None, default to TOML_PATH Returns ------- Any The value of the setting. """ if not path: path = TOML_PATH config = get_config(path) value = config[section][setting] message = ( '{section} {setting} is {value}'.format( section=section, setting=setting, value=value, ) ) logger.debug(message) return value def update_setting(section: str, setting: str, value: Any, path=None): """Update a setting in the TOML file. Parameters ---------- section : str Section name. setting : str Setting name. value : Any Value of the setting. path : str or None Directory path for TOML file. If None, default to TOML_PATH """ if not path: path = TOML_PATH config = get_config(path) config[section][setting] = value with open(path, 'w') as config_file: toml.dump(config, config_file) def bulk_update_settings(settings: dict, path=None): """Bulk update settings in TOML file. Use in Preferences dialog. Parameters ---------- settings : dict path : str or None Directory path for TOML file. If None, default to TOML_PATH """ if not path: path = TOML_PATH config = get_config(path) for section in config.keys(): for setting in settings.keys(): if setting in config[section].keys() and config[section][setting] != settings[setting]: old_value = config[section][setting] new_value = settings[setting] config[section][setting] = new_value logger.info({ "msg": "Updating TOML file", "setting": setting, "old_value": old_value, "new_value": new_value, }) with open(path, 'w') as config_file: toml.dump(config, config_file)
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,657
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/window/ui_asset.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'K:\Library\Python\AssetsBrowser\ui\window\asset.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_AssetDialog(object): def setupUi(self, AssetDialog): AssetDialog.setObjectName("AssetDialog") AssetDialog.resize(350, 600) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(AssetDialog.sizePolicy().hasHeightForWidth()) AssetDialog.setSizePolicy(sizePolicy) AssetDialog.setMinimumSize(QtCore.QSize(350, 600)) AssetDialog.setMaximumSize(QtCore.QSize(500, 750)) AssetDialog.setFocusPolicy(QtCore.Qt.StrongFocus) AssetDialog.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.verticalLayout = QtWidgets.QVBoxLayout(AssetDialog) self.verticalLayout.setObjectName("verticalLayout") self.categoryGroup = QtWidgets.QGroupBox(AssetDialog) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.categoryGroup.setFont(font) self.categoryGroup.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.categoryGroup.setFlat(False) self.categoryGroup.setCheckable(False) self.categoryGroup.setObjectName("categoryGroup") self.layoutVtlCat = QtWidgets.QVBoxLayout(self.categoryGroup) self.layoutVtlCat.setObjectName("layoutVtlCat") self.categoryComboBox = QtWidgets.QComboBox(self.categoryGroup) self.categoryComboBox.setObjectName("categoryComboBox") self.layoutVtlCat.addWidget(self.categoryComboBox) self.variantGroupBox = QtWidgets.QGroupBox(self.categoryGroup) self.variantGroupBox.setCheckable(True) self.variantGroupBox.setChecked(False) self.variantGroupBox.setObjectName("variantGroupBox") self.horizontalLayout = QtWidgets.QHBoxLayout(self.variantGroupBox) self.horizontalLayout.setObjectName("horizontalLayout") self.variantRadioAlphabet = QtWidgets.QRadioButton(self.variantGroupBox) self.variantRadioAlphabet.setChecked(True) self.variantRadioAlphabet.setObjectName("variantRadioAlphabet") self.horizontalLayout.addWidget(self.variantRadioAlphabet) self.variantRadioNumber = QtWidgets.QRadioButton(self.variantGroupBox) self.variantRadioNumber.setChecked(False) self.variantRadioNumber.setObjectName("variantRadioNumber") self.horizontalLayout.addWidget(self.variantRadioNumber) self.layoutVtlCat.addWidget(self.variantGroupBox) self.verticalLayout.addWidget(self.categoryGroup) self.detailsGroup = QtWidgets.QGroupBox(AssetDialog) self.detailsGroup.setEnabled(True) self.detailsGroup.setObjectName("detailsGroup") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.detailsGroup) self.verticalLayout_2.setObjectName("verticalLayout_2") self.shortNameLabel = QtWidgets.QLabel(self.detailsGroup) self.shortNameLabel.setObjectName("shortNameLabel") self.verticalLayout_2.addWidget(self.shortNameLabel) self.shortNameLineEdit = QtWidgets.QLineEdit(self.detailsGroup) self.shortNameLineEdit.setMaxLength(3) self.shortNameLineEdit.setObjectName("shortNameLineEdit") self.verticalLayout_2.addWidget(self.shortNameLineEdit) self.nameLabel = QtWidgets.QLabel(self.detailsGroup) self.nameLabel.setObjectName("nameLabel") self.verticalLayout_2.addWidget(self.nameLabel) self.nameLineEdit = QtWidgets.QLineEdit(self.detailsGroup) self.nameLineEdit.setObjectName("nameLineEdit") self.verticalLayout_2.addWidget(self.nameLineEdit) self.descLabel = QtWidgets.QLabel(self.detailsGroup) self.descLabel.setObjectName("descLabel") self.verticalLayout_2.addWidget(self.descLabel) self.descTextEdit = QtWidgets.QPlainTextEdit(self.detailsGroup) self.descTextEdit.setObjectName("descTextEdit") self.verticalLayout_2.addWidget(self.descTextEdit) self.verticalLayout.addWidget(self.detailsGroup) self.previewGroup = QtWidgets.QGroupBox(AssetDialog) self.previewGroup.setFlat(False) self.previewGroup.setCheckable(True) self.previewGroup.setChecked(False) self.previewGroup.setObjectName("previewGroup") self.layoutVtlPreview = QtWidgets.QVBoxLayout(self.previewGroup) self.layoutVtlPreview.setObjectName("layoutVtlPreview") self.previewText = QtWidgets.QPlainTextEdit(self.previewGroup) self.previewText.setReadOnly(True) self.previewText.setObjectName("previewText") self.layoutVtlPreview.addWidget(self.previewText) self.verticalLayout.addWidget(self.previewGroup) self.layoutCreateCancel = QtWidgets.QHBoxLayout() self.layoutCreateCancel.setObjectName("layoutCreateCancel") self.btnCreate = QtWidgets.QPushButton(AssetDialog) self.btnCreate.setObjectName("btnCreate") self.layoutCreateCancel.addWidget(self.btnCreate) self.btnCancel = QtWidgets.QPushButton(AssetDialog) self.btnCancel.setObjectName("btnCancel") self.layoutCreateCancel.addWidget(self.btnCancel) self.verticalLayout.addLayout(self.layoutCreateCancel) self.retranslateUi(AssetDialog) QtCore.QMetaObject.connectSlotsByName(AssetDialog) def retranslateUi(self, AssetDialog): _translate = QtCore.QCoreApplication.translate AssetDialog.setWindowTitle(_translate("AssetDialog", "Create New Asset")) self.categoryGroup.setTitle(_translate("AssetDialog", "Category")) self.variantGroupBox.setTitle(_translate("AssetDialog", "Variant")) self.variantRadioAlphabet.setText(_translate("AssetDialog", "Alphabet")) self.variantRadioNumber.setText(_translate("AssetDialog", "Number")) self.detailsGroup.setTitle(_translate("AssetDialog", "Details")) self.shortNameLabel.setText(_translate("AssetDialog", "Shortname")) self.shortNameLineEdit.setToolTip(_translate("AssetDialog", "Alphanumeric only")) self.nameLabel.setText(_translate("AssetDialog", "Full Name")) self.descLabel.setText(_translate("AssetDialog", "Description")) self.descTextEdit.setPlaceholderText(_translate("AssetDialog", "Asset\'s description goes here")) self.previewGroup.setTitle(_translate("AssetDialog", "Preview")) self.btnCreate.setText(_translate("AssetDialog", "Create")) self.btnCancel.setText(_translate("AssetDialog", "Cancel"))
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,658
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/window/ui_preferences.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'K:\Library\Python\AssetsBrowser\ui\window\preferences.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_PrefsDialog(object): def setupUi(self, PrefsDialog): PrefsDialog.setObjectName("PrefsDialog") PrefsDialog.setEnabled(True) PrefsDialog.resize(519, 614) PrefsDialog.setMinimumSize(QtCore.QSize(519, 614)) PrefsDialog.setFocusPolicy(QtCore.Qt.StrongFocus) PrefsDialog.setContextMenuPolicy(QtCore.Qt.PreventContextMenu) PrefsDialog.setSizeGripEnabled(True) self.gridLayout = QtWidgets.QGridLayout(PrefsDialog) self.gridLayout.setObjectName("gridLayout") self.sideLayout = QtWidgets.QVBoxLayout() self.sideLayout.setObjectName("sideLayout") self.sideList = QtWidgets.QListWidget(PrefsDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sideList.sizePolicy().hasHeightForWidth()) self.sideList.setSizePolicy(sizePolicy) self.sideList.setMaximumSize(QtCore.QSize(100, 16777215)) self.sideList.setObjectName("sideList") item = QtWidgets.QListWidgetItem() self.sideList.addItem(item) item = QtWidgets.QListWidgetItem() self.sideList.addItem(item) item = QtWidgets.QListWidgetItem() self.sideList.addItem(item) self.sideLayout.addWidget(self.sideList) self.gridLayout.addLayout(self.sideLayout, 3, 0, 2, 1) self.btnDialogBox = QtWidgets.QDialogButtonBox(PrefsDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnDialogBox.sizePolicy().hasHeightForWidth()) self.btnDialogBox.setSizePolicy(sizePolicy) self.btnDialogBox.setOrientation(QtCore.Qt.Horizontal) self.btnDialogBox.setStandardButtons(QtWidgets.QDialogButtonBox.Apply|QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok|QtWidgets.QDialogButtonBox.RestoreDefaults) self.btnDialogBox.setCenterButtons(False) self.btnDialogBox.setObjectName("btnDialogBox") self.gridLayout.addWidget(self.btnDialogBox, 5, 1, 1, 1) self.stackedWidget = QtWidgets.QStackedWidget(PrefsDialog) self.stackedWidget.setObjectName("stackedWidget") self.pageGeneral = QtWidgets.QWidget() sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pageGeneral.sizePolicy().hasHeightForWidth()) self.pageGeneral.setSizePolicy(sizePolicy) self.pageGeneral.setObjectName("pageGeneral") self.formLayout_11 = QtWidgets.QFormLayout(self.pageGeneral) self.formLayout_11.setObjectName("formLayout_11") self.projectPathLayout = QtWidgets.QHBoxLayout() self.projectPathLayout.setObjectName("projectPathLayout") self.projectPathLabel = QtWidgets.QLabel(self.pageGeneral) self.projectPathLabel.setSizeIncrement(QtCore.QSize(0, 0)) self.projectPathLabel.setObjectName("projectPathLabel") self.projectPathLayout.addWidget(self.projectPathLabel) self.projectPathLine = QtWidgets.QLineEdit(self.pageGeneral) self.projectPathLine.setFocusPolicy(QtCore.Qt.StrongFocus) self.projectPathLine.setEchoMode(QtWidgets.QLineEdit.Normal) self.projectPathLine.setDragEnabled(False) self.projectPathLine.setPlaceholderText("") self.projectPathLine.setObjectName("projectPathLine") self.projectPathLayout.addWidget(self.projectPathLine) self.projectPathTool = QtWidgets.QToolButton(self.pageGeneral) self.projectPathTool.setAutoRaise(False) self.projectPathTool.setArrowType(QtCore.Qt.NoArrow) self.projectPathTool.setObjectName("projectPathTool") self.projectPathLayout.addWidget(self.projectPathTool) self.formLayout_11.setLayout(0, QtWidgets.QFormLayout.SpanningRole, self.projectPathLayout) self.settingsDivider1 = QtWidgets.QFrame(self.pageGeneral) self.settingsDivider1.setFrameShape(QtWidgets.QFrame.HLine) self.settingsDivider1.setFrameShadow(QtWidgets.QFrame.Sunken) self.settingsDivider1.setObjectName("settingsDivider1") self.formLayout_11.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.settingsDivider1) self.descCheck = QtWidgets.QCheckBox(self.pageGeneral) self.descCheck.setObjectName("descCheck") self.formLayout_11.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.descCheck) self.settingsDivider2 = QtWidgets.QFrame(self.pageGeneral) self.settingsDivider2.setFrameShape(QtWidgets.QFrame.HLine) self.settingsDivider2.setFrameShadow(QtWidgets.QFrame.Sunken) self.settingsDivider2.setObjectName("settingsDivider2") self.formLayout_11.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.settingsDivider2) self.boxTheme = QtWidgets.QGroupBox(self.pageGeneral) self.boxTheme.setObjectName("boxTheme") self.formLayout = QtWidgets.QFormLayout(self.boxTheme) self.formLayout.setObjectName("formLayout") self.themeRadioLight = QtWidgets.QRadioButton(self.boxTheme) self.themeRadioLight.setShortcut("") self.themeRadioLight.setChecked(True) self.themeRadioLight.setObjectName("themeRadioLight") self.themeBtnGrp = QtWidgets.QButtonGroup(PrefsDialog) self.themeBtnGrp.setObjectName("themeBtnGrp") self.themeBtnGrp.addButton(self.themeRadioLight) self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.themeRadioLight) self.themeRadioDark = QtWidgets.QRadioButton(self.boxTheme) self.themeRadioDark.setShortcut("") self.themeRadioDark.setObjectName("themeRadioDark") self.themeBtnGrp.addButton(self.themeRadioDark) self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.themeRadioDark) self.formLayout_11.setWidget(4, QtWidgets.QFormLayout.SpanningRole, self.boxTheme) self.boxFont = QtWidgets.QGroupBox(self.pageGeneral) self.boxFont.setObjectName("boxFont") self.formLayout_10 = QtWidgets.QFormLayout(self.boxFont) self.formLayout_10.setObjectName("formLayout_10") self.fontRadioDefault = QtWidgets.QRadioButton(self.boxFont) self.fontRadioDefault.setChecked(True) self.fontRadioDefault.setObjectName("fontRadioDefault") self.fontBtnGrp = QtWidgets.QButtonGroup(PrefsDialog) self.fontBtnGrp.setObjectName("fontBtnGrp") self.fontBtnGrp.addButton(self.fontRadioDefault) self.formLayout_10.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.fontRadioDefault) self.fontRadioMonospace = QtWidgets.QRadioButton(self.boxFont) self.fontRadioMonospace.setObjectName("fontRadioMonospace") self.fontBtnGrp.addButton(self.fontRadioMonospace) self.formLayout_10.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.fontRadioMonospace) self.fontSizeLabel = QtWidgets.QLabel(self.boxFont) self.fontSizeLabel.setObjectName("fontSizeLabel") self.formLayout_10.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.fontSizeLabel) self.fontSizeComboBox = QtWidgets.QComboBox(self.boxFont) self.fontSizeComboBox.setObjectName("fontSizeComboBox") self.fontSizeComboBox.addItem("") self.fontSizeComboBox.addItem("") self.fontSizeComboBox.addItem("") self.formLayout_10.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.fontSizeComboBox) self.fontCustomLayout = QtWidgets.QHBoxLayout() self.fontCustomLayout.setSpacing(24) self.fontCustomLayout.setObjectName("fontCustomLayout") self.fontRadioCustom = QtWidgets.QRadioButton(self.boxFont) self.fontRadioCustom.setObjectName("fontRadioCustom") self.fontBtnGrp.addButton(self.fontRadioCustom) self.fontCustomLayout.addWidget(self.fontRadioCustom) self.fontListComboBox = QtWidgets.QFontComboBox(self.boxFont) self.fontListComboBox.setEnabled(False) self.fontListComboBox.setObjectName("fontListComboBox") self.fontCustomLayout.addWidget(self.fontListComboBox) self.fontCustomLayout.setStretch(1, 1) self.formLayout_10.setLayout(2, QtWidgets.QFormLayout.SpanningRole, self.fontCustomLayout) self.formLayout_11.setWidget(5, QtWidgets.QFormLayout.SpanningRole, self.boxFont) self.stackedWidget.addWidget(self.pageGeneral) self.pageAssets = QtWidgets.QWidget() self.pageAssets.setObjectName("pageAssets") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.pageAssets) self.verticalLayout_3.setObjectName("verticalLayout_3") self.boxNaming = QtWidgets.QGroupBox(self.pageAssets) self.boxNaming.setObjectName("boxNaming") self.formLayout_3 = QtWidgets.QFormLayout(self.boxNaming) self.formLayout_3.setObjectName("formLayout_3") self.maxCharLayout = QtWidgets.QFormLayout() self.maxCharLayout.setObjectName("maxCharLayout") self.maxCharLabel = QtWidgets.QLabel(self.boxNaming) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.maxCharLabel.sizePolicy().hasHeightForWidth()) self.maxCharLabel.setSizePolicy(sizePolicy) self.maxCharLabel.setObjectName("maxCharLabel") self.maxCharLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.maxCharLabel) self.maxCharSpinner = QtWidgets.QSpinBox(self.boxNaming) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.maxCharSpinner.sizePolicy().hasHeightForWidth()) self.maxCharSpinner.setSizePolicy(sizePolicy) self.maxCharSpinner.setMinimum(3) self.maxCharSpinner.setObjectName("maxCharSpinner") self.maxCharLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.maxCharSpinner) self.formLayout_3.setLayout(0, QtWidgets.QFormLayout.LabelRole, self.maxCharLayout) self.separatorLayout = QtWidgets.QFormLayout() self.separatorLayout.setObjectName("separatorLayout") self.separatorLabel = QtWidgets.QLabel(self.boxNaming) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.separatorLabel.sizePolicy().hasHeightForWidth()) self.separatorLabel.setSizePolicy(sizePolicy) self.separatorLabel.setObjectName("separatorLabel") self.separatorLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.separatorLabel) self.separatorCombo = QtWidgets.QComboBox(self.boxNaming) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.separatorCombo.sizePolicy().hasHeightForWidth()) self.separatorCombo.setSizePolicy(sizePolicy) self.separatorCombo.setMaximumSize(QtCore.QSize(120, 16777215)) self.separatorCombo.setObjectName("separatorCombo") self.separatorCombo.addItem("") self.separatorCombo.addItem("") self.separatorLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.separatorCombo) self.formLayout_3.setLayout(1, QtWidgets.QFormLayout.LabelRole, self.separatorLayout) self.boxPrefix = QtWidgets.QGroupBox(self.boxNaming) self.boxPrefix.setCheckable(True) self.boxPrefix.setObjectName("boxPrefix") self.verticalLayout = QtWidgets.QVBoxLayout(self.boxPrefix) self.verticalLayout.setObjectName("verticalLayout") self.prefixRadioFirst = QtWidgets.QRadioButton(self.boxPrefix) self.prefixRadioFirst.setChecked(True) self.prefixRadioFirst.setObjectName("prefixRadioFirst") self.prefixBtnGrp = QtWidgets.QButtonGroup(PrefsDialog) self.prefixBtnGrp.setObjectName("prefixBtnGrp") self.prefixBtnGrp.addButton(self.prefixRadioFirst) self.verticalLayout.addWidget(self.prefixRadioFirst) self.prefixRadioWhole = QtWidgets.QRadioButton(self.boxPrefix) self.prefixRadioWhole.setChecked(False) self.prefixRadioWhole.setObjectName("prefixRadioWhole") self.prefixBtnGrp.addButton(self.prefixRadioWhole) self.verticalLayout.addWidget(self.prefixRadioWhole) self.formLayout_3.setWidget(2, QtWidgets.QFormLayout.SpanningRole, self.boxPrefix) self.boxSuffix = QtWidgets.QGroupBox(self.boxNaming) self.boxSuffix.setCheckable(True) self.boxSuffix.setChecked(True) self.boxSuffix.setObjectName("boxSuffix") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.boxSuffix) self.verticalLayout_2.setObjectName("verticalLayout_2") self.suffixVersionLayout = QtWidgets.QFormLayout() self.suffixVersionLayout.setObjectName("suffixVersionLayout") self.suffixRadioVersion = QtWidgets.QRadioButton(self.boxSuffix) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.suffixRadioVersion.sizePolicy().hasHeightForWidth()) self.suffixRadioVersion.setSizePolicy(sizePolicy) self.suffixRadioVersion.setChecked(True) self.suffixRadioVersion.setObjectName("suffixRadioVersion") self.suffixBtnGrp = QtWidgets.QButtonGroup(PrefsDialog) self.suffixBtnGrp.setObjectName("suffixBtnGrp") self.suffixBtnGrp.addButton(self.suffixRadioVersion) self.suffixVersionLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.suffixRadioVersion) self.suffixVersionCombo = QtWidgets.QComboBox(self.boxSuffix) self.suffixVersionCombo.setMaximumSize(QtCore.QSize(120, 16777215)) self.suffixVersionCombo.setObjectName("suffixVersionCombo") self.suffixVersionCombo.addItem("") self.suffixVersionCombo.addItem("") self.suffixVersionLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.suffixVersionCombo) self.verticalLayout_2.addLayout(self.suffixVersionLayout) self.suffixCustomLayout = QtWidgets.QHBoxLayout() self.suffixCustomLayout.setObjectName("suffixCustomLayout") self.suffixRadioCustomName = QtWidgets.QRadioButton(self.boxSuffix) self.suffixRadioCustomName.setObjectName("suffixRadioCustomName") self.suffixBtnGrp.addButton(self.suffixRadioCustomName) self.suffixCustomLayout.addWidget(self.suffixRadioCustomName) self.suffixCustomName = QtWidgets.QLineEdit(self.boxSuffix) self.suffixCustomName.setEnabled(False) self.suffixCustomName.setObjectName("suffixCustomName") self.suffixCustomLayout.addWidget(self.suffixCustomName) self.verticalLayout_2.addLayout(self.suffixCustomLayout) self.formLayout_3.setWidget(3, QtWidgets.QFormLayout.SpanningRole, self.boxSuffix) self.verticalLayout_3.addWidget(self.boxNaming) self.boxCategory = QtWidgets.QGroupBox(self.pageAssets) self.boxCategory.setObjectName("boxCategory") self.formLayout_4 = QtWidgets.QFormLayout(self.boxCategory) self.formLayout_4.setObjectName("formLayout_4") self.categoryBtnLayout = QtWidgets.QFormLayout() self.categoryBtnLayout.setObjectName("categoryBtnLayout") self.categoryBtnAdd = QtWidgets.QPushButton(self.boxCategory) self.categoryBtnAdd.setObjectName("categoryBtnAdd") self.categoryBtnLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.categoryBtnAdd) self.categoryBtnRemove = QtWidgets.QPushButton(self.boxCategory) self.categoryBtnRemove.setObjectName("categoryBtnRemove") self.categoryBtnLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.categoryBtnRemove) self.formLayout_4.setLayout(0, QtWidgets.QFormLayout.LabelRole, self.categoryBtnLayout) self.categoryList = QtWidgets.QListWidget(self.boxCategory) self.categoryList.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.categoryList.setObjectName("categoryList") self.formLayout_4.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.categoryList) self.verticalLayout_3.addWidget(self.boxCategory) self.boxSubfolder = QtWidgets.QGroupBox(self.pageAssets) self.boxSubfolder.setObjectName("boxSubfolder") self.formLayout_5 = QtWidgets.QFormLayout(self.boxSubfolder) self.formLayout_5.setObjectName("formLayout_5") self.subfolderBtnLayout = QtWidgets.QFormLayout() self.subfolderBtnLayout.setObjectName("subfolderBtnLayout") self.subfolderBtnAdd = QtWidgets.QPushButton(self.boxSubfolder) self.subfolderBtnAdd.setObjectName("subfolderBtnAdd") self.subfolderBtnLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.subfolderBtnAdd) self.subfolderBtnRemove = QtWidgets.QPushButton(self.boxSubfolder) self.subfolderBtnRemove.setObjectName("subfolderBtnRemove") self.subfolderBtnLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.subfolderBtnRemove) self.formLayout_5.setLayout(0, QtWidgets.QFormLayout.LabelRole, self.subfolderBtnLayout) self.subfolderList = QtWidgets.QListWidget(self.boxSubfolder) self.subfolderList.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.subfolderList.setObjectName("subfolderList") self.formLayout_5.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.subfolderList) self.verticalLayout_3.addWidget(self.boxSubfolder) self.stackedWidget.addWidget(self.pageAssets) self.pageAdvanced = QtWidgets.QWidget() self.pageAdvanced.setObjectName("pageAdvanced") self.formLayout_9 = QtWidgets.QFormLayout(self.pageAdvanced) self.formLayout_9.setObjectName("formLayout_9") self.boxLog = QtWidgets.QGroupBox(self.pageAdvanced) self.boxLog.setObjectName("boxLog") self.formLayout_6 = QtWidgets.QFormLayout(self.boxLog) self.formLayout_6.setObjectName("formLayout_6") self.logDebugCheck = QtWidgets.QCheckBox(self.boxLog) self.logDebugCheck.setObjectName("logDebugCheck") self.formLayout_6.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.logDebugCheck) self.logDivider2 = QtWidgets.QFrame(self.boxLog) self.logDivider2.setFrameShape(QtWidgets.QFrame.HLine) self.logDivider2.setFrameShadow(QtWidgets.QFrame.Sunken) self.logDivider2.setObjectName("logDivider2") self.formLayout_6.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.logDivider2) self.logDebugWarning = QtWidgets.QLabel(self.boxLog) self.logDebugWarning.setObjectName("logDebugWarning") self.formLayout_6.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.logDebugWarning) self.logDivider1 = QtWidgets.QFrame(self.boxLog) self.logDivider1.setFrameShape(QtWidgets.QFrame.HLine) self.logDivider1.setFrameShadow(QtWidgets.QFrame.Sunken) self.logDivider1.setObjectName("logDivider1") self.formLayout_6.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.logDivider1) self.logButtonLayout = QtWidgets.QHBoxLayout() self.logButtonLayout.setObjectName("logButtonLayout") self.logButtonOpen = QtWidgets.QPushButton(self.boxLog) self.logButtonOpen.setObjectName("logButtonOpen") self.logButtonLayout.addWidget(self.logButtonOpen) self.logButtonClear = QtWidgets.QPushButton(self.boxLog) self.logButtonClear.setObjectName("logButtonClear") self.logButtonLayout.addWidget(self.logButtonClear) self.formLayout_6.setLayout(4, QtWidgets.QFormLayout.LabelRole, self.logButtonLayout) self.formLayout_9.setWidget(1, QtWidgets.QFormLayout.SpanningRole, self.boxLog) self.boxColumnView = QtWidgets.QGroupBox(self.pageAdvanced) self.boxColumnView.setObjectName("boxColumnView") self.formLayout_8 = QtWidgets.QFormLayout(self.boxColumnView) self.formLayout_8.setObjectName("formLayout_8") self.boxPreview = QtWidgets.QGroupBox(self.boxColumnView) self.boxPreview.setObjectName("boxPreview") self.formLayout_7 = QtWidgets.QFormLayout(self.boxPreview) self.formLayout_7.setObjectName("formLayout_7") self.previewHelpLabel = QtWidgets.QLabel(self.boxPreview) self.previewHelpLabel.setObjectName("previewHelpLabel") self.formLayout_7.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.previewHelpLabel) self.previewLayout = QtWidgets.QVBoxLayout() self.previewLayout.setObjectName("previewLayout") self.previewRadioSmall = QtWidgets.QRadioButton(self.boxPreview) self.previewRadioSmall.setChecked(True) self.previewRadioSmall.setObjectName("previewRadioSmall") self.previewBtnGrp = QtWidgets.QButtonGroup(PrefsDialog) self.previewBtnGrp.setObjectName("previewBtnGrp") self.previewBtnGrp.addButton(self.previewRadioSmall) self.previewLayout.addWidget(self.previewRadioSmall) self.previewRadioBig = QtWidgets.QRadioButton(self.boxPreview) self.previewRadioBig.setObjectName("previewRadioBig") self.previewBtnGrp.addButton(self.previewRadioBig) self.previewLayout.addWidget(self.previewRadioBig) self.previewCustomLayout = QtWidgets.QHBoxLayout() self.previewCustomLayout.setObjectName("previewCustomLayout") self.previewRadioCustom = QtWidgets.QRadioButton(self.boxPreview) self.previewRadioCustom.setObjectName("previewRadioCustom") self.previewBtnGrp.addButton(self.previewRadioCustom) self.previewCustomLayout.addWidget(self.previewRadioCustom) self.previewSpinnerCustom = QtWidgets.QSpinBox(self.boxPreview) self.previewSpinnerCustom.setEnabled(False) self.previewSpinnerCustom.setMinimum(150) self.previewSpinnerCustom.setMaximum(1000) self.previewSpinnerCustom.setObjectName("previewSpinnerCustom") self.previewCustomLayout.addWidget(self.previewSpinnerCustom) self.previewLayout.addLayout(self.previewCustomLayout) self.formLayout_7.setLayout(1, QtWidgets.QFormLayout.LabelRole, self.previewLayout) self.formLayout_8.setWidget(0, QtWidgets.QFormLayout.SpanningRole, self.boxPreview) self.boxIcon = QtWidgets.QGroupBox(self.boxColumnView) self.boxIcon.setObjectName("boxIcon") self.formLayout_2 = QtWidgets.QFormLayout(self.boxIcon) self.formLayout_2.setObjectName("formLayout_2") self.iconRadioLayout = QtWidgets.QVBoxLayout() self.iconRadioLayout.setObjectName("iconRadioLayout") self.iconRadioEnable = QtWidgets.QRadioButton(self.boxIcon) self.iconRadioEnable.setChecked(True) self.iconRadioEnable.setObjectName("iconRadioEnable") self.iconBtnGrp = QtWidgets.QButtonGroup(PrefsDialog) self.iconBtnGrp.setObjectName("iconBtnGrp") self.iconBtnGrp.addButton(self.iconRadioEnable) self.iconRadioLayout.addWidget(self.iconRadioEnable) self.iconRadioDisable = QtWidgets.QRadioButton(self.boxIcon) self.iconRadioDisable.setChecked(False) self.iconRadioDisable.setObjectName("iconRadioDisable") self.iconBtnGrp.addButton(self.iconRadioDisable) self.iconRadioLayout.addWidget(self.iconRadioDisable) self.iconRadioGeneric = QtWidgets.QRadioButton(self.boxIcon) self.iconRadioGeneric.setMaximumSize(QtCore.QSize(331, 16777215)) self.iconRadioGeneric.setChecked(False) self.iconRadioGeneric.setObjectName("iconRadioGeneric") self.iconBtnGrp.addButton(self.iconRadioGeneric) self.iconRadioLayout.addWidget(self.iconRadioGeneric) self.formLayout_2.setLayout(0, QtWidgets.QFormLayout.LabelRole, self.iconRadioLayout) self.formLayout_8.setWidget(1, QtWidgets.QFormLayout.SpanningRole, self.boxIcon) self.formLayout_9.setWidget(0, QtWidgets.QFormLayout.SpanningRole, self.boxColumnView) self.stackedWidget.addWidget(self.pageAdvanced) self.gridLayout.addWidget(self.stackedWidget, 4, 1, 1, 1) self.retranslateUi(PrefsDialog) self.stackedWidget.setCurrentIndex(1) self.sideList.currentRowChanged['int'].connect(self.stackedWidget.setCurrentIndex) self.suffixRadioVersion.toggled['bool'].connect(self.suffixVersionCombo.setEnabled) self.previewRadioCustom.toggled['bool'].connect(self.previewSpinnerCustom.setEnabled) self.fontRadioCustom.toggled['bool'].connect(self.fontListComboBox.setEnabled) self.suffixRadioCustomName.toggled['bool'].connect(self.suffixCustomName.setEnabled) QtCore.QMetaObject.connectSlotsByName(PrefsDialog) def retranslateUi(self, PrefsDialog): _translate = QtCore.QCoreApplication.translate PrefsDialog.setWindowTitle(_translate("PrefsDialog", "Preferences")) __sortingEnabled = self.sideList.isSortingEnabled() self.sideList.setSortingEnabled(False) item = self.sideList.item(0) item.setText(_translate("PrefsDialog", "General")) item = self.sideList.item(1) item.setText(_translate("PrefsDialog", "Assets")) item = self.sideList.item(2) item.setText(_translate("PrefsDialog", "Advanced")) self.sideList.setSortingEnabled(__sortingEnabled) self.projectPathLabel.setText(_translate("PrefsDialog", "Project Path:")) self.projectPathLine.setToolTip(_translate("PrefsDialog", "Insert your project path here. E.g. \"P:/\", \"media/projects\"")) self.projectPathTool.setToolTip(_translate("PrefsDialog", "Choose directory")) self.projectPathTool.setText(_translate("PrefsDialog", "...")) self.descCheck.setToolTip(_translate("PrefsDialog", "Display description for assets.")) self.descCheck.setText(_translate("PrefsDialog", "Show Description Panel")) self.boxTheme.setTitle(_translate("PrefsDialog", "Theme")) self.themeRadioLight.setToolTip(_translate("PrefsDialog", "Fusion Style")) self.themeRadioLight.setText(_translate("PrefsDialog", "Default (Light)")) self.themeRadioDark.setToolTip(_translate("PrefsDialog", "QDarkStyle")) self.themeRadioDark.setText(_translate("PrefsDialog", "Dark")) self.boxFont.setTitle(_translate("PrefsDialog", "Font")) self.fontRadioDefault.setText(_translate("PrefsDialog", "Default (Sans Serif)")) self.fontRadioMonospace.setText(_translate("PrefsDialog", "Monospace")) self.fontSizeLabel.setText(_translate("PrefsDialog", "Size:")) self.fontSizeComboBox.setItemText(0, _translate("PrefsDialog", "Default")) self.fontSizeComboBox.setItemText(1, _translate("PrefsDialog", "Tiny")) self.fontSizeComboBox.setItemText(2, _translate("PrefsDialog", "Large")) self.fontRadioCustom.setToolTip(_translate("PrefsDialog", "Select font that best suited to your project locale and language")) self.fontRadioCustom.setText(_translate("PrefsDialog", "Custom font")) self.boxNaming.setTitle(_translate("PrefsDialog", "Naming Convention")) self.maxCharLabel.setText(_translate("PrefsDialog", "Max characters:")) self.maxCharSpinner.setToolTip(_translate("PrefsDialog", "Min: 3, Max: 99")) self.separatorLabel.setText(_translate("PrefsDialog", "Separator:")) self.separatorCombo.setItemText(0, _translate("PrefsDialog", " _ (underscore)")) self.separatorCombo.setItemText(1, _translate("PrefsDialog", " - (dash)")) self.boxPrefix.setTitle(_translate("PrefsDialog", "Prefix")) self.prefixRadioFirst.setText(_translate("PrefsDialog", "Use first character of category (e.g.: p)")) self.prefixRadioWhole.setText(_translate("PrefsDialog", "Use whole category (e.g.: props)")) self.boxSuffix.setTitle(_translate("PrefsDialog", "Suffix")) self.suffixRadioVersion.setText(_translate("PrefsDialog", "Use versioning (v):")) self.suffixVersionCombo.setItemText(0, _translate("PrefsDialog", "lowercase (v001)")) self.suffixVersionCombo.setItemText(1, _translate("PrefsDialog", "UPPERCASE (V001)")) self.suffixRadioCustomName.setText(_translate("PrefsDialog", "Use custom naming:")) self.boxCategory.setTitle(_translate("PrefsDialog", "Categories")) self.categoryBtnAdd.setText(_translate("PrefsDialog", "Add")) self.categoryBtnRemove.setText(_translate("PrefsDialog", "Remove")) self.boxSubfolder.setTitle(_translate("PrefsDialog", "Subfolders")) self.subfolderBtnAdd.setText(_translate("PrefsDialog", "Add")) self.subfolderBtnRemove.setText(_translate("PrefsDialog", "Remove")) self.boxLog.setTitle(_translate("PrefsDialog", "Logs")) self.logDebugCheck.setToolTip(_translate("PrefsDialog", "Log file will include debug statement. Useful for troubleshooting.")) self.logDebugCheck.setText(_translate("PrefsDialog", "Enable Debug Log")) self.logDebugWarning.setText(_translate("PrefsDialog", "WARNING: Debug log will result in bigger log file size!")) self.logButtonOpen.setToolTip(_translate("PrefsDialog", "Clear current log contents")) self.logButtonOpen.setText(_translate("PrefsDialog", "Open Log Location")) self.logButtonClear.setToolTip(_translate("PrefsDialog", "Clear current log contents")) self.logButtonClear.setText(_translate("PrefsDialog", "Clear Log")) self.boxColumnView.setTitle(_translate("PrefsDialog", "Column View")) self.boxPreview.setTitle(_translate("PrefsDialog", "Preview")) self.previewHelpLabel.setText(_translate("PrefsDialog", "Preview size for supported images")) self.previewRadioSmall.setToolTip(_translate("PrefsDialog", "150px")) self.previewRadioSmall.setText(_translate("PrefsDialog", "Small")) self.previewRadioBig.setToolTip(_translate("PrefsDialog", "300px")) self.previewRadioBig.setText(_translate("PrefsDialog", "Big")) self.previewRadioCustom.setToolTip(_translate("PrefsDialog", "Valid range: 150 to 1000")) self.previewRadioCustom.setText(_translate("PrefsDialog", "Custom max size:")) self.boxIcon.setTitle(_translate("PrefsDialog", "Icon Thumbnails")) self.iconRadioEnable.setToolTip(_translate("PrefsDialog", "Default. Performance hit when navigating directory with lots of supported images.")) self.iconRadioEnable.setText(_translate("PrefsDialog", "Enable")) self.iconRadioDisable.setToolTip(_translate("PrefsDialog", "No icons display in Column View. Fastest performance.")) self.iconRadioDisable.setText(_translate("PrefsDialog", "Disable (fastest)")) self.iconRadioGeneric.setToolTip(_translate("PrefsDialog", "Display generic icons by disabling icon thumbnail generation for supported images.")) self.iconRadioGeneric.setText(_translate("PrefsDialog", "Use generic icons"))
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,659
hueyyeng/AssetsBrowser
refs/heads/develop
/helpers/utils.py
"""Utilities""" import logging import os import platform import subprocess import sys from pathlib import Path from PyQt5 import QtGui, QtWidgets from config import configurations from config.constants import TOML_PATH from helpers.exceptions import InvalidProjectPath logger = logging.getLogger(__name__) def alert_window(title: str, text: str): """PyQt MessageBox Alert Window Reusable generic alert window. Parameters ---------- title : str Title of the alert window. text : str Text message of the alert window. """ # 1. Set up QApplication, QWidget and QMessageBox instance app = QtWidgets.QApplication(sys.argv) app.setWindowIcon(QtGui.QIcon('ui/icons/logo.ico')) widget = QtWidgets.QWidget() message = QtWidgets.QMessageBox # 2. Move PyQt Window position to center of the screen qt_rectangle = widget.frameGeometry() center_point = QtWidgets.QDesktopWidget().availableGeometry().center() qt_rectangle.moveCenter(center_point) widget.move(qt_rectangle.topLeft()) # 3. Display widget (alert window) message.warning(widget, title, text, message.Ok) widget.show() def valid_project_path(project: str, toml=None): """Check path validity and update TOML if invalid. Check if PROJECT_PATH is valid and reset to home directory if error. A warning message will pop up to inform user that the Project Path has been reset to the user's home directory. Parameters ---------- project : str Path to project directory. toml : str or None Path to TOML file. If None, default to TOML_PATH Raises ------ InvalidProjectPath If project path value in TOML is invalid. """ if not toml: toml = TOML_PATH # 1. Exit early if exists if Path(project).exists(): logger.info("Project path exists: %s", project) return # 2. Set Project Path to User's Home directory home = Path.home().as_posix() # 3. Update ProjectPath in TOML with User's Home directory path configurations.update_setting( 'Settings', 'ProjectPath', value=home, path=toml, ) # 4. Raise Alert Window warning_text = ( "Project Path doesn't exists!\n\n" f"Project Path has been set to {home} temporarily.\n\n" "Please restart Assets Browser." ) alert_window('Warning', warning_text) raise InvalidProjectPath(project) def get_file_size(size: int or float, precision=2) -> str: """Get file size. Refactor from https://stackoverflow.com/a/32009595/8337847 Parameters ---------- size : int or float The file size value. precision : int The decimal place. Returns ------- str The formatted message of the file size. See Also -------- hurry.file_size : https://pypi.python.org/pypi/hurry.file_size/ """ suffixes = ['B', 'KB', 'MB', 'GB', 'TB'] suffix_index = 0 while size > 1024 and suffix_index < 4: suffix_index += 1 # Increment the index of the suffix size = size / 1024 # Apply the division # Return using String formatting. f for float and s for string. return "%.*f %s" % (precision, size, suffixes[suffix_index]) def reveal_in_os(path: str): """Reveal in OS. Reveal the file/directory path using the OS File Manager. Parameters ---------- path : str The path of the file/directory. """ system = platform.system() path = Path(path) # Default to macOS since no extra handling cmd = (['open', '-R', path.as_posix()]) if system == 'Windows' and path.is_dir(): cmd = str('explorer /e,' + path) elif system == 'Windows' and path.exists(): cmd = str('explorer /select,' + path) elif system == 'Linux': dir_path = '/'.join(path.split('/')[0:-1]) # Omit file_name from path # subprocess.Popen(['xdg-open', dir_path]) cmd = (['xdg-open', dir_path]) subprocess.call(cmd) def open_file(target: str): """ Open selected file using the OS associated program. Parameters ---------- target : str Path to file/directory. """ system = platform.system() try: os.startfile(target) except OSError: command = 'xdg-open' # Linux if system == 'Darwin': command = 'open' subprocess.call([command, target])
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,660
hueyyeng/AssetsBrowser
refs/heads/develop
/database/db.py
"""Database""" import logging import os import peewee as pw from database.constants import DEFAULT_MODELS from database.models import SQLITE_DB logger = logging.getLogger(__name__) DEFAULT_DB = os.path.join(os.path.dirname(__file__), 'db.sqlite3') SQLITE_MEMORY = ':memory:' class Database: """"Assets' Browser Database. Currently configure using sqlite for standalone execution without relying on another DB driver like MySQL or Postgres """ def __init__(self, db=None, sqlite_on_delete=True, use_default_db=False): self.db = SQLITE_DB if not db and use_default_db: db = DEFAULT_DB self.connect_db(db, sqlite_on_delete) self.check_db_schema() def connect_db(self, db=None, sqlite_on_delete: bool = True): """Connect to database Parameters ---------- db : str or None Path to DB. By default, None which will use in memory DB sqlite_on_delete : bool Set SQLite on Delete. By default, True. Returns ------- object : peewee.SqliteDatabase """ if not db: db = SQLITE_MEMORY self.validate_db(db) pragmas = {'foreign_keys': 1} if sqlite_on_delete else {} self.db.init(db, pragmas=pragmas) def validate_db(self, db: str): """Validate DB Verify if DB path exists. If IOError, create a new DB file at the specify path. Parameters ---------- db : str Path to DB """ if not db == SQLITE_MEMORY: try: open(db, 'r').close() logger.info('DB file found: %s', db) except IOError: open(db, 'w').close() logger.error('DB file not found! Creating new empty DB at: %s', db) def delete_db(self, db: str = DEFAULT_DB): """Delete DB Parameters ---------- db : str Path to DB """ username = os.getlogin() try: os.remove(db) logger.info("Database deleted by user: %s", username) except OSError as e: logger.error("Error deleting database: %s - %s.", e.filename, e.strerror) def check_db_schema(self): """Check DB Schema Always create DB schema on creation startup if using SQLITE_MEMORY. If a DB path are given, verify if the DB has existing tables and create tables if none (for new DB file) """ if not self.db.get_tables(): self.create_db_schema() def create_db_schema(self): """Create DB schema""" self.create_db_tables(DEFAULT_MODELS) def create_db_tables(self, tables: list or pw.Model): """Create DB tables Parameters ---------- tables : list or peewee.Model List of str. If Model, convert to list of Model. """ if not isinstance(tables, list): tables = [tables] self.db.create_tables(tables)
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,661
hueyyeng/AssetsBrowser
refs/heads/develop
/helpers/exceptions.py
"""Custom exceptions""" import logging logger = logging.getLogger(__name__) class InvalidProjectPath(Exception): def __init__(self, path): Exception.__init__(self, path) self.message = "Project Path doesn't exists: %s", str(path) logger.error(self.message) def __str__(self): return str(self.message) class ApplicationAlreadyExists(Exception): def __init__(self, app): Exception.__init__(self, app) self.message = "QApplication instance already exists: %s", str(app) logger.error(self.message) def __str__(self): return str(self.message)
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,662
hueyyeng/AssetsBrowser
refs/heads/develop
/config/exceptions.py
"""Config exceptions""" class ConfigNotFoundException(Exception): pass
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,663
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/window/ui_main.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'K:\Library\Python\AssetsBrowser\ui\window\main.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setWindowModality(QtCore.Qt.NonModal) MainWindow.resize(851, 603) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) MainWindow.setMinimumSize(QtCore.QSize(800, 600)) MainWindow.setMaximumSize(QtCore.QSize(16777215, 16777215)) font = QtGui.QFont() font.setPointSize(8) MainWindow.setFont(font) MainWindow.setDocumentMode(False) MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded) self.centralWidget = QtWidgets.QWidget(MainWindow) self.centralWidget.setEnabled(True) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.centralWidget.sizePolicy().hasHeightForWidth()) self.centralWidget.setSizePolicy(sizePolicy) self.centralWidget.setMinimumSize(QtCore.QSize(800, 550)) self.centralWidget.setObjectName("centralWidget") self.gridLayout = QtWidgets.QGridLayout(self.centralWidget) self.gridLayout.setObjectName("gridLayout") self.splitter = QtWidgets.QSplitter(self.centralWidget) self.splitter.setEnabled(True) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setChildrenCollapsible(False) self.splitter.setObjectName("splitter") self.actionWidget = QtWidgets.QWidget(self.splitter) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.actionWidget.sizePolicy().hasHeightForWidth()) self.actionWidget.setSizePolicy(sizePolicy) self.actionWidget.setMinimumSize(QtCore.QSize(230, 0)) self.actionWidget.setMaximumSize(QtCore.QSize(230, 16777215)) self.actionWidget.setObjectName("actionWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.actionWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.labelProject = QtWidgets.QLabel(self.actionWidget) self.labelProject.setObjectName("labelProject") self.verticalLayout.addWidget(self.labelProject) self.projectComboBox = QtWidgets.QComboBox(self.actionWidget) self.projectComboBox.setLayoutDirection(QtCore.Qt.LeftToRight) self.projectComboBox.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContentsOnFirstShow) self.projectComboBox.setFrame(True) self.projectComboBox.setObjectName("projectComboBox") self.verticalLayout.addWidget(self.projectComboBox) self.pushBtnNewAsset = QtWidgets.QPushButton(self.actionWidget) self.pushBtnNewAsset.setObjectName("pushBtnNewAsset") self.verticalLayout.addWidget(self.pushBtnNewAsset) self.pushBtnNewAssetItem = QtWidgets.QPushButton(self.actionWidget) self.pushBtnNewAssetItem.setObjectName("pushBtnNewAssetItem") self.verticalLayout.addWidget(self.pushBtnNewAssetItem) self.pushBtnManageFormat = QtWidgets.QPushButton(self.actionWidget) self.pushBtnManageFormat.setObjectName("pushBtnManageFormat") self.verticalLayout.addWidget(self.pushBtnManageFormat) self.debugCheckBox = QtWidgets.QCheckBox(self.actionWidget) self.debugCheckBox.setEnabled(True) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.debugCheckBox.sizePolicy().hasHeightForWidth()) self.debugCheckBox.setSizePolicy(sizePolicy) self.debugCheckBox.setObjectName("debugCheckBox") self.verticalLayout.addWidget(self.debugCheckBox) self.textEdit = QtWidgets.QTextEdit(self.actionWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.textEdit.sizePolicy().hasHeightForWidth()) self.textEdit.setSizePolicy(sizePolicy) self.textEdit.setObjectName("textEdit") self.verticalLayout.addWidget(self.textEdit) spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.MinimumExpanding) self.verticalLayout.addItem(spacerItem) self.labelCredits = QtWidgets.QLabel(self.actionWidget) self.labelCredits.setTextFormat(QtCore.Qt.AutoText) self.labelCredits.setOpenExternalLinks(True) self.labelCredits.setObjectName("labelCredits") self.verticalLayout.addWidget(self.labelCredits) self.labelCredits.raise_() self.debugCheckBox.raise_() self.pushBtnNewAsset.raise_() self.labelProject.raise_() self.textEdit.raise_() self.projectComboBox.raise_() self.pushBtnNewAssetItem.raise_() self.pushBtnManageFormat.raise_() self.tabWidget = QtWidgets.QTabWidget(self.splitter) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) self.tabWidget.setSizePolicy(sizePolicy) self.tabWidget.setObjectName("tabWidget") self.tabHelp = QtWidgets.QWidget() self.tabHelp.setObjectName("tabHelp") self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.tabHelp) self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.frameHelp = QtWidgets.QFrame(self.tabHelp) self.frameHelp.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frameHelp.setFrameShadow(QtWidgets.QFrame.Sunken) self.frameHelp.setObjectName("frameHelp") self.horizontalLayout = QtWidgets.QHBoxLayout(self.frameHelp) self.horizontalLayout.setObjectName("horizontalLayout") self.textBrowserHelp = QtWidgets.QTextBrowser(self.frameHelp) self.textBrowserHelp.setOpenExternalLinks(True) self.textBrowserHelp.setObjectName("textBrowserHelp") self.horizontalLayout.addWidget(self.textBrowserHelp) self.horizontalLayout_3.addWidget(self.frameHelp) self.tabWidget.addTab(self.tabHelp, "") self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralWidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 851, 21)) self.menubar.setObjectName("menubar") self.menuFile = QtWidgets.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuView = QtWidgets.QMenu(self.menubar) self.menuView.setObjectName("menuView") self.menuHelp = QtWidgets.QMenu(self.menubar) self.menuHelp.setObjectName("menuHelp") self.menuSettings = QtWidgets.QMenu(self.menubar) self.menuSettings.setObjectName("menuSettings") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionQuit = QtWidgets.QAction(MainWindow) self.actionQuit.setObjectName("actionQuit") self.actionAbout = QtWidgets.QAction(MainWindow) self.actionAbout.setObjectName("actionAbout") self.actionAlwaysOnTop = QtWidgets.QAction(MainWindow) self.actionAlwaysOnTop.setCheckable(True) self.actionAlwaysOnTop.setObjectName("actionAlwaysOnTop") self.actionPreferences = QtWidgets.QAction(MainWindow) self.actionPreferences.setObjectName("actionPreferences") self.actionNewAsset = QtWidgets.QAction(MainWindow) self.actionNewAsset.setObjectName("actionNewAsset") self.actionNewAssetItem = QtWidgets.QAction(MainWindow) self.actionNewAssetItem.setObjectName("actionNewAssetItem") self.actionApplicationsList = QtWidgets.QAction(MainWindow) self.actionApplicationsList.setObjectName("actionApplicationsList") self.actionManageFormat = QtWidgets.QAction(MainWindow) self.actionManageFormat.setObjectName("actionManageFormat") self.menuFile.addAction(self.actionNewAsset) self.menuFile.addAction(self.actionNewAssetItem) self.menuFile.addAction(self.actionManageFormat) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit) self.menuView.addAction(self.actionAlwaysOnTop) self.menuHelp.addAction(self.actionAbout) self.menuSettings.addAction(self.actionPreferences) self.menuSettings.addAction(self.actionApplicationsList) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.menubar.addAction(self.menuSettings.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Assets Browser")) self.labelProject.setText(_translate("MainWindow", "Project:")) self.pushBtnNewAsset.setText(_translate("MainWindow", "Create New Asset")) self.pushBtnNewAssetItem.setText(_translate("MainWindow", "Create New Asset Item")) self.pushBtnManageFormat.setText(_translate("MainWindow", "Manage Asset Item Format")) self.debugCheckBox.setText(_translate("MainWindow", "Show Debug Panel")) self.labelCredits.setText(_translate("MainWindow", "<html><head/><body><p>Huey Yeng © 2017-2021</p><p><a href=\"https://taukeke.com\"><span style=\" text-decoration: underline; color:#0000ff;\">taukeke.com<br/></span></a><a href=\"https://github.com/hueyyeng/AssetsBrowser\"><span style=\" text-decoration: underline; color:#0000ff;\">Assets Browser@ GitHub</span></a></p></body></html>")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabHelp), _translate("MainWindow", "Help")) self.menuFile.setTitle(_translate("MainWindow", "&File")) self.menuView.setTitle(_translate("MainWindow", "&View")) self.menuHelp.setTitle(_translate("MainWindow", "&Help")) self.menuSettings.setTitle(_translate("MainWindow", "&Settings")) self.actionQuit.setText(_translate("MainWindow", "&Quit")) self.actionAbout.setText(_translate("MainWindow", "&About Assets Browser")) self.actionAlwaysOnTop.setText(_translate("MainWindow", "Always on &Top")) self.actionPreferences.setText(_translate("MainWindow", "&Preferences...")) self.actionNewAsset.setText(_translate("MainWindow", "&New Asset")) self.actionNewAssetItem.setText(_translate("MainWindow", "New &Asset Item")) self.actionApplicationsList.setText(_translate("MainWindow", "&Applications List...")) self.actionManageFormat.setText(_translate("MainWindow", "&Manage Asset Item Format"))
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,664
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/dialog/applications_list.py
"""Applications List Dialog""" import logging import sys from PyQt5 import QtWidgets import ui.functions from database.db import Database from helpers.functions import ham from ui.window.ui_applications_list import ( Ui_AppListDialog, ) logger = logging.getLogger(__name__) class AppListDialog(QtWidgets.QDialog, Ui_AppListDialog): def __init__(self, parent=None): super(AppListDialog, self).__init__(parent) self.setupUi(self) self.db = Database(use_default_db=True) ui.functions.set_window_icon(self) self._setup_ui_buttons() def _setup_ui_buttons(self): self.btnPushAdd.clicked.connect(ham) self.btnPushRemove.clicked.connect(ham) self.btnPushClear.clicked.connect(ham) def show_dialog(): dialog = AppListDialog() if not dialog.exec_(): logger.debug('Aborting Applications List...') if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = AppListDialog() window.show() sys.exit(app.exec_())
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,665
hueyyeng/AssetsBrowser
refs/heads/develop
/tests/database/test_projects.py
from pytest import mark import peewee as pw from database.models import ( Asset, Category, Project, ) from database.db import Database class TestProjects: def setup(self): self.test_db = Database() def test_create_project(self): project_name = "Super Good" project_short_name = "SG" project_desc = "Sequel to Good" project_data = { "name": project_name, "short_name": project_short_name, "description": project_desc, } Project.create(**project_data) p = Project.get(**project_data) assert p.name == project_name assert p.description == project_desc assert p.short_name == project_short_name assert str(p) == "SG - Super Good" def test_create_project_with_short_name_only(self): project_short_name = "SG" project_data = { "short_name": project_short_name, } Project.create(**project_data) p = Project.get(**project_data) assert not p.name assert not p.description assert p.short_name == project_short_name assert str(p) == "SG"
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,666
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/window/ui_asset_item_format.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'K:\Library\Python\AssetsBrowser\ui\window\asset_item_format.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_AssetItemFormatDialog(object): def setupUi(self, AssetItemFormatDialog): AssetItemFormatDialog.setObjectName("AssetItemFormatDialog") AssetItemFormatDialog.resize(480, 360) AssetItemFormatDialog.setMinimumSize(QtCore.QSize(480, 360)) self.verticalLayout = QtWidgets.QVBoxLayout(AssetItemFormatDialog) self.verticalLayout.setObjectName("verticalLayout") self.btnPushLayout = QtWidgets.QHBoxLayout() self.btnPushLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize) self.btnPushLayout.setSpacing(12) self.btnPushLayout.setObjectName("btnPushLayout") self.btnPushAdd = QtWidgets.QPushButton(AssetItemFormatDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPushAdd.sizePolicy().hasHeightForWidth()) self.btnPushAdd.setSizePolicy(sizePolicy) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/resources/plus-circle.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btnPushAdd.setIcon(icon) self.btnPushAdd.setIconSize(QtCore.QSize(30, 30)) self.btnPushAdd.setCheckable(False) self.btnPushAdd.setDefault(False) self.btnPushAdd.setFlat(False) self.btnPushAdd.setObjectName("btnPushAdd") self.btnPushLayout.addWidget(self.btnPushAdd) self.btnPushRemove = QtWidgets.QPushButton(AssetItemFormatDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPushRemove.sizePolicy().hasHeightForWidth()) self.btnPushRemove.setSizePolicy(sizePolicy) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(":/resources/minus-circle.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btnPushRemove.setIcon(icon1) self.btnPushRemove.setIconSize(QtCore.QSize(30, 30)) self.btnPushRemove.setCheckable(False) self.btnPushRemove.setObjectName("btnPushRemove") self.btnPushLayout.addWidget(self.btnPushRemove) self.btnPushClear = QtWidgets.QPushButton(AssetItemFormatDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPushClear.sizePolicy().hasHeightForWidth()) self.btnPushClear.setSizePolicy(sizePolicy) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(":/resources/x-circle.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btnPushClear.setIcon(icon2) self.btnPushClear.setIconSize(QtCore.QSize(30, 30)) self.btnPushClear.setCheckable(False) self.btnPushClear.setObjectName("btnPushClear") self.btnPushLayout.addWidget(self.btnPushClear) spacerItem = QtWidgets.QSpacerItem(539, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.btnPushLayout.addItem(spacerItem) self.verticalLayout.addLayout(self.btnPushLayout) self.tableAssetItemFormat = QtWidgets.QTableWidget(AssetItemFormatDialog) self.tableAssetItemFormat.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents) self.tableAssetItemFormat.setObjectName("tableAssetItemFormat") self.tableAssetItemFormat.setColumnCount(3) self.tableAssetItemFormat.setRowCount(1) item = QtWidgets.QTableWidgetItem() self.tableAssetItemFormat.setVerticalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableAssetItemFormat.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableAssetItemFormat.setHorizontalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableAssetItemFormat.setHorizontalHeaderItem(2, item) self.verticalLayout.addWidget(self.tableAssetItemFormat) self.label = QtWidgets.QLabel(AssetItemFormatDialog) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) spacerItem1 = QtWidgets.QSpacerItem(20, 15, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) self.verticalLayout.addItem(spacerItem1) self.btnExportLayout = QtWidgets.QHBoxLayout() self.btnExportLayout.setSpacing(6) self.btnExportLayout.setObjectName("btnExportLayout") self.btnExportCSV = QtWidgets.QPushButton(AssetItemFormatDialog) self.btnExportCSV.setEnabled(False) self.btnExportCSV.setFlat(False) self.btnExportCSV.setObjectName("btnExportCSV") self.btnExportLayout.addWidget(self.btnExportCSV) self.btnExportJSON = QtWidgets.QPushButton(AssetItemFormatDialog) self.btnExportJSON.setEnabled(False) self.btnExportJSON.setObjectName("btnExportJSON") self.btnExportLayout.addWidget(self.btnExportJSON) spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.btnExportLayout.addItem(spacerItem2) self.verticalLayout.addLayout(self.btnExportLayout) self.btnDialogBox = QtWidgets.QDialogButtonBox(AssetItemFormatDialog) self.btnDialogBox.setOrientation(QtCore.Qt.Horizontal) self.btnDialogBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.btnDialogBox.setObjectName("btnDialogBox") self.verticalLayout.addWidget(self.btnDialogBox) self.tableAssetItemFormat.raise_() self.btnDialogBox.raise_() self.label.raise_() self.btnExportCSV.raise_() self.retranslateUi(AssetItemFormatDialog) self.btnDialogBox.accepted.connect(AssetItemFormatDialog.accept) self.btnDialogBox.rejected.connect(AssetItemFormatDialog.reject) QtCore.QMetaObject.connectSlotsByName(AssetItemFormatDialog) def retranslateUi(self, AssetItemFormatDialog): _translate = QtCore.QCoreApplication.translate AssetItemFormatDialog.setWindowTitle(_translate("AssetItemFormatDialog", "Manage Asset Item Format")) self.btnPushAdd.setToolTip(_translate("AssetItemFormatDialog", "Add Asset Item Format")) self.btnPushRemove.setToolTip(_translate("AssetItemFormatDialog", "Remove selected Asset Item Formats")) self.btnPushClear.setToolTip(_translate("AssetItemFormatDialog", "Clear all Asset Item Formats")) item = self.tableAssetItemFormat.verticalHeaderItem(0) item.setText(_translate("AssetItemFormatDialog", "1")) item = self.tableAssetItemFormat.horizontalHeaderItem(0) item.setText(_translate("AssetItemFormatDialog", "Name")) item = self.tableAssetItemFormat.horizontalHeaderItem(1) item.setText(_translate("AssetItemFormatDialog", "Format")) item = self.tableAssetItemFormat.horizontalHeaderItem(2) item.setText(_translate("AssetItemFormatDialog", "Application")) self.label.setText(_translate("AssetItemFormatDialog", "<html><head/><body><p>Use comma as separator for multiple extensions in Format. Case insensitive.</p><p>E.g. <span style=\" font-weight:600;\">MA,MB</span> or <span style=\" font-weight:600;\">Max</span> or <span style=\" font-weight:600;\">hipnc,hip</span></p></body></html>")) self.btnExportCSV.setText(_translate("AssetItemFormatDialog", " Export to CSV ")) self.btnExportJSON.setText(_translate("AssetItemFormatDialog", " Export to JSON ")) from . import icons_rc
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,667
hueyyeng/AssetsBrowser
refs/heads/develop
/assetsbrowser.py
"""Assets Browser MainWindow""" import logging import os import sys from pathlib import Path from PyQt5 import QtCore, QtGui, QtWidgets import helpers.functions import helpers.utils import ui.functions from config import configurations from config.constants import TOML_PATH from config.utils import check_config_file from helpers.exceptions import ( ApplicationAlreadyExists, ) from helpers.widgets import ColumnViewWidget from ui.dialog import ( about, applications_list, asset, asset_item, asset_item_format, preferences, ) from ui.window import ui_main logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) EXIT_CODE_REBOOT = -123 class AssetsBrowser(QtWidgets.QMainWindow, ui_main.Ui_MainWindow): def __init__(self, parent=None): super(AssetsBrowser, self).__init__(parent) self.setupUi(self) ui.functions.set_window_icon(self) self._setup_window_properties() self._setup_menu_actions() self._setup_ui_buttons() self._setup_debug_log() self._setup_project_list_dropdown() self._setup_initial_tabs() self._setup_help_tab() def _setup_window_properties(self): """Setup Window Properties""" self.setWindowTitle('Assets Browser [PID: %d]' % QtWidgets.QApplication.applicationPid()) self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint) self.splitter.setSizes([150, 500]) ui.functions.center_screen(self) def _setup_menu_actions(self): # 1.2 Menu action goes here self.actionNewAsset.triggered.connect(asset.show_dialog) self.actionNewAssetItem.triggered.connect(asset_item.show_dialog) self.actionManageFormat.triggered.connect(asset_item_format.show_dialog) self.actionApplicationsList.triggered.connect(applications_list.show_dialog) self.actionAbout.triggered.connect(about.show_dialog) self.actionAlwaysOnTop.triggered.connect(lambda: ui.functions.always_on_top(self)) self.actionPreferences.triggered.connect(preferences.show_dialog) self.actionQuit.triggered.connect(helpers.functions.close_app) def _setup_ui_buttons(self): # 1.3 Setup input/button here self.pushBtnNewAsset.clicked.connect(asset.show_dialog) self.pushBtnNewAssetItem.clicked.connect(asset_item.show_dialog) self.pushBtnManageFormat.clicked.connect(asset_item_format.show_dialog) self.debugCheckBox.clicked.connect(self.show_debug) def _setup_debug_log(self): """Setup Debug Log""" # 1. Debug textbox self.textEdit.clear() self.textEdit.setHidden(True) self.textEdit.setEnabled(False) # 2. Redirect stdout/stderr to QTextEdit widget for debug log sys.stdout = OutLog(self.textEdit, sys.stdout) sys.stderr = OutLog(self.textEdit, sys.stderr, QtGui.QColor(255, 0, 0)) formatter = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=formatter) def _setup_project_list_dropdown(self): """Setup Project List Dropdown""" self.project_path = configurations.get_setting('Settings', 'ProjectPath') self.combobox_fsm = QtWidgets.QFileSystemModel() self.projectComboBox.setModel(self.combobox_fsm) root_idx = self.combobox_fsm.setRootPath(self.project_path) self.projectComboBox.setRootModelIndex(root_idx) self.combobox_fsm.directoryLoaded.connect(self.populate_project_list) self.projectComboBox.activated[str].connect(self.select_project) def _setup_initial_tabs(self): """Setup initial tabs Create ColumnView tabs using TOML CurrentProject value """ self.select_project() def _setup_help_tab(self): """Setup Help tab""" help_file = Path(__file__).parent / 'ui' / 'help' / 'help.html' self.textBrowserHelp.setSource(QtCore.QUrl.fromLocalFile(str(help_file))) def create_tabs(self, categories: list, project: str): """Create QColumnView tabs. Create QColumnView tabs dynamically from Assets' List. Parameters ---------- categories : :obj:`list` of :obj:`str` Array of categories in str format. project : str The project name. Notes ----- Uses ColumnViewWidget that inherit QColumnView with custom properties """ for category in categories: tab = QtWidgets.QWidget() self.tabWidget.addTab(tab, category) self.horizontalLayout = QtWidgets.QHBoxLayout(tab) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.addWidget(ColumnViewWidget(category, project)) def populate_project_list(self, path): """Populate Project directories name in Project List comboBox. This is a workaround to set the current project on startup as Qt will only populate the combobox after initializing QApplication instance due to the way FileSystemModel works. By using directoryLoaded signal, this function will be called and populate the combobox using setCurrentIndex and findText to retrieve the current project index. Parameters ---------- path : str Project directory path """ # 1. Loop and add the project directories name fsm_index = self.combobox_fsm.index(path) for i in range(self.combobox_fsm.rowCount(fsm_index)): project_idx = self.combobox_fsm.index(i, 0, fsm_index) self.projectComboBox.addItem(project_idx.data(), self.combobox_fsm.filePath(project_idx)) # 2. Set the current project based on TOML settings self.projectComboBox.setCurrentIndex( self.projectComboBox.findText( configurations.get_setting('Settings', 'CurrentProject'), QtCore.Qt.MatchContains, ) ) def select_project(self, project=None): """Select Project from Project List comboBox. Select project, clear existing tabs and create new tabs using the subdirectories in the project's Assets directory. Parameters ---------- project : str or None Project name. By default, None """ # 1. Use CurrentProject value from TOML on startup if not project: project = configurations.get_setting('Settings', 'CurrentProject') else: project = self.projectComboBox.currentText() configurations.update_setting('Settings', 'CurrentProject', project) # 2. Raised warning if Assets directory not found in project path assets_path = Path(self.project_path) / project / 'Assets' if not assets_path.is_dir(): warning_text = ( "Assets directory is unavailable.\n\n" "The Assets directory is either missing in the selected project\n" "directory or you do not have permission to access it.\n\n" ) helpers.utils.alert_window("Warning", warning_text) helpers.functions.close_app() # 3. Clear all tabs except Help count = 0 total_tabs = self.tabWidget.count() while count < total_tabs: count += 1 self.tabWidget.removeTab(1) # 4. Create tabs from Assets' subfolders self.categories = [] asset_categories = [a for a in os.listdir(str(assets_path)) if not a.startswith(('_', '.'))] for category in asset_categories: category_subfolder = assets_path / category if category_subfolder.is_dir(): self.categories.append(str(category)) self.create_tabs(self.categories, project) def show_debug(self): """Toggle Debug Display.""" text = self.textEdit if self.debugCheckBox.isChecked(): text.clear() text.setHidden(False) text.setEnabled(True) else: text.setHidden(True) text.setEnabled(False) def __del__(self): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ class OutLog(): def __init__(self, edit: QtWidgets.QTextEdit, out=None, color=None): """Redirect stdout to QTextEdit widget. Parameters ---------- edit : QtWidgets.QTextEdit QTextEdit object. out : object or None Alternate stream (can be the original sys.stdout). color : QtGui.QColor or None QColor object (i.e. color stderr a different color). """ self.edit = edit self.out = out self.color = color def write(self, text: str): """Write stdout print values to QTextEdit widget. Parameters ---------- text : str Print values from stdout. """ if self.color: text_color = self.edit.textColor() self.edit.setTextColor(text_color) if self.out: self.out.write(text) self.edit.moveCursor(QtGui.QTextCursor.End) self.edit.insertPlainText(text) def flush(self): """Flush Outlog when process terminates. This prevent Exit Code 120 from happening so the process can finished with Exit Code 0. """ self.out.flush() if __name__ == "__main__": # 1.1 Check for config file and create one if doesn't exists check_config_file(TOML_PATH) # 1.2 Raise error if invalid project path helpers.utils.valid_project_path(configurations.get_setting('Settings', 'ProjectPath')) # 2. Setup OS related settings ui.functions.taskbar_icon() # os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" # Temporary disable as scaling is wrong on Ubuntu 16.04 LTS # 3.1 Launch main window current_exit_code = EXIT_CODE_REBOOT while current_exit_code == EXIT_CODE_REBOOT: # 3.2 Initialize QApplication instance app = QtWidgets.QApplication.instance() if app is not None: raise ApplicationAlreadyExists(app) app = QtWidgets.QApplication(sys.argv) app.setStyleSheet(open('ui/stylesheet.css').read()) ui.functions.theme_loader(app) window = AssetsBrowser() window.show() exit_code = app.exec_() app = None
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,668
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/functions.py
"""UI Functions""" import ctypes import logging import platform from enum import Enum from pathlib import Path import qdarkstyle from PyQt5 import QtCore, QtGui, QtWidgets from config import configurations from config.constants import ICON_FILE logger = logging.getLogger(__name__) def set_window_icon(widget: QtWidgets.QWidget, icon=None): """Set PyQt Window Icon Parameters ---------- widget : QtWidgets.QWidget icon : str or None Path to icon file. If None, use default icon (file.png) """ if not icon: icon = Path.cwd() / 'ui' / 'icons' / ICON_FILE widget.setWindowIcon(QtGui.QIcon(str(icon))) def set_font_scale(widget: QtWidgets.QWidget, size=None, scale=1.0): """Set font scale Adjust font scaling (and optionally size) for HiDPI display (e.g. macOS devices). Notes ----- This can also override the default font size to arbitrary values although the default values are good enough on non HiDPI display (e.g. Windows 7). Parameters ---------- widget : QtWidgets.QWidget size : int Set the default font size. If None, use FontSize value from TOML settings. scale : float The scale multiplier to resize the font size. """ font = QtGui.QFont() if not size: size = configurations.get_setting('UI', 'FontSize') system = platform.system() # TODO: Get access to macOS device with Retina display if system == 'Darwin': scale = 1.0 elif system == 'Linux': scale = 1.0 font.setPointSize(size * scale) widget.setFont(font) def center_screen(widget: QtWidgets.QWidget): """Center PyQt Window on screen""" resolution = QtWidgets.QDesktopWidget().screenGeometry() widget.move((resolution.width() / 2) - (widget.frameSize().width() / 2), (resolution.height() / 2) - (widget.frameSize().height() / 2)) def always_on_top(widget: QtWidgets.QWidget): """Toggle AlwaysOnTop (works in Windows and Linux)""" widget.setWindowFlags(widget.windowFlags() & ~QtCore.Qt.WindowStaysOnTopHint) checked = widget.actionAlwaysOnTop.isChecked() if checked: widget.setWindowFlags(widget.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) logger.debug('Always on Top Enabled' if checked else 'Always on Top Disabled') widget.show() def taskbar_icon(): """Workaround to show setWindowIcon on Win7 taskbar instead of default Python icon""" if platform.system() == 'Windows': app_id = u'taukeke.python.assetsbrowser' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id) def enable_hidpi(app): """Enable HiDPI support for QApplication. Parameters ---------- app : QtWidgets.QApplication """ app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) logger.info('High DPI Scaling and Pixmaps Enabled') def theme_loader(app): """Theme loader for QApplication. Parameters ---------- app : QtWidgets.QApplication """ theme = configurations.get_setting("UI", "Theme") if theme == "LIGHT": app.setStyle('Fusion') if theme == "DARK": app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) def generate_stylesheet(font=None, size=12): """Generate/update stylesheet for QApplication Handle font-family and font-size for users working with different language like Japanese, Traditional/Simplified Chinese, etc Parameters ---------- font : str or None Font name. If None, use system default font size : int Font size """ font_db = QtGui.QFontDatabase() if not font or font == 'sans-serif': font = font_db.systemFont(font_db.GeneralFont).family() elif font == 'monospace': font = font_db.systemFont(font_db.FixedFont).family() css = ( "QWidget { " f"font-family: '{font}'; " f"font-size: {size}px; " "}" ) css_path = Path(__file__).parent / 'stylesheet.css' with open(css_path, 'w') as f: f.write(css) def checked_radio(enum: Enum, radios: dict): """Checked radio button Retrieve the QRadioButton to be check Parameters ---------- enum : Enum radios : dict Dict mapping must have the following key value pairs - Key: Enum name - Value: QRadioButton """ radio = radios.get(enum.name) radio.setChecked(True)
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,669
hueyyeng/AssetsBrowser
refs/heads/develop
/helpers/enums.py
"""Helpers Enums""" from enum import Enum class FileManager(Enum): WINDOWS = 'Explorer' DARWIN = 'Finder' LINUX = 'File Manager'
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,670
hueyyeng/AssetsBrowser
refs/heads/develop
/database/mixins.py
"""Database Mixins""" from datetime import datetime import peewee as pw import pytz UTC = pytz.utc class NameDescriptionMixin(pw.Model): name = pw.CharField( null=True, max_length=50, verbose_name='Name', ) description = pw.CharField( null=True, max_length=255, verbose_name='Description', ) class DateTimeMixin(pw.Model): created_dt = pw.DateTimeField( default=datetime.now(UTC), verbose_name='Date Created', ) modified_dt = pw.DateTimeField( default=datetime.now(UTC), verbose_name='Date Modified', ) # TODO: Currently unused. Will revisit if to remain or remove class EmailPhoneMixin(pw.Model): email = pw.CharField( null=True, max_length=254, # http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690 verbose_name='Email', ) phone_number = pw.CharField( null=True, verbose_name='Phone Number', )
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,671
hueyyeng/AssetsBrowser
refs/heads/develop
/helpers/widgets.py
"""Assets Browser Custom Widgets""" import logging import platform from pathlib import Path from PyQt5 import QtCore, QtGui, QtWidgets from config.configurations import get_setting from config.constants import IMAGE_FORMAT from helpers.enums import FileManager from helpers.utils import get_file_size, open_file, reveal_in_os from ui.enums import IconRadio, PreviewRadio logger = logging.getLogger(__name__) ICON_THUMBNAILS_MODE = IconRadio(get_setting('Advanced', 'IconThumbnails')) ICON_THUMBNAILS_SIZE = QtCore.QSize(32, 32) MAX_SIZE = PreviewRadio(get_setting('Advanced', 'Preview')).size() class ColumnViewFileIcon(QtWidgets.QFileIconProvider): def icon(self, file_info: QtCore.QFileInfo): if ICON_THUMBNAILS_MODE.value == -3: return QtGui.QIcon() path = file_info.filePath() icon = super().icon(file_info) if path.lower().endswith(IMAGE_FORMAT): file_icon = QtGui.QPixmap(ICON_THUMBNAILS_SIZE) file_icon.load(path) icon = QtGui.QIcon(file_icon) return icon class ColumnViewWidget(QtWidgets.QColumnView): def __init__(self, category, project): super().__init__() default_path = Path(get_setting('Settings', 'ProjectPath')) / project / "Assets" / category logger.debug("Load... %s", default_path) self.setAlternatingRowColors(False) self.setResizeGripsVisible(True) self.setColumnWidths([200] * 9) # Column width multiply by the amount of columns self.setEnabled(True) self.fsm = QtWidgets.QFileSystemModel() self.fsm.setReadOnly(False) self.fsm.setIconProvider(ColumnViewFileIcon()) self.setModel(self.fsm) self.setRootIndex(self.fsm.setRootPath(str(default_path))) self.clicked.connect(self.get_file_info) self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.context_menu) # File Category Labels self.preview_category_name = QtWidgets.QLabel('Name:') self.preview_category_size = QtWidgets.QLabel('Size:') self.preview_category_type = QtWidgets.QLabel('Type:') self.preview_category_date = QtWidgets.QLabel('Modified:') # Align Right for Prefix Labels align_right = QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter self.preview_category_name.setAlignment(align_right) self.preview_category_size.setAlignment(align_right) self.preview_category_type.setAlignment(align_right) self.preview_category_date.setAlignment(align_right) # File Attributes Labels self.preview_file_name = QtWidgets.QLabel() self.preview_file_size = QtWidgets.QLabel() self.preview_file_type = QtWidgets.QLabel() self.preview_file_date = QtWidgets.QLabel() # File Attributes Layout and Value for Preview Pane self.sublayout_text = QtWidgets.QGridLayout() self.sublayout_text.addWidget(self.preview_category_name, 0, 0) self.sublayout_text.addWidget(self.preview_category_size, 1, 0) self.sublayout_text.addWidget(self.preview_category_type, 2, 0) self.sublayout_text.addWidget(self.preview_category_date, 3, 0) self.sublayout_text.addWidget(self.preview_file_name, 0, 1) self.sublayout_text.addWidget(self.preview_file_size, 1, 1) self.sublayout_text.addWidget(self.preview_file_type, 2, 1) self.sublayout_text.addWidget(self.preview_file_date, 3, 1) self.sublayout_text.setRowStretch(4, 1) # Arrange layout to upper part of widget # Preview Thumbnails self.preview = QtWidgets.QLabel() self.sublayout_thumbnail = QtWidgets.QVBoxLayout() self.sublayout_thumbnail.addWidget(self.preview) self.sublayout_thumbnail.setAlignment(QtCore.Qt.AlignCenter) # Set Preview Pane for QColumnView self.preview_widget = QtWidgets.QWidget() self.preview_pane = QtWidgets.QVBoxLayout(self.preview_widget) self.preview_pane.addLayout(self.sublayout_thumbnail) self.preview_pane.addLayout(self.sublayout_text) self.setPreviewWidget(self.preview_widget) # Custom context menu handling for directory or file def context_menu(self, pos): """Custom context menu. Display different set of menu actions if directory or file. Parameters ---------- pos : QtCore.QPoint """ menu = QtWidgets.QMenu() idx = self.indexAt(pos) is_selection = idx.isValid() # Only show context menu if the cursor position is over a valid item if is_selection: selected_item = self.fsm.index(idx.row(), 0, idx.parent()) file_name = str(self.fsm.fileName(selected_item)) file_name = file_name[:50] + '...' if len(file_name) > 50 else file_name file_path = str(self.fsm.filePath(selected_item)) is_dir = self.fsm.isDir(selected_item) if not is_dir: open_action = menu.addAction('Open ' + file_name) open_action.triggered.connect(lambda: open_file(file_path)) reveal_action = menu.addAction( 'Reveal in ' + getattr(FileManager, platform.system().upper()).value ) reveal_action.triggered.connect(lambda: reveal_in_os(file_path)) menu.exec_(self.mapToGlobal(pos)) self.clearSelection() # Return selected item attributes in Model View for Preview Pane def get_file_info(self, idx): """Get file info. Retrieve file information for display in Preview tab. Parameters ---------- idx : QtCore.QModelIndex QModelIndex using decorator method. Returns ------- str File path. """ selected_item = self.fsm.index(idx.row(), 0, idx.parent()) # Retrieve File Attributes file_name = self.fsm.fileName(selected_item) file_size = self.fsm.size(selected_item) file_type = self.fsm.type(selected_item).split(' ')[0] file_date = self.fsm.lastModified(selected_item) file_path = self.fsm.filePath(selected_item) # Assign the File Attributes' string into respective labels self.preview_file_name.setText(file_name) self.preview_file_size.setText(get_file_size(file_size)) self.preview_file_type.setText(file_type.upper() + ' file') self.preview_file_date.setText(file_date.toString('yyyy/MM/dd h:m AP')) # Retrieve image path for Thumbnail Preview image_path = self.fsm.filePath(selected_item) # Generate thumbnails for Preview Pane if image_path.lower().endswith(IMAGE_FORMAT): image = QtGui.QImageReader() image.setFileName(image_path) scaled_size = image.size() scaled_size.scale(MAX_SIZE, MAX_SIZE, QtCore.Qt.KeepAspectRatio) image.setScaledSize(scaled_size) thumbnail = QtGui.QPixmap.fromImage(image.read()) else: file_info = QtCore.QFileInfo(image_path) # Retrieve info like icons, path, etc file_icon = QtWidgets.QFileIconProvider().icon(file_info) thumbnail = file_icon.pixmap(48, 48, QtGui.QIcon.Normal, QtGui.QIcon.Off) self.preview.setPixmap(thumbnail) return file_path
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,672
hueyyeng/AssetsBrowser
refs/heads/develop
/config/constants.py
"""Configurations Constants""" import os CONFIG_DIR = os.path.abspath(os.path.dirname(__file__)) TOML_FILE = 'settings.toml' TOML_PATH = os.path.join(CONFIG_DIR, TOML_FILE) ICON_FILE = 'file.png' IMAGE_FORMAT = ( '.jpg', '.jpeg', '.bmp', '.png', '.gif', '.bmp', '.ico', '.tga', '.tif', '.tiff', ) DEFAULT_CATEGORY = ( 'BG', 'CH', 'FX', 'Props', 'Vehicles', ) DEFAULT_SUBFOLDER = ( 'References', 'Scenes', 'Textures', 'WIP', ) DEFAULT_METADATA = ( 'Author', 'Category', 'Date Created', 'Date Modified', 'Description', 'Format', 'Name', 'Project', 'Version', )
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,673
hueyyeng/AssetsBrowser
refs/heads/develop
/config/utils.py
import logging import os from config.configurations import create_config from config.constants import DEFAULT_CATEGORY, DEFAULT_SUBFOLDER logger = logging.getLogger(__name__) def check_config_file(path: str): """Check for TOML config file If doesn't exists, create one with default value. Parameters ---------- path : str Path to TOML config file """ if os.path.exists(path): return logger.info("TOML config file not found. Creating new TOML config file at %s", path) create_config(path) def create_project_structure_dirs(project=None): """Create sample project structure directories Parameters ---------- project : str or None Project name. If None, default to Project Notes ----- Project Category 1 Subfolder 1 Subfolder 2 Category 2 Subfolder 1 Subfolder 2 """ home = os.path.expanduser('~') # Defaults to home directory if not project: project = "Project" for category in DEFAULT_CATEGORY: for subfolder in DEFAULT_SUBFOLDER: path = os.path.join(home, project, category, subfolder) os.makedirs(path) logger.info("%s directory created", path)
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,674
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/window/ui_asset_item.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'K:\Library\Python\AssetsBrowser\ui\window\asset_item.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_AssetItemDialog(object): def setupUi(self, AssetItemDialog): AssetItemDialog.setObjectName("AssetItemDialog") AssetItemDialog.resize(310, 360) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(AssetItemDialog.sizePolicy().hasHeightForWidth()) AssetItemDialog.setSizePolicy(sizePolicy) AssetItemDialog.setMinimumSize(QtCore.QSize(310, 360)) AssetItemDialog.setMaximumSize(QtCore.QSize(310, 360)) AssetItemDialog.setFocusPolicy(QtCore.Qt.StrongFocus) AssetItemDialog.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.verticalLayout = QtWidgets.QVBoxLayout(AssetItemDialog) self.verticalLayout.setObjectName("verticalLayout") self.assetLayout = QtWidgets.QHBoxLayout() self.assetLayout.setObjectName("assetLayout") self.assetLabel = QtWidgets.QLabel(AssetItemDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.assetLabel.sizePolicy().hasHeightForWidth()) self.assetLabel.setSizePolicy(sizePolicy) self.assetLabel.setMinimumSize(QtCore.QSize(60, 0)) self.assetLabel.setObjectName("assetLabel") self.assetLayout.addWidget(self.assetLabel) self.assetComboBox = QtWidgets.QComboBox(AssetItemDialog) self.assetComboBox.setObjectName("assetComboBox") self.assetLayout.addWidget(self.assetComboBox) self.verticalLayout.addLayout(self.assetLayout) self.formatLayout = QtWidgets.QHBoxLayout() self.formatLayout.setObjectName("formatLayout") self.formatLabel = QtWidgets.QLabel(AssetItemDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.formatLabel.sizePolicy().hasHeightForWidth()) self.formatLabel.setSizePolicy(sizePolicy) self.formatLabel.setMinimumSize(QtCore.QSize(60, 0)) self.formatLabel.setObjectName("formatLabel") self.formatLayout.addWidget(self.formatLabel) self.formatComboBox = QtWidgets.QComboBox(AssetItemDialog) self.formatComboBox.setObjectName("formatComboBox") self.formatLayout.addWidget(self.formatComboBox) self.verticalLayout.addLayout(self.formatLayout) self.checkboxCopyIncrement = QtWidgets.QCheckBox(AssetItemDialog) self.checkboxCopyIncrement.setEnabled(False) self.checkboxCopyIncrement.setObjectName("checkboxCopyIncrement") self.verticalLayout.addWidget(self.checkboxCopyIncrement) self.shortNameVersionLayout = QtWidgets.QHBoxLayout() self.shortNameVersionLayout.setObjectName("shortNameVersionLayout") self.shortNameLayout = QtWidgets.QHBoxLayout() self.shortNameLayout.setObjectName("shortNameLayout") self.shortNameLabel = QtWidgets.QLabel(AssetItemDialog) self.shortNameLabel.setMinimumSize(QtCore.QSize(60, 0)) self.shortNameLabel.setObjectName("shortNameLabel") self.shortNameLayout.addWidget(self.shortNameLabel) self.shortNameLineEdit = QtWidgets.QLineEdit(AssetItemDialog) self.shortNameLineEdit.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.shortNameLineEdit.sizePolicy().hasHeightForWidth()) self.shortNameLineEdit.setSizePolicy(sizePolicy) self.shortNameLineEdit.setMinimumSize(QtCore.QSize(0, 0)) self.shortNameLineEdit.setMaximumSize(QtCore.QSize(300, 16777215)) self.shortNameLineEdit.setMaxLength(3) self.shortNameLineEdit.setObjectName("shortNameLineEdit") self.shortNameLayout.addWidget(self.shortNameLineEdit) self.shortNameVersionLayout.addLayout(self.shortNameLayout) self.versionLayout = QtWidgets.QHBoxLayout() self.versionLayout.setObjectName("versionLayout") self.versionLabel = QtWidgets.QLabel(AssetItemDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.versionLabel.sizePolicy().hasHeightForWidth()) self.versionLabel.setSizePolicy(sizePolicy) self.versionLabel.setMinimumSize(QtCore.QSize(0, 0)) self.versionLabel.setObjectName("versionLabel") self.versionLayout.addWidget(self.versionLabel) self.versionSpinBox = QtWidgets.QSpinBox(AssetItemDialog) self.versionSpinBox.setEnabled(False) self.versionSpinBox.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.versionSpinBox.setButtonSymbols(QtWidgets.QAbstractSpinBox.UpDownArrows) self.versionSpinBox.setProperty("value", 1) self.versionSpinBox.setObjectName("versionSpinBox") self.versionLayout.addWidget(self.versionSpinBox) self.shortNameVersionLayout.addLayout(self.versionLayout) self.verticalLayout.addLayout(self.shortNameVersionLayout) self.nameLayout = QtWidgets.QHBoxLayout() self.nameLayout.setObjectName("nameLayout") self.nameLabel = QtWidgets.QLabel(AssetItemDialog) self.nameLabel.setMinimumSize(QtCore.QSize(60, 0)) self.nameLabel.setObjectName("nameLabel") self.nameLayout.addWidget(self.nameLabel) self.nameLineEdit = QtWidgets.QLineEdit(AssetItemDialog) self.nameLineEdit.setEnabled(False) self.nameLineEdit.setPlaceholderText("") self.nameLineEdit.setObjectName("nameLineEdit") self.nameLayout.addWidget(self.nameLineEdit) self.verticalLayout.addLayout(self.nameLayout) self.descLayout = QtWidgets.QHBoxLayout() self.descLayout.setObjectName("descLayout") self.descLabel = QtWidgets.QLabel(AssetItemDialog) self.descLabel.setEnabled(True) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.descLabel.sizePolicy().hasHeightForWidth()) self.descLabel.setSizePolicy(sizePolicy) self.descLabel.setMinimumSize(QtCore.QSize(60, 0)) self.descLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.descLabel.setObjectName("descLabel") self.descLayout.addWidget(self.descLabel) self.descTextEdit = QtWidgets.QPlainTextEdit(AssetItemDialog) self.descTextEdit.setEnabled(True) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.descTextEdit.sizePolicy().hasHeightForWidth()) self.descTextEdit.setSizePolicy(sizePolicy) self.descTextEdit.setMaximumSize(QtCore.QSize(16777215, 125)) self.descTextEdit.setObjectName("descTextEdit") self.descLayout.addWidget(self.descTextEdit) self.verticalLayout.addLayout(self.descLayout) self.infoLabel = QtWidgets.QLabel(AssetItemDialog) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.infoLabel.sizePolicy().hasHeightForWidth()) self.infoLabel.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.infoLabel.setFont(font) self.infoLabel.setTextFormat(QtCore.Qt.PlainText) self.infoLabel.setAlignment(QtCore.Qt.AlignCenter) self.infoLabel.setObjectName("infoLabel") self.verticalLayout.addWidget(self.infoLabel) self.layoutCreateCancel = QtWidgets.QHBoxLayout() self.layoutCreateCancel.setObjectName("layoutCreateCancel") self.btnCreate = QtWidgets.QPushButton(AssetItemDialog) self.btnCreate.setEnabled(False) self.btnCreate.setObjectName("btnCreate") self.layoutCreateCancel.addWidget(self.btnCreate) self.btnCancel = QtWidgets.QPushButton(AssetItemDialog) self.btnCancel.setObjectName("btnCancel") self.layoutCreateCancel.addWidget(self.btnCancel) self.verticalLayout.addLayout(self.layoutCreateCancel) self.retranslateUi(AssetItemDialog) QtCore.QMetaObject.connectSlotsByName(AssetItemDialog) def retranslateUi(self, AssetItemDialog): _translate = QtCore.QCoreApplication.translate AssetItemDialog.setWindowTitle(_translate("AssetItemDialog", "Create New Asset Item")) self.assetLabel.setText(_translate("AssetItemDialog", "Asset")) self.formatLabel.setText(_translate("AssetItemDialog", "Format")) self.checkboxCopyIncrement.setText(_translate("AssetItemDialog", "Copy and increment existing Asset Item")) self.shortNameLabel.setText(_translate("AssetItemDialog", "Shortname")) self.shortNameLineEdit.setToolTip(_translate("AssetItemDialog", "Alphanumeric only")) self.versionLabel.setText(_translate("AssetItemDialog", "Version")) self.nameLabel.setText(_translate("AssetItemDialog", "Full Name")) self.descLabel.setText(_translate("AssetItemDialog", "Description")) self.descTextEdit.setPlaceholderText(_translate("AssetItemDialog", "Optional. Max chars 255.")) self.infoLabel.setText(_translate("AssetItemDialog", "Placeholder")) self.btnCreate.setText(_translate("AssetItemDialog", "Create")) self.btnCancel.setText(_translate("AssetItemDialog", "Cancel"))
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,675
hueyyeng/AssetsBrowser
refs/heads/develop
/database/validators.py
"""Database Field Validators""" import re from voluptuous import Email, Schema, Url # pylint: disable=no-value-for-parameter class ModelValidator: def validate_url(self, value): schema = Schema(Url()) schema(value) def validate_email(self, value): schema = Schema(Email()) schema(value) def validate_username(self, value): if value is None: return if re.match(r'^(?![-._])(?!.*[_.-]{2})[\w.-]{6,30}(?<![-._])$', value): return value.lower() raise Exception("Username may only contain alphanumeric, underscore(_), hyphen(-) and period(.)") def validate_phone_number(self, value): if value is None: return if re.match("^[0-9-+ ]+$", value): return raise Exception("Phone number may only contain plus(+), hyphen(-) and digits only")
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,676
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/dialog/asset_item.py
"""Asset Item Dialog""" import logging import sys from PyQt5 import QtWidgets import ui.functions from config import configurations from database.db import Database from helpers.functions import ham from ui.window.ui_asset_item import ( Ui_AssetItemDialog, ) logger = logging.getLogger(__name__) class AssetItemDialog(QtWidgets.QDialog, Ui_AssetItemDialog): def __init__(self, parent=None): super(AssetItemDialog, self).__init__(parent) self.setupUi(self) self.db = Database(use_default_db=True) ui.functions.set_window_icon(self) self._setup_ui_buttons() self._setup_asset_combobox() self._setup_format_combobox() def _setup_asset_combobox(self): """Setup Asset combobox""" asset_categories = configurations.get_setting('Assets', 'CategoryList') for asset_category in asset_categories: self.assetComboBox.addItem(asset_category) def _setup_format_combobox(self): """Setup Asset Format combobox""" asset_categories = configurations.get_setting('Assets', 'CategoryList') for asset_category in asset_categories: self.formatComboBox.addItem(asset_category) def _setup_ui_buttons(self): self.btnCreate.setDisabled(True) self.btnCreate.clicked.connect(ham) self.btnCancel.clicked.connect(self.close) def show_dialog(): dialog = AssetItemDialog() if dialog.exec_(): logger.debug('Creating new asset item...') else: logger.debug('Aborting Create New Asset Item...') if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = AssetItemDialog() window.show() sys.exit(app.exec_())
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,677
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/enums.py
"""UI Enums""" from enum import Enum from config.configurations import get_setting class PreviewRadio(Enum): SMALL = -2 BIG = -3 CUSTOM = -4 def size(self): # https://github.com/PyCQA/pylint/issues/2306#issuecomment-524554162 value = int(self.value) if value == -2: return 150 if value == -3: return 300 if value == -4: return get_setting('Advanced', 'PreviewCustomMaxSize') class IconRadio(Enum): ENABLE = -2 DISABLE = -3 GENERIC = -4 class ThemeRadio(Enum): LIGHT = -2 DARK = -3 class SeparatorCombo(Enum): UNDERSCORE = 0 DASH = 1 class PrefixRadio(Enum): FIRST = -2 WHOLE = -3 class SuffixRadio(Enum): VERSION = -2 CUSTOM = -3 class FontRadio(Enum): DEFAULT = -2 MONOSPACE = -3 CUSTOM = -4 def font(self): value = int(self.value) if value == -2: return 'sans-serif' if value == -3: return 'monospace' class FontSize(Enum): DEFAULT = 12 TINY = 10 LARGE = 16
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,094,678
hueyyeng/AssetsBrowser
refs/heads/develop
/ui/dialog/asset.py
"""Asset Dialog""" import logging import os import sys from PyQt5 import QtCore, QtGui, QtWidgets import ui.functions from config import configurations from database.db import Database from database.models import Asset as AssetModel from database.models import Category, Project from helpers.utils import alert_window from ui.window.ui_asset import Ui_AssetDialog logger = logging.getLogger(__name__) class AssetDialog(QtWidgets.QDialog, Ui_AssetDialog): def __init__(self, parent=None): super(AssetDialog, self).__init__(parent) self.setupUi(self) self.db = Database(use_default_db=True) ui.functions.set_window_icon(self) self._setup_ui_buttons() self._setup_asset_name_validator() self._setup_category_combobox() self._append_max_chars_suffix() def _append_max_chars_suffix(self): """Append Max Chars to Asset's Name label""" max_chars = configurations.get_setting('Assets', 'MaxChars') label = self.shortNameLabel.text() self.shortNameLabel.setText(f"{label} (Max chars: {max_chars})") def _setup_category_combobox(self): """Setup Category combobox""" asset_categories = configurations.get_setting('Assets', 'CategoryList') for asset_category in asset_categories: self.categoryComboBox.addItem(asset_category) def _setup_asset_name_validator(self): """Setup Asset name validator""" # Limit the range of acceptable characters input by the user using regex regex = QtCore.QRegularExpression("^[a-zA-Z0-9]+$") validator = QtGui.QRegularExpressionValidator(regex, self) self.shortNameLineEdit.setValidator(validator) # Runs text_uppercase and preview whenever Qt detects textChanged self.shortNameLineEdit.textChanged.connect(self.text_uppercase) self.shortNameLineEdit.textChanged.connect(self.preview_asset_name) def _setup_ui_buttons(self): self.btnCreate.setDisabled(True) self.btnCreate.clicked.connect(self.create_asset) self.btnCancel.clicked.connect(self.close) self.previewGroup.clicked.connect(self.preview_asset_name) def text_uppercase(self): """Convert text to UPPERCASE.""" asset_name = self.shortNameLineEdit.text() self.shortNameLineEdit.setText(asset_name.upper()) def create_asset(self): """Create asset with preconfigure directories structure.""" current_project = configurations.get_setting('Settings', 'CurrentProject') project_path = configurations.get_setting('Settings', 'ProjectPath') asset_category = self.catBtnGroup.checkedButton().text() asset_format = self.formatComboBox.currentText() asset_path = os.path.join(project_path, current_project, "Assets", asset_category) asset_full_name = self.nameLineEdit.text() asset_short_name = self.generate_asset_name() full_path = os.path.join(asset_path, asset_short_name) # Create Asset directory try: os.mkdir(full_path) except OSError: alert_window('Warning', 'ERROR! Asset already exists!') logger.debug('Assets will be created at %s', full_path) # Create Asset's subfolders folders = configurations.get_setting('Assets', 'SubfolderList') logger.debug(folders) for folder in folders: try: os.mkdir(os.path.join(full_path, folder)) except OSError: logger.error("The Assets directory %s cannot be created.", full_path) # Retrieve category and project id. If not exists, create the category and project in DB category, _ = Category.get_or_create(name=asset_category) project, _ = Project.get_or_create(short_name=current_project) # Create Asset entry in DB asset_data = { "category": category.id, "project": project.id, "format": asset_format, "name": asset_full_name, "short_name": asset_short_name, } AssetModel.create(**asset_data) logger.info({ "msg": "Asset creation successful", "short_name": asset_short_name, "project": project, }) self.accept() def generate_asset_name(self): """Generate asset's name with category prefix. Use input from `shortNameLineEdit` to generate asset's name with Returns ------- str Asset's name with category prefix """ category = self.categoryComboBox.currentText() prefix = category[0].lower() suffix = self.shortNameLineEdit.text() asset_name = f"{prefix}{suffix}" return asset_name def preview_asset_name(self): """Preview asset's name in non-editable text field. Notes ----- Since both `catBtnGroup` and `shortNameLineEdit` emits signal to this method, it allows the text field to "dynamically" update. """ # 1. Disable Create button and clear the text field to create "illusion" of dynamic update self.previewText.clear() self.btnCreate.setDisabled(True) # 2.1 Generate preview message name_length = len(self.shortNameLineEdit.text()) checked = self.previewGroup.isChecked() asset_name = self.generate_asset_name() # 2.2 Enable Create button and display the expected asset name message = "Ensure asset's name is three characters length!" if checked and name_length == 3: self.btnCreate.setDisabled(False) project = configurations.get_setting('Settings', 'CurrentProject') message = f"The asset name will be {asset_name}.\n" \ f"Ensure the asset name is correct before proceeding.\n" \ f"\n" \ f"Project: {project}" self.previewText.appendPlainText(message) def show_dialog(): dialog = AssetDialog() if dialog.exec_(): logger.debug('Creating new asset...') else: logger.debug('Aborting Create New Asset...') if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = AssetDialog() window.show() sys.exit(app.exec_())
{"/modules/functions.py": ["/modules/utils.py"], "/assetsbrowser.py": ["/ui/help/__init__.py", "/helpers/functions.py", "/helpers/utils.py", "/ui/functions.py", "/config/constants.py", "/config/utils.py", "/helpers/exceptions.py", "/helpers/widgets.py"], "/config/constants.py": ["/config/configurations.py"], "/tests/test_create_config.py": ["/config/configurations.py"], "/ui/dialog/preferences.py": ["/ui/window/ui_preferences.py", "/helpers/functions.py", "/ui/functions.py", "/ui/enums.py"], "/ui/dialog/asset.py": ["/ui/window/ui_asset.py", "/ui/functions.py", "/database/db.py", "/database/models.py", "/helpers/utils.py"], "/ui/dialog/about.py": ["/modules/functions.py", "/ui/window/ui_about.py", "/ui/functions.py"], "/tests/database/test_assets.py": ["/database/db.py", "/database/models.py"], "/database/constants.py": ["/database/models.py"], "/tests/database/test_categories.py": ["/database/db.py", "/database/models.py"], "/tests/database/test_db_schema.py": ["/database/models.py", "/database/constants.py", "/database/db.py"], "/tests/database/test_db.py": ["/database/db.py", "/database/models.py"], "/tests/config/test_config.py": ["/config/configurations.py", "/config/exceptions.py"], "/database/models.py": ["/database/mixins.py", "/database/validators.py"], "/ui/dialog/asset_item_format.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item_format.py"], "/config/configurations.py": ["/config/constants.py", "/config/exceptions.py"], "/helpers/utils.py": ["/config/constants.py", "/helpers/exceptions.py"], "/database/db.py": ["/database/constants.py", "/database/models.py"], "/ui/dialog/applications_list.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py"], "/tests/database/test_projects.py": ["/database/models.py", "/database/db.py"], "/ui/functions.py": ["/config/constants.py"], "/helpers/widgets.py": ["/config/configurations.py", "/config/constants.py", "/helpers/enums.py", "/helpers/utils.py", "/ui/enums.py"], "/config/utils.py": ["/config/configurations.py", "/config/constants.py"], "/ui/dialog/asset_item.py": ["/ui/functions.py", "/database/db.py", "/helpers/functions.py", "/ui/window/ui_asset_item.py"], "/ui/enums.py": ["/config/configurations.py"]}
22,156,707
aapatrick/CT_Extinct
refs/heads/main
/chatbot/chat.py
import random import json import numpy as np import pickle import nltk from nltk.stem import WordNetLemmatizer from tensorflow.keras.models import load_model lemmatizer = WordNetLemmatizer() intentsDictionary = json.loads(open("intents.json").read()) wordList = pickle.load(open("wordList.pk1", "rb")) # read binary tagList = pickle.load(open("tagList.pk1", "rb")) model = load_model("chatbot.h5") # this function tokenizes each word in the sentence and lemmatizes it. def cleanup_sentence(sentence): sentence_words = nltk.word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(eachWord) for eachWord in sentence_words] return sentence_words # convert a sentence into Bag of Words. A list of 0s or 1s to indicate if a word is there or not. def bag_of_words(sentence): sentence_words = cleanup_sentence(sentence) bag = [0] * len(wordList) for x in sentence_words: for i, thisWord in enumerate(wordList): if thisWord == x: bag[i] = 1 return np.array(bag) # for predicting the tag based on the sentence inputted def predict_tag(sentence): bag_of_w = bag_of_words(sentence) # this will be inputted into the neural network result_tag = model.predict(np.array([bag_of_w]))[0] # 0 added to match the format ERROR_THRESHOLD = 0.25 percentage_res = [[i, r] for i, r in enumerate(result_tag) if r > ERROR_THRESHOLD] percentage_res.sort(key=lambda x: x[1], reverse=True) return_list = [] for r in percentage_res: return_list.append({"intent": tagList[r[0]], "probability": str(r[1])}) return return_list # for giving a response def get_response(intents_list, intents_json): tag = intents_list[0]["intent"] list_of_intents = intents_json["intents"] for i in list_of_intents: if i["tag"] == tag: result_response = random.choice(i["responses"]) break return result_response
{"/ctextinct/__main__.py": ["/ctextinct/controller.py"]}
22,156,708
aapatrick/CT_Extinct
refs/heads/main
/chatbot_model.model/janine.py
import random import json import numpy as np import pickle import nltk from nltk.stem import WordNetLemmatizer from tensorflow.keras.models import load_model lemmatizer = WordNetLemmatizer() intentsDictionary = json.loads(open("intents.json").read()) wordList = pickle.load(open("wordList.pk1", "rb")) # read binary tagList = pickle.load(open("tagList.pk1", "rb")) model = load_model("chatbot.h5") # this function tokenizes each word in the sentence and lemmatizes it. def cleanUpSentence(sentence): sentenceWords = nltk.word_tokenize(sentence) sentenceWords = [lemmatizer.lemmatize(eachWord) for eachWord in sentenceWords] return sentenceWords # convert a sentence into Bag of Words. A list of 0s or 1s to indicate if a word is there or not. def bagOfWords(sentence): sentenceWords = cleanUpSentence(sentence) bag = [0] * len(wordList) for x in sentenceWords: for i, thisWord in enumerate(wordList): if thisWord == x: bag[i] = 1 return np.array(bag)
{"/ctextinct/__main__.py": ["/ctextinct/controller.py"]}
22,156,709
aapatrick/CT_Extinct
refs/heads/main
/chatbot/app.py
from chat import * import tkinter as tk # if __name__ == "__main__": def next_question(response): print("error 1") entry.delete(0, tk.END) print("error 2") responseL.configure(text=response) print("error 3") def ask_question(Event): print("firstaskquestion") user_q = entry.get() print("firstaskquestion2") ints = predict_tag(user_q) print("firstaskquestion3") response = get_response(ints, intentsDictionary) print("firstaskquestion4") next_question(response) # tkinter GUI root = tk.Tk() entry = tk.Entry( fg="yellow", bg="green", width=50 ) responseL = tk.Label( text="Janine just joined the chat! What would you like to ask her?", fg="yellow", bg="green", ) root.bind('<Return>', ask_question) entry.pack() responseL.pack() root.mainloop()
{"/ctextinct/__main__.py": ["/ctextinct/controller.py"]}
22,156,710
aapatrick/CT_Extinct
refs/heads/main
/janine.py
import random import json import numpy as np import pickle import nltk from nltk.stem import WordNetLemmatizer from tensorflow.keras.models import load_model lemmatizer = WordNetLemmatizer() intentsDictionary = json.loads(open("intents.json").read()) wordList = pickle.load(open("wordList.pk1", "rb")) # read binary tagList = pickle.load(open("tagList.pk1", "rb")) model = load_model("chatbot.h5") # this function tokenizes each word in the sentence and lemmatizes it. def cleanUpSentence(sentence): sentenceWords = nltk.word_tokenize(sentence) sentenceWords = [lemmatizer.lemmatize(eachWord) for eachWord in sentenceWords] return sentenceWords # convert a sentence into Bag of Words. A list of 0s or 1s to indicate if a word is there or not. def bagOfWords(sentence): sentenceWords = cleanUpSentence(sentence) bag = [0] * len(wordList) for x in sentenceWords: for i, thisWord in enumerate(wordList): if thisWord == x: bag[i] = 1 return np.array(bag) # for predicting the tag based on the sentence inputted def predictTag(sentence): bagOfw = bagOfWords(sentence) # this will be inputted into the neural network result = model.predict(np.array([bagOfw]))[0] # 0 added to match the format ERROR_THRESHOLD = 0.25 percentageRes = [[i, r] for i, r in enumerate(result) if r > ERROR_THRESHOLD] percentageRes.sort(key=lambda x: x[1], reverse=True) returnList = [] for r in percentageRes: returnList.append({"intent": tagList[r[0]], "probability": str(r[1])}) return returnList # for giving a response def getResponse(intentsList, intentsJson): tag = intentsList[0]["intent"] listOfIntents = intentsJson["intents"] for i in listOfIntents: if i["tag"] == tag: result = random.choice(i["responses"]) break return result print("Janine just joined the chat! What would you like to ask her?") while True: message = input("") ints = predictTag(message) response = getResponse(ints, intentsDictionary) print(response)
{"/ctextinct/__main__.py": ["/ctextinct/controller.py"]}
22,156,711
aapatrick/CT_Extinct
refs/heads/main
/chatbot/database.py
import firebase_admin cred_obj = firebase_admin.credentials.Certificate( r"C:\Users\MrLaziz\Desktop\Kingston University Level 6\Individual " r"Project\CT_Extinct\chatbot\ctextinct-firebase-adminsdk-xnpem-e13f73b9d2.json") default_app = firebase_admin.initialize_app(cred_obj, { 'databaseURL': "https://ctextinct-default-rtdb.europe-west1.firebasedatabase.app/" }) # WRITE DATA ref = db.reference("/") ref.set({ "News": { "Article": -1 } }) ref = db.reference("/News/Article") import json with open(r"C:\Users\MrLaziz\Desktop\Kingston University Level 6\Individual Project\CT_Extinct\chatbot\news.json", "r") as f: file_contents = json.load(f) for key, value in file_contents.items(): ref.push().set(value) # UPDATE DATA # ref = db.reference("/Books/Best_Sellers/") # best_sellers = ref.get() # print(best_sellers) # for key, value in best_sellers.items(): # if(value["Author"] == "J.R.R. Tolkien"): # value["Price"] = 90 # ref.child(key).update({"Price":80}) # RETRIEVE DATA # ref = db.reference("/Books/Best_Sellers/") # print(ref.order_by_child("Price").get()) # ref.order_by_child("Price").limit_to_last(1).get() # ref.order_by_child("Price").limit_to_first(1).get() # ref.order_by_child("Price").equal_to(80).get() # DELETE DATA # ref = db.reference("/Books/Best_Sellers") # for key, value in best_sellers.items(): # if(value["Author"] == "J.R.R. Tolkien"): # ref.child(key).set({})
{"/ctextinct/__main__.py": ["/ctextinct/controller.py"]}
22,156,712
aapatrick/CT_Extinct
refs/heads/main
/chatbot/training.py
import random # required for choosing a random response import json import pickle # Python object serialization import numpy as np import nltk # natural language tool kit from nltk.stem import WordNetLemmatizer from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.optimizers import SGD import tensorflow as tf physical_devices = tf.config.list_physical_devices('CPU') # tf.config.experimental.set_memory_growth(physical_devices[0], True) # used when training using CUDA and NVIDIA # Graphics card. # SGD stands for Stochastic gradient descent lemmatizer = WordNetLemmatizer() # calling the wordNetLemmatizer constructor # the lemmatizer will reduce the word to its stem. For example, work, working, worked, works is all the same stem # word as "work". Wordnet is an large, freely and publicly available lexical database for the English language aiming # to establish structured semantic relationships between words. intentsDictionary = json.loads(open("intents.json").read()) # created 3 empty lists and the letters this program will ignore wordList = [] tagList = [] documentList = [] # this list will be used for the linked tokenized words and tags ignoredCharList = ["?", "!", ",", "."] # I am iterating over the intents for intent in intentsDictionary["intents"]: # for each of the patterns, the below will tokenize the sentences. Meaning the sentences will split into words. for pattern in intent["patterns"]: listOfWords = nltk.word_tokenize(pattern) wordList.extend(listOfWords) documentList.append((listOfWords, intent["tag"])) # for each tag discovered, if not added to the classes list yet, it becomes added. if intent["tag"] not in tagList: tagList.append(intent["tag"]) print(documentList) # testing purposes # replacing the contents of wordList with a lemmatized version excluding the "ignore_letters" wordList = [lemmatizer.lemmatize(eachWord) for eachWord in wordList if eachWord not in ignoredCharList] # to eliminate the duplicates and sort the list wordList = sorted(set(wordList)) tagList = sorted(set(tagList)) print(wordList) # testing purposes print(tagList) # testing purposes # Next, I am saving the data into files. Pickling is a way to convert a python object (list, dict, etc.) into a # character stream. The idea is that this character stream contains all the information necessary to reconstruct the # object in another python script. pickle.dump(wordList, open("wordList.pk1", "wb")) # write binary pickle.dump(tagList, open("tagList.pk1", "wb")) # The above organised data is not yet numerical, which is what we need for a machine learning algorithm. # The below code assigns 0 or 1 to each of the words depending on training = [] outputEmpty = [0] * len(tagList) # as many 0 as there are classes # turning our data into Matrices, (harder than image data (because RGB uses numbers)) for document in documentList: bag = [] # bag of words model used here--- the inputs of 1s & 0s into the machine learning algorithm wordPatterns = document[0] # each document is a list of (pattern and related tag) wordPatterns = [lemmatizer.lemmatize(eachWord.lower()) for eachWord in wordPatterns] # if a word in wordlist is equal to word in wordPatterns than add 1 to bag, if not add 0. for eachWord in wordList: bag.append(1) if eachWord in wordPatterns else bag.append(0) outputRow = list(outputEmpty) # copying outputEmpty into OutputRow. outputRow[tagList.index(document[1])] = 1 # The output row is the "Prediction" of the related tag training.append([bag, outputRow]) # example: bag(10100010101000000000100001001000) outputRow(000010000) how many # words relate to a certain tag # preprocessing the data random.shuffle(training) training = np.array(training) # converting to numpy array trainX = list(training[:, 0]) # features that we wil use trainY = list(training[:, 1]) # labels that we will use to train # Start of building Neural Network model model = Sequential() model.add(Dense(128, input_shape=(len(trainX[0]),), activation="relu")) model.add(Dropout(0.5)) model.add(Dense(64, activation="relu")) model.add(Dropout(0.5)) model.add(Dense(len(trainY[0]), activation="softmax")) # sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"]) hist = model.fit(np.array(trainX), np.array(trainY), epochs=200, batch_size=5, verbose=1) model.save("chatbot.h5", hist) print("Done")
{"/ctextinct/__main__.py": ["/ctextinct/controller.py"]}
22,160,790
Rishabhc711/Document-Scanner
refs/heads/main
/cv2test.py
from cv2 import cv2 import numpy as np #import utlis ######################################################################## webCamFeed = True pathImage = "DOCSCANNER\\Images\\20210114_230355.jpg" cap = cv2.VideoCapture(0) cap.set(10,160) heightImg = 640 widthImg = 480 ######################################################################## #utlis.initializeTrackbars() count=0 def nothing(x=0): pass #cv2.imshow("Canny Image",ImageCanny) cv2.namedWindow("Threshold Parameters") cv2.resizeWindow("Threshold Parameters",400,600) cv2.createTrackbar("Threshold1","Threshold Parameters",60,255,nothing) cv2.createTrackbar("Threshold2","Threshold Parameters",60,255,nothing) def getBiggestcontour(contours): #contours, hierarchy=cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) #cv2.drawContours(imgcontour,contours, -1,"red",5) for contour in contours: area=cv2.contourArea(contour) if area > 2000: peri=cv2.arcLength(contour,True) shape=cv2.approxPolyDP(contour,0.02*peri,True) #print(len(shape)) if(len(shape)==4): print(len(shape)) #cv2.drawContours(imgcontour,contours, -1,(255, 255,0),5) cv2.drawContours(imgcontour,contour, -1,"blue",5) return imgcontour while True: #if webCamFeed:success, img = cap.read() #else: img = cv2.imread(pathImage) img = cv2.resize(img, (widthImg, heightImg)) # RESIZE IMAGE imgBlank = np.zeros((heightImg,widthImg, 3), np.uint8) # CREATE A BLANK IMAGE FOR TESTING DEBUGING IF REQUIRED imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # CONVERT IMAGE TO GRAY SCALE imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 1) ''' cv2.imshow("Image1",img) cv2.imshow("BLank Image",imgBlank) cv2.imshow("Blurred Image",imgBlur) cv2.waitKey() ''' #cv2.destroyAllWindows() # ADD GAUSSIAN BLUR #thres=utlis.valTrackbars() # GET TRACK BAR VALUES FOR THRESHOLDS #imgThreshold = cv2.Canny(imgBlur,thres[0],thres[1]) # APPLY CANNY BLUR th1=cv2.getTrackbarPos("Threshold1","Threshold Parameters") th2=cv2.getTrackbarPos("Threshold2","Threshold Parameters") ImageCanny=cv2.Canny(imgBlur,th1,th2) cv2.imshow("Canny Image",ImageCanny) cv2.waitKey(0) print('hi') kernel = np.ones((5, 5)) imgDial = cv2.dilate(ImageCanny, kernel, iterations=2) # APPLY DILATION imgThreshold = cv2.erode(imgDial, kernel, iterations=1) # APPLY EROSION ''' cv2.imshow("Dilated",imgDial) cv2.imshow("Eroded",imgThreshold) cv2.waitKey() ''' imgcontour=img.copy() #imgcontour=getcontours(ImageCanny,imgcontour) contours, hierarchy =cv2.findContours(imgThreshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) #cv2.drawContours(imgcontour,contours, -1,(0, 255, 0), 20) #cv2.imshow("Threshold image", imgcontour) # contour is also destructive #img = cv2.cvtColor(imgcontour, cv2.COLOR_GRAY2BGR) #add this line cv2.drawContours(imgcontour, contours, -1, (0,255,0), 10) # I am expecting the contour lines to be green cv2.imshow("Contour Image With colours", imgcontour) cv2.waitKey(0) img_with_corners=img.copy() corners = cv2.goodFeaturesToTrack(imgBlur, 150, 0.2, 50) corners = np.int0(corners) for corner in corners: x, y = corner.ravel() cv2.circle(img_with_corners, (x, y), 5, (200, 0, 255), -1) cv2.imshow("Image With corners", img_with_corners) if cv2.waitKey(0) & 0xFF == ord('s'): break ''' cv2.imshow(imgBlank) cv2.imshow(imgBlur) cv2.imshow(imgDial) cv2.imshow(imgThreshold) ''' print(cv2.__version__) print('hi') cv2.destroyAllWindows()
{"/main.py": ["/utilities.py"]}
22,160,791
Rishabhc711/Document-Scanner
refs/heads/main
/alignment.py
import cv2 import numpy as np img1= cv2.imread('richdadpoordad.jpg', cv2.IMREAD_GRAYSCALE) img2= cv2.imread('mewithbook.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow("Image1",img1) cv2.imshow("Image2",img2) cv2.waitKey(0) cv2.destroyAllWindows()
{"/main.py": ["/utilities.py"]}
22,360,823
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/authentication/models.py
from django.db import models from PIL import Image class Organization(models.Model): name = models.CharField(max_length=255, blank=False) username = models.CharField(max_length=100, blank=False) email = models.EmailField(blank=False) password = models.CharField(max_length=255, blank=False) def __str__(self) -> str: return self.email class Candidate(models.Model): username = models.CharField(max_length=100, blank=False) name = models.CharField(max_length=255, blank=False) email = models.EmailField(blank=False) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, blank=False) password = models.CharField(max_length=255, blank=False) pic=models.ImageField(upload_to="pic", blank=False, null=True) is_staff=models.BooleanField(default=False, blank=False) is_organization_admin = models.BooleanField(default=False, blank=False) def __str__(self) -> str: return self.email class AdminUser(models.Model): name = models.CharField(max_length=255) email = models.EmailField() password = models.CharField(max_length=255) def __str__(self) -> str: return self.email
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,824
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/app/urls.py
from django.urls import path from .views import AttendanceView urlpatterns = [ path("<slot>",AttendanceView.as_view()) ]
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,825
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/utils/tools.py
def checkFields(fields): def outer(endpoint): def inner(self, request, *args, **kwargs): for i in fields: if i not in request.data.keys(): raise ValueError(f"{i} missing") return endpoint(self, request, *args, **kwargs) return inner return outer
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,826
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/authentication/urls.py
from django.urls import path from .views import * urlpatterns = [ path("org/<service_type>", OrganizationView.as_view()), path("cand/<service_type>", CandidateView.as_view()) ]
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,827
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/app/views.py
from rest_framework.views import APIView from rest_framework.response import Response from authentication.models import Candidate from utils.security import authenticate from tempfile import NamedTemporaryFile import cv2 import face_recognition as fr from PIL import Image import os class AttendanceView(APIView): @authenticate def post(self, request, slot=None): data=request.data cand=Candidate.objects.get(username=request.username) img = Image.open(data["pic"]) img.save("media/new_img.jpg") actual=fr.load_image_file(cand.pic) img="media/new_img.jpg" actual=cv2.cvtColor(actual, cv2.COLOR_BGR2RGB) check=fr.load_image_file(img) check=cv2.cvtColor(check, cv2.COLOR_BGR2RGB) acFL=fr.face_locations(actual)[0] acEN=fr.face_encodings(actual)[0] chFL=fr.face_locations(check)[0] chEN=fr.face_encodings(check)[0] result = fr.compare_faces([acEN],chEN) return Response(data={ "message":"Success", "Attendance":result, "status":True },status=200)
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,828
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/authentication/migrations/0001_initial.py
# Generated by Django 3.2.6 on 2021-10-17 17:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AdminUser', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('email', models.EmailField(max_length=254)), ('password', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Organization', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('username', models.CharField(max_length=20)), ('email', models.EmailField(max_length=254)), ('password', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Candidate', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(max_length=30)), ('name', models.CharField(max_length=255)), ('email', models.EmailField(max_length=254)), ('password', models.CharField(max_length=255)), ('is_staff', models.BooleanField(default=False)), ('is_organization_admin', models.BooleanField(default=False)), ('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='authentication.organization')), ], ), ]
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,829
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/utils/secrets.py
FRONTEND_KEY = "c6l27hd@nyu9&ek-45hd=r3z=%gpmo%dv9wnw8@n%1-&a!&d&(" BACKEND_KEY = "c6l27hd@nyu9&ek-45hd=r3z=%gpmo%dv9wnw8@n%1-&a!&d&("
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,830
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/authentication/views.py
from rest_framework.response import Response from rest_framework.views import APIView from utils.tools import checkFields from utils.security import payloadGenerator from datetime import datetime from .models import * class OrganizationView(APIView): @checkFields(["name","email","password","confirm_password"]) def register(self, request): data=request.data if data["password"]!=data["confirm_password"]: raise ValueError("Password Not Matched") try: org=Organization.objects.get(email=data["email"]) except Exception as e: org=None if org: raise ValueError(f"{data['name']} already exists") org=Organization.objects.create(name=data["name"], username=data["email"].split('@')[0]+str(datetime.utcnow()), email=data["email"], password=data["password"]) org.save() return Response(data={ "message":"Success", "status":True },status=200) @checkFields(["email","password"]) def login(self, request): data=request.data try: org=Organization.objects.get(email=data["email"]) except Exception as e: org=None if not org: raise ValueError(f"{data['name']} donot exists") if not org.password==data['password']: raise ValueError('Invalid Credentials') print(org.username) return Response(data={ "message":"Success", "data":payloadGenerator(org.username), "status":True },status=200) def post(self, request, service_type=None): try: if service_type=="register": return self.register(request) elif service_type=="login": return self.login(request) except Exception as e: return Response(data={ "message":"Failed", "error":str(e), "status":False }, status=401) class CandidateView(APIView): @checkFields(["name","email","organization","password","confirm_password"]) def register(self, request): data=request.data if data["password"]!=data["confirm_password"]: raise ValueError("Password Not Matched") try: org=Candidate.objects.get(email=data["email"]) except Exception as e: org=None if org: raise ValueError(f"{data['name']} already exists") organization=Organization.objects.get(username=data["organization"]) org=Candidate.objects.create(name=data["name"], username=data["organization"]+str(datetime.utcnow()), email=data["email"], password=data["password"], organization=organization) org.save() return Response(data={ "message":"Success", "status":True },status=200) @checkFields(["email","password"]) def login(self, request): data=request.data try: org=Candidate.objects.get(email=data["email"]) except Exception as e: org=None if not org: raise ValueError(f"{data['name']} donot exists") if not org.password==data['password']: raise ValueError('Invalid Credentials') return Response(data={ "message":"Success", "data":payloadGenerator(org.username), "status":True },status=200) def post(self, request, service_type=None): try: if service_type=="register": return self.register(request) elif service_type=="login": return self.login(request) except Exception as e: return Response(data={ "message":"Failed", "error":str(e), "status":False }, status=401)
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,831
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/utils/security.py
from jwt import encode, decode from .secrets import FRONTEND_KEY, BACKEND_KEY from datetime import datetime, timedelta from authentication.models import Candidate from rest_framework.authentication import get_authorization_header def payloadGenerator(username): access_key_payload=dict( username=username, exp=datetime.utcnow()+timedelta(days=1), iat= datetime.utcnow() ) refresh_key_payload=dict( username=username, exp=datetime.utcnow()+timedelta(days=2), iat= datetime.utcnow() ) token = dict( access_key=encode(access_key_payload,BACKEND_KEY,algorithm="HS256"), refresh_key=encode(refresh_key_payload,BACKEND_KEY,algorithm="HS256") ) return token def verify_access_key(key): payload=decode(key, BACKEND_KEY, algorithms=["HS256"]) try: if Candidate.objects.get(username=payload['username']): flag=True except Exception as e: flag=False if(payload.get('exp')<datetime.utcnow().timestamp() and flag): return False, None return True, payload["username"] def authenticate(endpoint): def inner(self, request, *args, **kwargs): key = get_authorization_header(request).split()[1] state, username = verify_access_key(key) if not state: raise ValueError("Invalid Token") request.username=username return endpoint(self, request, *args, **kwargs) return inner
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,832
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/authentication/migrations/0002_candidate_pic.py
# Generated by Django 3.2.6 on 2021-10-18 01:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0001_initial'), ] operations = [ migrations.AddField( model_name='candidate', name='pic', field=models.ImageField(null=True, upload_to='pic'), ), ]
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,360,833
mrinmay678/Attendence-Management-System
refs/heads/master
/ams/app/models.py
from django.db import models from authentication.models import Organization, Candidate # Create your models here. class Slot(models.Model): name=models.CharField(max_length=200,blank=False,null=True) organization=models.ForeignKey(Organization, on_delete=models.CASCADE) candidates=models.ManyToManyField(Candidate) def __str__(self): return self.name
{"/authentication/serializers.py": ["/authentication/models.py", "/teacher/models.py", "/student/models.py"], "/student/models.py": ["/authentication/models.py", "/teacher/models.py"], "/student/serializers.py": ["/student/models.py", "/teacher/models.py"], "/authentication/views.py": ["/authentication/utils.py", "/authentication/serializers.py"], "/teacher/serializers.py": ["/teacher/models.py", "/authentication/models.py"], "/teacher/views.py": ["/authentication/utils.py"], "/authentication/utils.py": ["/LMS/local_settings.py"], "/authentication/urls.py": ["/authentication/views.py"], "/teacher/models.py": ["/authentication/models.py"], "/ams/app/urls.py": ["/ams/app/views.py"], "/ams/authentication/urls.py": ["/ams/authentication/views.py"], "/ams/app/views.py": ["/authentication/models.py"], "/ams/authentication/views.py": ["/ams/authentication/models.py"], "/ams/utils/security.py": ["/ams/utils/secrets.py", "/authentication/models.py"], "/ams/app/models.py": ["/authentication/models.py"]}
22,365,228
cchenyixuan/tool
refs/heads/main
/packages.py
import os class Names: """File names saved here with paths""" def __init__(self): self.cases_dir = {"Mie02": "./data/zio/Mie_case02_retry_20200516_after_sorting/", "Mie03": "./data/zio/Mie_case03_WL204_3rd_growing_after_sorting/", "Mie02_10": "./data/zio/M02_10slices_zio/"} self.pressure_file = {"Mie02": "M02_Pressure_100.csv"} self.cases_name_rule = {"Mie02": "Mie_case02_{}.csv", "Mie03": "MIe_case03_a_{}.csv", "Mie02_10": "Mie_case02_{}.csv"} self.cases_cardio_circle = {"Mie02": 0.804, "Mie03": 0.804, "Mie02_10": 0.804} self.cases_pressure_dir = {} self.project_dir = "./unnamed_project/" try: os.makedirs(self.project_dir) except FileExistsError: pass self.data_name = "" self.data = {} self.movement_data = {} class DataManager(Names): def __init__(self): super().__init__() pass def load_data(self, data_name): import os import csv import re self.data_name = data_name # load point_cloud data find_index = re.compile(r"([0-9]+).csv", re.S) data = os.listdir(self.cases_dir[data_name]) direction = self.cases_dir[data_name] for item in data: index = int(re.findall(find_index, item)[0]) self.data[index] = {} with open(direction + item, "r") as file: csv_reader = csv.reader(file) for step, row in enumerate(csv_reader): if step == 0: continue self.data[index][step - 1] = row[2:] # call load_output to refresh present states self.load_output() def load_output(self): # load output data self.project_dir = "./" + self.data_name + "/" try: os.makedirs(self.project_dir) except FileExistsError: pass files = os.listdir(self.project_dir) # no data found if files is None: pass # normal load data else: for file in files: self.movement_data[file[:-4]] = self.project_dir + "/" + file def show(self, time_index): import numpy as np import open3d as o3d slices = list(self.data.keys()) point_data = [] for i in slices: data_slice = self.data[i][time_index] point_number = int(len(data_slice) // 3) for j in range(point_number): point_data.append(data_slice[j * 3:j * 3 + 3]) point_cloud = np.array(point_data) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(point_cloud[:, :3]) o3d.visualization.draw_geometries([pcd]) def create_ply(self, time_index, name="p_mesh_c{}.ply", crop=True): import numpy as np import open3d as o3d try: os.makedirs("./mesh/" + self.data_name) except FileExistsError: pass slices = list(self.data.keys()) point_data = [] for i in slices: data_slice = self.data[i][time_index] point_number = int(len(data_slice) // 3) for j in range(point_number): point_data.append(data_slice[j * 3:j * 3 + 3]) point_cloud = np.array(point_data, dtype=np.float32) point_position = [] for item in point_cloud: point_position.append(item[:3]) x_, y_, z_ = 0, 0, 0 for item in point_position: x_ += item[0] y_ += item[1] z_ += item[2] x_ /= point_cloud.shape[0] y_ /= point_cloud.shape[0] z_ /= point_cloud.shape[0] middle = np.array([x_, y_, z_]) normal_vectors = [] for item in point_position: normal = item - middle normal_vectors.append(normal) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(point_cloud[:, :3]) pcd.normals = o3d.utility.Vector3dVector(normal_vectors[:]) # fake normals with low accu poisson_mesh = \ o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=8, width=0, scale=1.1, linear_fit=False)[0] bbox = pcd.get_axis_aligned_bounding_box() p_mesh_crop = poisson_mesh.crop(bbox) if crop is True: o3d.io.write_triangle_mesh("./mesh/" + self.data_name + "/" + name.format(time_index), p_mesh_crop) else: o3d.io.write_triangle_mesh("./mesh/" + self.data_name + "/" + name.format(time_index), poisson_mesh) # a method not cropping the mesh class Test: def __init__(self): print(1) self.book = {1: 2} def test(self): print("This is Test.test!") # Done class Analysis(DataManager): def __init__(self, data_name=None): super().__init__() if data_name is None: print('Try "Analysis(data name)"') print("Or try '.load_data(data name)'") else: self.load_data(data_name) def show_data(self, datatype): print("Here is DataManager.Analysis.show_data!") import Viewer self.load_output() try: data = self.movement_data[datatype] print(data) Viewer.plot(data) except KeyError: print("File {}.csv not found, unable to process!".format(datatype)) pass def calculate_data(self, activated=1234567): print("Here is DataManager.Analysis.calculate_data!") import preprocess import starter_forward_difference file_path = self.cases_dir[self.data_name] cardio_circle = self.cases_cardio_circle[self.data_name] output_dir = self.project_dir name_rule = self.cases_name_rule[self.data_name] preprocess.preprocess(file_path) starter_forward_difference.main(file_path, activated, cardio_circle, output_dir, name_rule) pass class DeepAnalysis(Analysis): def __init__(self, data_name=None): super().__init__(data_name) self.plot_data = {"time": None, "slices": [key for key in self.data.keys()], "type": None} self.dataset = {"point": None, "normal": None, "pressure": None, "m": None, "mu": None, "k": None} self.full_dataset = {"point": None, "normal": None, "pressure": None, "m": None, "mu": None, "k": None} self.pressure = {} self.purified_pressure = {} self.load_pressure() def load_pressure(self): """load pressure data""" try: assert self.data_name != "" except AssertionError: print("Failed to init...") print("Case name is indispensable for DeepAnalysis!") return import os import csvreader try: self.cases_pressure_dir[self.data_name] = "./data/pressure/" + self.data_name os.listdir(self.cases_pressure_dir[self.data_name]) assert os.listdir(self.cases_pressure_dir[self.data_name]) is not [] except FileNotFoundError: print("Pressure folder not found, generating files...") csvreader.convert_file(self.data_name, self.pressure_file[self.data_name]) except AssertionError: print("Pressure folder is empty, generating files...") csvreader.convert_file(self.data_name, self.pressure_file[self.data_name]) pressure_files = os.listdir(self.cases_pressure_dir[self.data_name]) for pressure_file in pressure_files: self.pressure[int(float(pressure_file[:-4]) * 100) / 100] = \ self.cases_pressure_dir[self.data_name] + "/" + pressure_file pass def purify_pressure(self, time_step=None): if time_step is None: time_step = [0, 99] import starter starter.solve(time_step=time_step, case_name=self.data_name, case_dir=self.cases_dir[self.data_name], pressure=self.pressure, background="bear") pass def advanced_show(self, **kwargs): """**kwargs = [time=0, slices=[1,2,3], type=[pressure, m, mu, k,...]]""" print("Here is DataManager.Analysis.DeepAnalysis.advanced_show!") import csv import random for keyword in kwargs.keys(): self.plot_data[keyword] = kwargs[keyword] time = "-" + str(self.plot_data["time"]) + "-" slices = "-" + str(self.plot_data["slices"][0]) + "-" + str(self.plot_data["slices"][-1]) + "-" type_ = "-" for i in self.plot_data["type"]: type_ += str(i) type_ += "-" with open(self.project_dir + "time{}_slice{}_type{}.csv".format(time, slices, type_), "w", newline="") as file: csv_writer = csv.writer(file) data = [] for item in self.plot_data["slices"]: raw_points = self.data[item][self.plot_data["time"]] for i in range(len(raw_points) // 3): temp = raw_points[i * 3:i * 3 + 3] temp.append(random.random()) # TODO show specific data, now use random as a test data.append(temp) for row in data: csv_writer.writerow(row) file.close() self.show_data("time{}_slice{}_type{}".format(time, slices, type_)) pass def analysis_ode(self, point_index=0): print("Here is DataManager.Analysis.DeepAnalysis.analysis_ode!") t = 0.01 import numpy as np import os import csv for file in os.listdir("./data/pressure/" + self.data_name + "_purified/"): self.purified_pressure[float(file[:-4])] = "./data/pressure/" + self.data_name + "_purified/" + file data_index = list(self.purified_pressure.keys()) data_index.sort() A = np.zeros([98, 2]) B = np.zeros([98, 1]) for step in range(len(data_index) - 2): point_cloud1 = [] point_cloud2 = [] point_cloud3 = [] pressure = [] normal = [] with open(self.purified_pressure[data_index[step]], "r") as f: csv_reader = csv.reader(f) for row in csv_reader: point_cloud1.append(row[:3]) f.close() with open(self.purified_pressure[data_index[step + 1]], "r") as f: csv_reader = csv.reader(f) for row in csv_reader: point_cloud2.append(row[:3]) pressure.append(float(row[3])) normal.append(row[4:]) f.close() with open(self.purified_pressure[data_index[step + 2]], "r") as f: csv_reader = csv.reader(f) for row in csv_reader: point_cloud3.append(row[:3]) f.close() point_cloud1 = np.array(point_cloud1, dtype=np.float32) point_cloud2 = np.array(point_cloud2, dtype=np.float32) point_cloud3 = np.array(point_cloud3, dtype=np.float32) pressure = np.array(pressure, dtype=np.float32) * 0.0001 normal = np.array(normal, dtype=np.float32) # pressure assert to have same direction with a dx1 = point_cloud2 - point_cloud1 dx2 = point_cloud3 - point_cloud2 dx = 0.5 * (dx1 + dx2) v = dx / t a_ = (dx2 - dx1) / t ** 2 A[step, 0] = np.linalg.norm(a_[point_index]) A[step, 1] = np.linalg.norm(v[point_index]) #A[step, 2] = np.linalg.norm(dx[point_index]) B[step] = np.linalg.norm(pressure[point_index] * normal[point_index] @ (a_[point_index] / np.linalg.norm(a_[point_index]))) self.A = A.T@A self.B = A.T@B print(np.linalg.solve(self.A, self.B)) # TODO ode model pass def analysis_ensemble_kalman_filter(self): self.dataset = self.dataset print("Here is DataManager.Analysis.DeepAnalysis.analysis_ensemble_kalman_filter!") # TODO EnKF model # TODO save analyzed data pass class Console: def __init__(self): self.console() pass def console(self): print("This is a python console, call Gui() to enter your code.") print("Code saved as '.text' attribute of Gui object.") import traceback while True: my_code = input(">>>") if my_code == "exit" or my_code == "quit": break try: execute_times = 0 try: answer = eval(my_code) if answer is not None: print(answer) execute_times += 1 except: pass if execute_times == 0: exec(my_code) except: traceback.print_exc() return class Gui: def __init__(self): self.text = None import tkinter root = tkinter.Tk() root.geometry("300x450") root.title("Text Editor") self.inbox = tkinter.Text(root, width=42, height=32) button1 = tkinter.Button(root, text="apply", width=41) self.inbox.place(x=0, y=0) button1.place(x=0, y=420) button1.bind('<Button-1>', lambda event: self.get_data(event)) root.mainloop() def get_data(self, event): self.text = self.inbox.get('1.0', 'end') def restart(self): import tkinter root = tkinter.Tk() root.geometry("300x450") root.title("Text Editor") self.inbox = tkinter.Text(root, width=42, height=32) button1 = tkinter.Button(root, text="apply", width=41) self.inbox.place(x=0, y=0) button1.place(x=0, y=420) button1.bind('<Button-1>', lambda event: self.get_data(event)) root.mainloop() a = DeepAnalysis("Mie02") # a.purify_pressure(time_step=[1, 1]) # a.analysis_ode() Console()
{"/packages.py": ["/Viewer.py", "/preprocess.py", "/starter_forward_difference.py", "/csvreader.py", "/starter.py"]}
22,365,229
cchenyixuan/tool
refs/heads/main
/starter.py
import os import json import time import re def solve(**kwargs): find_pyw = re.compile(r"pyw.exe", re.S) os.cpu_count() case_name = kwargs["case_name"] start, end = kwargs["time_step"] case_dir = kwargs["case_dir"] pressure = kwargs["pressure"] # dict{i:path_i} for i in range(start, end + 1): while True: running_pyw = os.popen('wmic process get description, processid').read() running_pyw = len(re.findall(find_pyw, running_pyw)) if running_pyw >= os.cpu_count() - 1: time.sleep(5) else: break prof = [case_name, case_dir, i, pressure[i / 100]] # [case_name, point_dir, time_step, pressure_dir] with open('./temp.bat', 'w') as file: file.write('set current_path=%~dp0') file.write('\n') file.write('start %current_path%\\pressure_purifier.py %1 %2 %3 %4') file.close() with open('./global.json', 'w') as file: json.dump(prof, file) file.close() with open('./global.json', 'r') as file: data = json.load(file) file.close() para = "temp.bat {} {} {} {}".format(data[0], data[1], data[2], data[3]) os.system(para) # check if run as background background = kwargs["background"] if background == "bear": print("master call pass") elif background != 1: check_background() else: import threading t1 = threading.Thread(target=check_background) t1.start() def check_background(): find_pyw = re.compile(r"pyw.exe", re.S) while True: running_pyw = os.popen('wmic process get description, processid').read() running_pyw = len(re.findall(find_pyw, running_pyw)) if running_pyw == 0: print("Task completed!") break time.sleep(10)
{"/packages.py": ["/Viewer.py", "/preprocess.py", "/starter_forward_difference.py", "/csvreader.py", "/starter.py"]}
22,394,130
JayQust/django_webserver
refs/heads/main
/tets.py
print("ujdjy")
{"/main.py": ["/app/app.py"], "/app/app.py": ["/posts/repo.py"]}
22,452,989
AkarasateH/PyRouterSimulation
refs/heads/main
/profileManager.py
import json from helper import DisplayObjectTable import logging logging.getLogger('Profile Manager:') class ProfileManager: filename = 'profile.json' def __init__(self): return None # Get profiles from file def __loadProfiles(self): with open(self.filename, 'r') as j: return json.loads(json.load(j)) # Update profiles in the json file def __updateProfiles(self, profiles: dict): with open(self.filename, 'w') as file: json.dump(json.dumps(profiles), file) # Get all subnets in the network def __getAllSubnets(self): profiles = self.__loadProfiles() subnets = [] for profileName in profiles.keys(): for subnet in profiles[profileName]['subnets']: subnets.append(subnet) if (not subnet in subnets) else subnets return subnets # Get unique subnet with the router. def getUniqueSubnets(self, routerName: str): routerSubnets = self.__loadProfiles()[routerName]['subnets'] set_router = set(routerSubnets) set_network = set(self.__getAllSubnets()) return list(set_network - set_router) # Add Neighbor def addNeighbor(self, routerName: str, neighborName: str): logging.info(f'Adding neighbor {neighborName} to {routerName}.') profiles = self.__loadProfiles() if not (neighborName in profiles[routerName]['neighbor']): profiles[routerName]['neighbor'].append(neighborName) self.__updateProfiles(profiles) return profiles[routerName] # Remove Neighbor def removeNeighbor(self, routerName: str, neighborName: str): logging.info(f'Removing neighbor {neighborName} from {routerName}.') profiles = self.__loadProfiles() profiles[routerName]['neighbor'].remove(neighborName) self.__updateProfiles(profiles) return profiles[routerName] # Removing profile. def removeProfile(self, profileName: str): # Get current profile logging.info(f'Removing profile {profileName}.') profile = self.__loadProfiles() # Pop profile [profileName] out. profile.pop(profileName) # Update profile as json self.__updateProfiles(profile) return profile # Adding new profile. def addAndUpdateProfile(self, name: str, ip: str, subnets: [str], port: int, neighbor: [str]): logging.info(f'Adding new profile {name}.') profile = {} newObj = { 'ip': ip, 'port': port, 'subnets': subnets, 'neighbor': neighbor } # Get previous profile profile = self.__loadProfiles() # Assignment new profile. profile[name] = newObj # Update profile as json self.__updateProfiles(profile) return profile def getProfileByName(self, name: str): # logging.info(f'Getting information of profile by name {name}.') profile = self.__loadProfiles() return profile[name] def getAllProfiles(self): logging.info(f'Getting information of all profiles.') profiles = self.__loadProfiles() DisplayObjectTable(['Router Name', 'IP', 'Port', 'Subnets', 'Neighbors'], profiles, 'Profiles Table') return profiles
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
22,452,990
AkarasateH/PyRouterSimulation
refs/heads/main
/routeTable.py
import logging from helper import DisplayObjectTable logging.getLogger('Routing Table:') class RoutingTable: def __displayTable(self): DisplayObjectTable(['Dest Subnet', 'Next Hop', 'Cost'], self.table, 'Routing Table ' + self.owner) def __init__(self, routerName: str, subnets: [str]): logging.info('Created routing table for router {} subnet {}'.format(routerName, subnets)) self.owner = routerName self.table = {} for subnet in subnets: self.table[subnet] = { 'nextHop': '-', 'cost': 1 } self.__displayTable() def removeHopByRouter(self, name: str): interations = self.table.copy() for subnet in interations.keys(): if name == self.table[subnet]['nextHop']: self.table.pop(subnet) # Remove link in the table by subnet def removeLinkBySubnet(self, subnet: str): self.table.pop(subnet) def subnetIsFound(self, subnet: str): return True if subnet in self.table.keys() else False def getLinkDetailBySubnet(self, subnet: str): return { 'owner': self.owner, 'linkDetail': self.table.get(subnet, None) } def __updateTableBySubnet(self, subnet: str, nextHop: str, cost: int): self.table[subnet] = { 'nextHop': nextHop, 'cost': cost } return self.table[subnet] # tableData should have this format { subnet, cost, owner } def updateTable(self, tableData: { 'subnet': str, 'cost': int, 'owner': str }): limitCost = 16 if tableData['cost'] >= 15 else tableData['cost'] if not tableData['subnet'] in self.table: self.__updateTableBySubnet(tableData['subnet'], tableData['owner'], tableData['cost']) elif tableData['cost'] < self.table[tableData['subnet']]['cost']: self.__updateTableBySubnet(tableData['subnet'], tableData['owner'], tableData['cost']) self.__displayTable()
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
22,452,991
AkarasateH/PyRouterSimulation
refs/heads/main
/routerB.py
from router import Router from profileManager import ProfileManager import logging logging.basicConfig(format='%(asctime)s - Router B:%(message)s', level=logging.INFO) profile = ProfileManager() profiles = profile.getAllProfiles() router = Router(profiles['B']['ip'], profiles['B']['port'], 'B') router.run() # router.updateRoutingTable()
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
22,452,992
AkarasateH/PyRouterSimulation
refs/heads/main
/router.py
from socket import * import threading import logging import re from time import sleep from profileManager import ProfileManager from routeTable import RoutingTable from helper import ConvertJsonToString, ConvertStringToJson logging.getLogger('Router Core:') class Router: TIMEOUT = 3 # Timeout 2 sec INTERVAL_TIME = 5 # Interval time 30 sec ALIVE_TIMEOUT = 6 reqMessage = 'Hello' resMessage = 'Hi' def __init__(self, ip: str, port: int, name: str): self.myIP = ip self.myPort = port self.myName = name self.profileManager = ProfileManager() self.routingTable = RoutingTable(name, self.profileManager.getProfileByName(name)['subnets']) self.COUNTER_FAIL = {} self.deathRouters = [] def getInfo(self): info = dict() info['ip'] = self.myIP info['port'] = self.myPort return info def __setInterval(self, func, profile, routerName): e = threading.Event() while not e.wait(self.INTERVAL_TIME): if self.COUNTER_FAIL.get(routerName, 0) >= self.ALIVE_TIMEOUT: self.deathRouters.append(routerName) self.profileManager.removeNeighbor(self.myName, routerName) self.routingTable.removeHopByRouter(routerName) e.set() else: func(profile, routerName) # Server Process: def __createServer(self): serverSocket = socket(AF_INET, SOCK_DGRAM) serverSocket.bind(('', self.myPort)) pattern = re.compile("(sender)|(receiver)|(findSubnet)|(deathRouters)") while 1: try: # logging.info('Server {} is ready to receive'.format(self.myName)) # logging.info('Server {} receiving data . . .'.format(self.myName)) receivedData, addr = serverSocket.recvfrom(4096) decodedMessage = receivedData.decode() # logging.info(f'{self.myName} received message: {decodedMessage} from {addr}') if decodedMessage == self.reqMessage: serverSocket.sendto(self.resMessage.encode(), addr) elif pattern.search(decodedMessage): # logging.info(f'{self.myName} decoded message: {decodedMessage}') requestJson = ConvertStringToJson(decodedMessage) response = self.__findSubnetProcess(requestJson['findSubnet'], 0) serverSocket.sendto(response.encode(), addr) for death in requestJson['deathRouters']: self.profileManager.removeNeighbor(self.myName, death) self.routingTable.removeHopByRouter(death) except Exception as err: # logging.info('ERR: ', err) pass # Multi tasks for server process. def run(self): job = threading.Thread(target=self.__createServer, args=[]).start() job2 = threading.Thread(target=self.updateRoutingTable, args=[]).start() self.checkAliveNeighbor() # self.updateRoutingTable() def __advertiseProcess(self, profile: dict, routerName: str): clientSocket = socket(AF_INET, SOCK_DGRAM) clientSocket.settimeout(self.TIMEOUT) try: # logging.info('Checking neighbor {}'.format(routerName)) clientSocket.sendto(self.reqMessage.encode(), (profile['ip'], profile['port'])) receivedMessage, addr = clientSocket.recvfrom(4096) if receivedMessage.decode() == self.resMessage: logging.info('{} is alive.'.format(routerName)) self.COUNTER_FAIL[routerName] = 0 except timeout as err: self.COUNTER_FAIL[routerName] = self.COUNTER_FAIL.get(routerName, 0) + 1 logging.info('Neighbor {} timeout {}.'.format(routerName, self.COUNTER_FAIL.get(routerName, 0))) pass # Client process def checkAliveNeighbor(self): profile = self.profileManager.getProfileByName(self.myName) neighbors = profile['neighbor'] # logging.info(f'Check stat neighbors : {neighbors}') for neighbor in neighbors: neighborProfile = self.profileManager.getProfileByName(neighbor) thread = threading.Thread(target=self.__setInterval, args=[self.__advertiseProcess, neighborProfile, neighbor]) thread.start() # RT (Routing Table) # Return the request as array. def __getRequestToUpdateRT(self, subnets: [str] = []): myNeighbors = self.profileManager.getProfileByName(self.myName)['neighbor'] findingSubnets = [] if len(subnets) == 0: findingSubnets = self.profileManager.getUniqueSubnets(self.myName) else: findingSubnets = subnets requests = [] for findSubnet in findingSubnets: for neighbor in myNeighbors: neighborProfile = self.profileManager.getProfileByName(neighbor) request = { 'sender': self.myName, 'receiver': neighbor, 'dest': { 'ip': neighborProfile['ip'], 'port': neighborProfile['port'], }, 'findSubnet': findSubnet, 'deathRouters': self.deathRouters } self.deathRouters = [] requests.append(request) return requests def __updatingRTProcess(self, requestMsg: dict): clientSocket = socket(AF_INET, SOCK_DGRAM) clientSocket.settimeout(self.TIMEOUT) try: logging.info('{} Update Routing Table {}'.format(self.myName, requestMsg)) requestMessage = ConvertJsonToString({ 'sender': requestMsg['sender'], 'receiver': requestMsg['receiver'], 'findSubnet': requestMsg['findSubnet'], 'deathRouters': requestMsg['deathRouters'], }) clientSocket.sendto(requestMessage.encode(), (requestMsg['dest']['ip'], requestMsg['dest']['port'])) # Response format will be { rcvFrom: [neighbor-name], cost: [link-cost], subnet: [found-subnet] } responseMessage, addr = clientSocket.recvfrom(4096) responseDict = ConvertStringToJson(responseMessage.decode()) # logging.info('Response message: {}'.format(responseDict)) updatingData = { 'subnet': responseDict['subnet'], 'cost': responseDict['cost'] + 1, 'owner': responseDict['rcvFrom'] } self.routingTable.updateTable(updatingData) except timeout as err: logging.info('Update Routing Table: {} :Error: {}.'.format(requestMsg['receiver'], err)) pass def updateRoutingTable(self): while 1: sleep(self.INTERVAL_TIME) # logging.info('Router {} is getting all requests for updating routing table'.format(self.myName)) requests = self.__getRequestToUpdateRT() for request in requests: thread = threading.Thread(target=self.__updatingRTProcess, args=[request]) thread.start() thread.join() return None def __findSubnetProcess(self, subnet: str, myCost: int = 0): # logging.info('Finding subnet: {}'.format(subnet)) cost = myCost + 1 # Limit maximum cost if cost >= 15: response = { 'rcvFrom': self.myName, 'cost': cost, 'subnet': subnet } return ConvertJsonToString(response) if self.routingTable.subnetIsFound(subnet): response = { 'rcvFrom': self.myName, 'cost': self.routingTable.getLinkDetailBySubnet(subnet)['linkDetail']['cost'], 'subnet': subnet } return ConvertJsonToString(response) else: requests = self.__getRequestToUpdateRT([subnet]) for request in requests: thread = threading.Thread(target=self.__updatingRTProcess, args=[request]) thread.start() return self.__findSubnetProcess(subnet, cost)
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}