unable to load static css file in the dash app - python

I have built a single page dash app which runs as expected when run as a single file, but when I am trying to run it as a whole app, the CSS does not load correctly.
Below is my folder structure
While I load the whole app by manage.py below is the error that I get
Internal Server Error: /assets/internal.css
Traceback (most recent call last):
File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\my_project\analyser_tool\views.py", line 32, in dash_index
return HttpResponse(dispatcher(request))
File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\my_project\analyser_tool\views.py", line 27, in dispatcher
return response.get_data()
File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\werkzeug\wrappers.py", line 986, in get_data
self._ensure_sequence()
File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\werkzeug\wrappers.py", line 1035, in _ensure_sequence
raise RuntimeError('Attempted implicit sequence conversion '
RuntimeError: Attempted implicit sequence conversion but the response object is in direct passthrough mode.
This is my only second dash app that I am working and unfortunately does not have much experience in it. I am really hopping if some could please help me fix this issue. I have been struggling with it for couple of days now.
Thanks a lot in advance !!

With continued research, I was able to resolve the issue by adding the following to my server.py
css_directory = os.getcwd()
stylesheets = ['stylesheet.css']
static_css_route = '/static/'
#app.server.route('{}<stylesheet>'.format(static_css_route))
def serve_stylesheet(stylesheet):
if stylesheet not in stylesheets:
raise Exception(
'"{}" is excluded from the allowed static files'.format(
stylesheet
)
)
return flask.send_from_directory(css_directory, stylesheet)
for stylesheet in stylesheets:
app.css.append_css({"external_url": "/static/{}".format(stylesheet)})
This answer was answered before and is taken from
https://community.plot.ly/t/serve-locally-option-with-additional-scripts-and-style-sheets/6974/6

Related

Unique PermissionError: [WinError 5] Access is denied IIS Issue

I am currently setting up a django site to run on IIS, however I am running into an issue with the USZipCodes python module, When it goes to call the USZipCodes module if gets an access denied error.
I have confirmed all folders regarding this EXCEPT the systemprofile folder has proper permissions for the IIS_IUSRS profile. I would do the systemprofile as well but it just give me more errors and I would prefer not to
This module works fine when not IIS, through CMD it works fine, it is only when using IIS to run the app does this occur.
I suspect I may just have the cut the module out but I would prefer not too
Error Log:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\inetpub\wwwroot\Apps\scituateApp\.\tickets\views.py", line 286, in push
json_client['street_name'], zco(json_client['zip']), json_client['state'], json_client['zip'],
File "C:\inetpub\wwwroot\Apps\scituateApp\.\tickets\views.py", line 15, in zco
search = SearchEngine()
File "C:\Python310\lib\site-packages\uszipcode\search.py", line 153, in __init__
self._download_db_file_if_not_exists()
File "C:\Python310\lib\site-packages\uszipcode\search.py", line 173, in _download_db_file_if_not_exists
download_db_file(
File "C:\Python310\lib\site-packages\uszipcode\db.py", line 33, in download_db_file
Path(db_file_path).parent.mkdir(parents=True, exist_ok=True)
File "C:\Python310\lib\site-packages\pathlib_mate\pathlib2.py", line 1614, in mkdir
_try_except_filenotfounderror(_try_func, _exc_func)
File "C:\Python310\lib\site-packages\pathlib_mate\pathlib2.py", line 117, in _try_except_filenotfounderror
try_func()
File "C:\Python310\lib\site-packages\pathlib_mate\pathlib2.py", line 1605, in _try_func
self._accessor.mkdir(self, mode)
File "C:\Python310\lib\site-packages\pathlib_mate\pathlib2.py", line 593, in wrapped
return strfunc(str(pathobj), *args)
PermissionError: [WinError 5] Access is denied: 'C:\\Windows\\system32\\config\\systemprofile\\.uszipcode'
Figured I would follow up. After quite some hours I was able to resolve the issue.
When you setup the IIS, it creates a local group called IIS_LUSRS. You must add the user (local or domain) that you log into to run IIS to this local groups (can be done through the lusrmgr.msc program). Then after this is done, allow that group modify and write privs on the python site package pathlib and the system profile in system 32.
This is not the best solutions, but it fixed it for me...

Send_email with django generate error _getfullpathname:

i'm tring to send email with django but i recive ad error even with a easy code
send_mail(
'Subject here',
'Here is the message.',
'from#example.com',
['to#example.com'],
fail_silently=False,
)
i get that output error
Traceback (most recent call last):
File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\VisualStudioWorkspaces\DjangoPlayground\django_tutorial\accounts\views.py", line 93, in register
send_mail(
File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\__init__.py", line 52, in send_mail
connection = connection or get_connection(
File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\__init__.py", line 35, in get_connection
return klass(fail_silently=fail_silently, **kwds)
File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\backends\filebased.py", line 20, in __init__
self.file_path = os.path.abspath(self.file_path)
File "C:\Users\oscur\AppData\Local\Programs\Python\Python39\lib\ntpath.py", line 527, in abspath
return normpath(_getfullpathname(path))
Exception Type: TypeError at /accounts/registration/
Exception Value: _getfullpathname: path should be string, bytes or os.PathLike, not NoneType
Django support different email backends.
SMTP backend(Default)
Console backend
File backend
In-memory backend
When you use send_mail function without a backend argument django select backend based on settings.EMAIL_BACKEND.
From the exception it seems like django using File backend(Which means EMAIL_BACKEND you are using most likely 'django.core.mail.backends.filebased.EmailBackend')
Quoting from the django docs
The file backend writes emails to a file. A new file is created for
each new session that is opened on this backend. The directory to
which the files are written is either taken from the EMAIL_FILE_PATH
setting or from the file_path keyword when creating a connection with
get_connection().
So my suggestion is that setting EMAIL_FILE_PATH in settings.py will solve this issue.

dictionary update sequence element #0 has length 0; 2 is required

I was working on my project and everthing worked fine. I tried to open the server in another browser and this error appeared. I stopped the project and start it agian and it stop working on my main browser aswell. I dont have any idea what this cause it.
Internal Server Error: /account/login/
Traceback (most recent call last):
File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
response = response.render()
File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 105, in render
self.content = self.rendered_content
File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content
return template.render(context, self._request)
File "A:\repos\topanime\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "A:\repos\topanime\venv\lib\site-packages\django\template\base.py", line 168, in render
with context.bind_template(self):
File "C:\Python\Python391\lib\contextlib.py", line 117, in __enter__
return next(self.gen)
File "A:\repos\topanime\venv\lib\site-packages\django\template\context.py", line 244, in bind_template
updates.update(processor(self.request))
ValueError: dictionary update sequence element #0 has length 0; 2 is required
[18/Mar/2021 18:52:01] "GET /account/login/ HTTP/1.1" 500 86400
If there is any other information that you need tell me.
The problem was that I had a view in context_processors that required login #login_required. So I couldnt load any page because i wasnt logged in
If you use #login_required in context_processors:
The way I solved it was by replacing it with an if statment inside the context_processor.
def myCP(self, *args, **kwargs):
kontext = {}
if self.user.is_authenticated:
# The user is logged in
kontext['loggedIn'] = True
else:
# The user is logged out
kontext['loggedIn'] = False
return kontext

Django test throwing an error on response status code 404

I'm following along with a lecture on django testing and this is one of the tests:
def test_invalid_flight_page(self):
max_id = Flight.objects.all().aggregate(Max("id"))["id__max"]
c = Client()
response = c.get(f"/flights/{max_id + 1}")
self.assertEqual(response.status_code, 404)
When I run manage.py tests it throws an error on this test, essentially saying there is no matching flight:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.......E..
======================================================================
ERROR: test_invalid_flight_page (flights.tests.FlightTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\sarah\Desktop\airline\flights\tests.py", line 68, in test_invalid_flight_page
response = c.get(f"/flights/{max_id + 1}")
File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 732, in get
response = super().get(path, data=data, secure=secure, **extra)
File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 393, in get
return self.generic('GET', path, secure=secure, **{
File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 470, in generic
return self.request(**r)
File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 709, in request
self.check_exception(response)
File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 571, in check_exception
raise exc_value
File "C:\Python\Python385\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python\Python385\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sarah\Desktop\airline\flights\views.py", line 21, in flight
flight = Flight.objects.get(pk=flight_id)
File "C:\Python\Python385\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python\Python385\lib\site-packages\django\db\models\query.py", line 429, in get
raise self.model.DoesNotExist(
flights.models.Flight.DoesNotExist: Flight matching query does not exist.
----------------------------------------------------------------------
Ran 10 tests in 0.120s
FAILED (errors=1)
Destroying test database for alias 'default'...
But that is the point, there is no flight with that id so the response status code for that request should equal 404. As far as I can see I have copied the code accurately from the lecture but the lecturer's tests are all running okay. Can anyone see what I may be missing?
When I change the expected response.status_code to 200 self.assertEqual(response.status_code, 200) it gives me the same error so this indicates to me that the main problem lies with the response line?
Please let me know if there is anything more you need to see.
Your view class is not handling when the query resolves to nothing. In django it's done as follows:
try:
result = SomeModel.objects.get(pk=some_id)
except SomeModel.DoesNotExist:
# Return 404 here
I've met the same problem. Indeed, it came from the response line or client.get() method itself. In my case, I add "/" at the end of the quotation mark as:
response = c.get(f"/flights/{max_id + 1}/")
And then check assert condition. Now it functions as I want.
Also found that:
If you substitute a word instead of a number as an invalid page, it works just fine. For example:
THIS ONE OK (404 were detected):
response = c.get(f"/flights/whatever")
THIS ONE DOESN'T WORK (404 were not detected and errors were alerted):
response = c.get(f"flights/15")

Unable to debug or use pdb in Django: bdb.BdbQuit

I'm using Django (2, 2, 4, 'final', 0) within a docker, but I'm able to bash inside to open or execute whatever is required. But I can't debug. (How to debug in Django, the good way? states some methods, none work for me)
Within my views.py I'm having various functions, for instance this here.
def visGraph(request):
showgraph = 'Graphen'
selectDB = request.GET.get('selectDB', '')
__import__("pdb").set_trace()
title += " <i>"+showgraph+"</i> ("+selectDB+")"
It works fine until I fill in the pdb, adding the debugger makes my app crash immediately:
> /code/DjangoGraphen/views.py(74)visGraph()
-> title += " <i>"+showgraph+"</i> ("+selectDB+")"
(Pdb)
Internal Server Error: /DjangoGraphen/visGraph
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "./DjangoGraphen/views.py", line 74, in visGraph
title += " <i>"+showgraph+"</i> ("+selectDB+")"
File "./DjangoGraphen/views.py", line 74, in visGraph
title += " <i>"+showgraph+"</i> ("+selectDB+")"
File "/usr/lib64/python3.7/bdb.py", line 88, in trace_dispatch
return self.dispatch_line(frame)
File "/usr/lib64/python3.7/bdb.py", line 113, in dispatch_line
if self.quitting: raise BdbQuit
bdb.BdbQuit
ERROR:django.request:Internal Server Error: /DjangoGraphen/visGraph
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "./DjangoGraphen/views.py", line 74, in visGraph
title += " <i>"+showgraph+"</i> ("+selectDB+")"
File "./DjangoGraphen/views.py", line 74, in visGraph
title += " <i>"+showgraph+"</i> ("+selectDB+")"
File "/usr/lib64/python3.7/bdb.py", line 88, in trace_dispatch
return self.dispatch_line(frame)
File "/usr/lib64/python3.7/bdb.py", line 113, in dispatch_line
if self.quitting: raise BdbQuit
bdb.BdbQuit
[21/Oct/2019 17:47:14] "GET /DjangoGraphen/visGraph?selectDB=Test&showgraph=graph HTTP/1.1" 500 88178
It doesn't matter very much if I'm using __import__("pdb").set_trace() or breakpoint() - both return the same result.
In my settings.py I have so far DEBUG = True, setting it to False doesn't change anything.
I'm viewing the logs within my command line using:
docker logs django_web_1 -f
I assume for the pdb I require an active shell rather than just a log-viewer, but I can't figure out what to change or how to do that.
But tried already what's given here as an answer: Interactive shell in Django
But it just opens a Python-Shell.
The solution is actually rather easy. The problem is the docker. The solution is stated here and works:
https://medium.com/#vladyslav.krylasov/how-to-use-pdb-inside-a-docker-container-eeb230de4d11
Add this to your docker-compose.yml:
ports:
- "4444:4444"
stdin_open: true
tty: true
Install the remote-pdb and use instead of your default pdb command:
__import__("remote_pdb").set_trace(host='0.0.0.0', port=4444)
Log into your docker and telnet into the pdb session:
telnet 0.0.0.0 4444
If you know you are going to end up in the debugger you can use run instead of up.
$ docker-compose run --rm --service-ports django_web
The problem is that up assumes it will run multiple services, even when you tell it to only run one, so it will wrap them for you. That's also why it prepends the output with the service name:
web_1 | Some output
db_1 | Some db logs
The run command doesn't do this and so you can have a shell and a debugger without problems or remote_pdb workarounds.
NOTE: when using run, you have to configure the dependencies because not everything is automatically started otherwise.

Categories

Resources