How to run Django with Uvicorn webserver? - python

I have a Django project running on my local machine with dev server manage.py runserver and I'm trying to run it with Uvicorn before I deploy it in a virtual machine. So in my virtual environment I installed uvicorn and started the server, but as you can see below it fails to find Django static css files.
(envdev) user#lenovo:~/python/myproject$ uvicorn myproject.asgi:application --port 8001
Started server process [17426]
Waiting for application startup.
ASGI 'lifespan' protocol appears unsupported.
Application startup complete.
Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit)
INFO: 127.0.0.1:45720 - "GET /admin/ HTTP/1.1" 200 OK
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/base.css
INFO: 127.0.0.1:45720 - "GET /static/admin/css/base.css HTTP/1.1" 404 Not Found
Not Found: /static/admin/css/dashboard.css
Not Found: /static/admin/css/dashboard.css
INFO: 127.0.0.1:45724 - "GET /static/admin/css/dashboard.css HTTP/1.1" 404 Not Found
Not Found: /static/admin/css/responsive.css
Not Found: /static/admin/css/responsive.css
INFO: 127.0.0.1:45726 - "GET /static/admin/css/responsive.css HTTP/1.1" 404 Not Found
Uvicorn has an option --root-path so I tried to specify the directory where these files are located but there is still the same error (path is correct). How can I solve this issue?

When not running with the built-in development server, you'll need to either
use whitenoise which does this as a Django/WSGI middleware (my recommendation)
use the classic staticfile deployment procedure which collects all static files into some root and a static file server is expected to serve them. Uvicorn doesn't seem to support static file serving, so you might need something else too (see e.g. https://www.uvicorn.org/deployment/#running-behind-nginx).
(very, very unpreferably!) have Django serve static files like it does in dev

Add below code your settings.py file
STATIC_ROOT = os.path.join(BASE_DIR, 'static', )
Add below code in your urls.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [.
.....] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Then run below command but static directory must exist
python manage.py collectstatic --noinput
start server
uvicorn main.asgi:application --host 0.0.0.0

Related

Template not found pyinstaller BOTTLE

I used pyinstaller to create an executable for a bottle_app for a personal project of mine for a friend. However, after running the executable, it fails to load the template for the home page.
The console for the server only shows the following after a couple refreshes:
Bottle v0.12.19 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit
127.0.0.1 - - [02/Apr/2021 08:01:30] "GET / HTTP/1.1" 500 788
127.0.0.1 - - [02/Apr/2021 08:01:30] "GET /favicon.ico HTTP/1.1" 404 742
127.0.0.1 - - [02/Apr/2021 08:01:35] "GET / HTTP/1.1" 500 788
127.0.0.1 - - [02/Apr/2021 08:01:36] "GET / HTTP/1.1" 500 788
When I run the bottle_app.py file on my machine normally, it works fine.
Here is the command that I ran in pyinstaller
pyinstaller --onefile --add-data 'views/*;views' --add-data 'views/css;views/css' --add-data 'views/js;views/js'--add-data 'pricesBeef.csv;.' --add-data 'pricesHog.csv;.' --add-data 'pricesLamb.csv;.' 'bottle_app.py'
And here is the structure of my application
bottle_app.py
pricesBeef.csv
pricesLamb.csv
pricesHog.csv
views (folder)
->7 html files (inside views)
->css (folder inside of views)
->->css file (only inside of css folder)
->js (folder inside of views)
->->js file (only file inside of js folder)
I'm not getting any traceback errors, which is what's the weird part to me.
Not a direct answer but a workaround
Use --onedir instead of --onefile and simply use a shortcut to the executable. It will work without needing python already installed, even with .pdy files in the directory

flask.cli.NoAppException: Failed to find Flask application or factory in module "flaskr". Use "FLASK_APP=flaskr:name to specify one

I am building a python web application using flask and following tutorial from http://flask.pocoo.org/docs/1.0/tutorial/factory/ . I am running the flask from the parent directory but getting following error.
(venv) E:\python-code\python-web>flask run
* Serving Flask app "flaskr" (lazy loading)
* Environment: development
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 294-690-396
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [16/Mar/2019 13:10:43] "GET /hello HTTP/1.1" 500 -
Traceback (most recent call last):
File "e:\python-code\python-web\venv\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "e:\python-code\python-web\venv\lib\site-packages\flask\cli.py", line 95, in find_best_app
module=module.__name__
flask.cli.NoAppException: Failed to find Flask application or factory in module "flaskr". Use "FLASK_APP=flaskr:name to specify one.
127.0.0.1 - - [16/Mar/2019 13:10:43] "GET /hello?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [16/Mar/2019 13:10:43] "GET /hello?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [16/Mar/2019 13:10:43] "GET /hello?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [16/Mar/2019 13:10:43] "GET /hello?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [16/Mar/2019 13:10:44] "GET /hello?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [16/Mar/2019 13:10:44] "GET /hello?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
Please help.
I have tried Running Flask app from cli gives "no module named flaskr"
and
flask.cli.NoAppException: Failed to find application in module?
I have found my problem. I was missing return app as the last statement in my code. Sorry for confusion and apologies.
I got that error
flask.cli.NoAppException flask.cli.NoAppException: Failed to find
Flask application or factory in module "flaskr". Use
"FLASK_APP=flaskr:name to specify one.
I tried all answers, and it got resolved after I changed the function name from create_function to create_app
I followed the instructions just like the official tutorial said but still got the same error.
My problem was with the IDE that I was using ( Pycharm )
Even though I had an init.py file in the flaskr directory, it still wasn't considered as a package.
So I deleted the flaskr directory and created a "new package". Then just copy the code in the init.py and that'll solve the problem
is your application dir not named properly? for example, if you wrote FLASK_APP=flaskr but your project name is something else, you will get this error. Also, what is in your flaskr/flaskr/__init__.py file if the project is named flaskr like in the tutorial?
You can't name the FLASK_APP enviroment var as Flask.py. Try with another name please and try again.
No puedes poner el nombre de la variable de ambiente FLASK_APP como Flask.py. Prueba cambiando el nombre del archivo.
Depending on the OS you are using you need to export flaskr in your environment
For Linux and Mac:
export FLASK_APP=flaskr
export FLASK_ENV=development
flask run
For Windows cmd, use set instead of export:
set FLASK_APP=flaskr
set FLASK_ENV=development
flask run
For Windows PowerShell, use $env: instead of export:
$env:FLASK_APP = "flaskr"
$env:FLASK_ENV = "development"
flask run```

Whitenoise to serve static files locally

As described in their docs here, I am configured my application to serve static files locally.
The only problem I am facing is that I am unable to determine if it is django or whitenoise which is serving static files?
Steps which I followed:
pip install whitenoise # install whitenoise
pip install brotlipy # install brotlipy for compression
INSTALLED_APPS = [
# default django apps
'django.contrib.messages',
# REMOVE IN PRODUCTION
# See: http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
# other apps
]
# add white-noise middleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
# static files serving
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# other middlewares
]
# add staticfiles
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# run collecstatic
python manage.py collectstatic
# restart the server
python manage.py runserver
# This gives me following
[10/Apr/2018 12:12:40] "GET /static/debug_toolbar/css/print.css HTTP/1.1" 304 0
[10/Apr/2018 12:12:40] "GET /static/chartkick.js HTTP/1.1" 304 0
[10/Apr/2018 12:12:40] "GET /static/debug_toolbar/js/jquery_pre.js HTTP/1.1" 304 0
However, I expect something like this,
[10/Apr/2018 12:12:40] "GET /static/debug_toolbar/css/print.636363s6s.css HTTP/1.1" 304 0
[10/Apr/2018 12:12:40] "GET /static/chartkick.2623678s3cdce3.js HTTP/1.1" 304 0
[10/Apr/2018 12:12:40] "GET /static/debug_toolbar/js/jquery_pre.6276gdg3js8j.js HTTP/1.1" 304 0
How can I check if whitenoise is working and that it is serving static files?
Since it's been quite a while since you asked this question, I imagine you've found an answer by now. But if anyone else stumbles on it, I've found that Django won't serve static files if you have DEBUG=False. So if you have that setting and you're still seeing static, it's likely being done by whitenoise.

Problems with Django static files

I have downloaded this project and trying to make it work: http://sourceforge.net/p/etconf/git/ci/master/tree/
The problem is, after I managed to install all prerequisites, it runs, but does not load staticfiles. According to settings it should look for them in the /media directory, but however I tried to change MEDIA_ROOT, STATIC_URL and various different parameters in settings.py it shows in the console:
[09/Oct/2015 10:56:08] "GET /static/configurator/admin/css/base.css HTTP/1.1" 404 2281
[09/Oct/2015 10:56:08] "GET /static/configurator/configurator.css HTTP/1.1" 404 2275
[09/Oct/2015 10:56:08] "GET /static/configurator/prototype.js HTTP/1.1" 404 2263
[09/Oct/2015 10:56:08] "GET /static/configurator/configurator.js HTTP/1.1" 404 2272
What am I doing wrong? Maybe it's some sort of old bug or something (project is using python 2 and django 1.1)
I guess you missed to run below command after configuration:
python manage.py collectstatic
What I see is you get 404 error for static files which means that the files are not located where it is been searched for.

Django not picking up new changes

I'm running an old branch A from my GitHub repo, and Django is not picking up any of the static files. What's weird is that if I make any text changes to the templates, it doesn't pick those up either. I've tried refreshing the page, opening Chrome in Incognito, restarting the server, etc. -- nothing is working.
After running the development server in a different branch B, and switching back to this one, Django acted as if I was still running on branch B (got not 404 errors):
$ ./manage.py runserver
0 errors found
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[12/Sep/2012 23:25:48] "GET /interviews/ HTTP/1.1" 200 13295
But as soon as I restarted the server, it reverted to the un-changed version of branch A (none of the changes were picked up and no static files could be found):
$ ./manage.py runserver
Validating models...
0 errors found
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[12/Sep/2012 23:26:20] "GET /interviews/ HTTP/1.1" 200 13295
[12/Sep/2012 23:26:20] "GET /static/js/plugins.js HTTP/1.1" 404 2653
[12/Sep/2012 23:26:20] "GET /static/js/jquery-1.7.1.min.js HTTP/1.1" 404 2653
[12/Sep/2012 23:26:20] "GET /static/css/style.css?v=2 HTTP/1.1" 404 2653
[12/Sep/2012 23:26:20] "GET /static/js/script.js HTTP/1.1" 404 2653
Between the two branches, settings.py and the static folder are identical so I'm not even sure where to begin with troubleshotting.
DEBUG = True
Check this. Built-in Django dev server does not work with static files if DEBUG = False.

Categories

Resources