KeyError: 'Unable to find stateless DjangoApp called app' - python

Why the DjangoApp app can't be found?
Given result
After executing manage.py runserver in the console Django is starting properly but in case I'm calling http://127.0.0.1:8000/dash_simple/app1/ a KeyError was thrown:
Django Version: 3.1.3
Exception Type: KeyError
Exception Value:
'Unable to find stateless DjangoApp called app'
Expected result
After executing manage.py runserver in the console Django is starting properly and the related page is shown for http://127.0.0.1:8000/dash_simple/app1/
dash_test/urls.py
urlpatterns = [
path('dash_simple/', include ('dash_simple.urls')),
]
dash_test/settings.py
INSTALLED_APPS = [
'dash_simple.apps.DashSimpleConfig',
]
dash_test/dash_simple/apps.py
class DashSimpleConfig(AppConfig):
name = 'dash_simple'
dash_simple/urls.py
urlpatterns = [
path('', views.home, name='home'),
path('app1/', views.app, name='app')
]
dash_simple/views.py
def home(request):
return render(request, template_name='dash_simple/home.html')
def app(request):
return render(request, template_name='dash_simple/app1.html')
dash_simple/templates/dash_simple/app1.html
{% load plotly_dash %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>App 1</title>
</head>
<body>
<H1>I'm App 1</H1>
<p>
{% plotly_app name="app" %}
</p>
</body>
</html>

Faced similar issue. In dash_simple/urls.py you need to import your dash application i.e.:
from dash_simple import your_dash_script_file_name
As simple as that!

For future reference. In my case getting 'Unable to find stateless DjangoApp called "AppName"'. For one of my plotly app it worked and for the other one i did not. I started verifying what one off them had and the other not.
After some hours i noticed this set of imports i made few days ago on the /views of the app that was serving the html template that showed the plot, while setting the first.
from plotly.offline import plot
import plotly.graph_objs as go
from .plot import *
I copied this to the other app that rendered had the view of the second plot. but the compilation failed because the 3rd import was not being found. Because of this i went into the reference of the import in the first plot and it was the module that had all the code of the first plot, so i changed the last import on the views of the django app that rendered my second plot
Basically. My solution was to also do the three imports on the views of the django app that is rendering the html that contains the plot and change the last line to import the script/module of the dash plotly app that i'm looking to render.

Related

Django/Flask : Rewritting an Flask Azure B2C authentication in Django

I want to use and Azure B2C authentication in Django, however there is no tutorial in Django for it but in Flask. However I never coded in Flask.
I used the documentation/tutorial of microsoft that share a github with the flask code to do it :
https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample-python-web-app?tabs=windows
https://github.com/Azure-Samples/ms-identity-python-webapp
I try to convert it in Django however I have an error that I do not understand ! The error message :
Internal Server Error: /login/
TypeError: Object of type HttpResponseRedirect is not JSON serializable
Here is the code
views.py
def index(request) :
if not request.session.get("user"):
return redirect("login")
return render('index.html', user=request.session["user"] )
def login(request):
# Technically we could use empty list [] as scopes to do just sign in,
# here we choose to also collect end user consent upfront
request.session["flow"] = _build_auth_code_flow(scopes=list(json.loads(os.getenv("SCOPE"))))
return render(request, "login.html", {'auth_url' : request.session["flow"]["auth_uri"]})
def authorized(request):
try:
cache = _load_cache(request=request)
result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow(
request.session.get("flow", {}), request.args)
if "error" in result:
return render("auth_error.html", result=result)
request.session["user"] = result.get("id_token_claims")
_save_cache(cache=cache, request=request)
except ValueError: # Usually caused by CSRF
pass # Simply ignore them
return redirect("index")
def _load_cache(request):
cache = msal.SerializableTokenCache()
if request.session.get("token_cache"):
cache.deserialize(request.ession["token_cache"])
return cache
def _save_cache(cache, request):
if cache.has_state_changed:
request.session["token_cache"] = cache.serialize()
def _build_msal_app(cache=None, authority=None):
return msal.ConfidentialClientApplication(
os.getenv("CLIENT_ID"), authority=authority or os.getenv("AUTHORITY"),
client_credential=os.getenv("CLIENT_SECRET"), token_cache=cache)
def _build_auth_code_flow(authority=None, scopes=None):
return _build_msal_app(authority=authority).initiate_auth_code_flow(
scopes or [],
redirect_uri=redirect('authorized'))
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Microsoft Identity Python Web App</h1>
<li><a href='{{ auth_url }}'>Sign In</a></li>
<footer style="text-align: right">Powered by MSAL Python {{ version }}</footer>
</body>
</html>
urls.py
from django.urls import path
from . import views
import os
from dotenv import load_dotenv
load_dotenv()
urlpatterns = [
path('index/', views.index, name="index"),
path('login/', views.login, name="login"),
# path(f'{os.getenv("REDIRECT_PATH")}/', views.login, name="authorized"),
path('getAToken/', views.login, name="authorized")
]
Did I do something wrond in the conversion to Django ?
Where does this error come from ? Is it something to set in the azure bc2 ?
Not the required answer (adopting the Flask solution for DJango), but your're right, there are no examples of using Django for aadb2c auth...
What I did, is used "mozilla-django-oidc" which fits well the azure oidc authentification..
More details are here:
https://stackoverflow.com/a/74156780/592737

`app.route` and `template_render` not working in Flask

I'm learning Flask and I created two routes :
"/about" : was routing a template as render.template(about.html)
"/aksh" : was routing a template as render.template(index.html)
It worked for index.html and not about.html and when I made changes in index.html and refreshed nothing happened.
I tried restarting everything including my system.
Then I commented that route "/aksh" but too much of my surprise portaddress/about was showing no url found whereas portaddress/aksh was still showing the text .
After that I re-edited whole code , now in new code there are 3 routes :
"/" : return a print statement "Hello World!"
"/aksh" : render a template index.html
"/about" : render a template about.html
But this has made no change now also I'm getting old results the new routes are not getting updated.
My python code is :
from flask import Flask,render_template
app=Flask(__name__)
#app.route("/")
def hello():
return "Hello World"
#app.route("/aksh")
def aksh():
return render_template('index.html')
#app.route("/about")
def about():
return render_template('about.html')
app.run(debug=True)
HTML codes for index and about are :
index.html :
<html>
<head>
<meta charset="utf-8">
<title>Title of my page</title>
</head>
<body>
<p>We are testing flask app here</p>
</body>
</html>
For about.html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>About this page</title>
</head>
<body>
<h1>This is about section</h1>
</body>
</html>
Its showing "we are testing app" but it must be "we are testing app here " and moreover its in wrong location it must be in route "/aksh" not "/"
Use separators to solve this problem.
from flask import Flask,render_template
app=Flask(__name__)
#app.route("/")
def hello():
return "Hello World"
#app.route("/aksh")
def aksh():
return render_template('index.html')
#app.route("/about")
def about():
return render_template('about.html')
app.run(debug=True)
Finally I managed to solve this issue .
The problem was 1st I runned this code via PyCharm and then by Python interpreter IDLE (obviously after closing pyCharm) and somehow PyCharm was still controlling the server even after system restart .
So after checking everything and getting now clue I just powered off my system completely and started again and then run the application via IDLE only thus solving all issue !
So the conclusion was :
->PyCharm was still controlling the server even after system restart.
->Power off and on solved the issue for me .
Sounds weird but that's how it worked .
If anyone here can explain why PyCharm was still controlling servers even after restart would be better .

Python 3.8.5 Flask giving internal server error with WSGI application when template is called using render_template in VS Code - 500 server error [duplicate]

This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 2 years ago.
I have been following a YouTube tutorial made by Corey Schafer using Flask. I have reached the 2nd tutorial about using html templates, but that is the only place I have reached. This is the program I am running called hello.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
app.run()
This is the HTML file I have been using, called home.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask Template Example</title>
</head>
<body>
<div>
<p>{{ message }}</p>
</div>
</body>
</html>
Whenever I try to run my code, I always get the error jinja2.exceptions.TemplateNotFound: template.html. I've tried to look at all possible solutions, but none have seemed to work. How could I fix this? I'm on a Windows 64-bit machine.
By default un Flask, the template folder is templates/. If home.html is in the same directory as app.py, you need to set template_folder.
Here is how to fix your app.py:
from flask import Flask, render_template
app = Flask(__name__, template_folder='./')
#app.route('/')
def home():
return render_template('home.html')
app.run()
To use the default template location (which is recommended), this is the file structure you would need to have:
app.py
templates
└── home.html

Django 1.11 404 Page while Debug=True

Without making things difficult, I just want to show a special 404 render with staticfiles.
If you set DEBUG = False you can use in urls.py
handler404 = 'app.views.handler404'
But it is without staticfiles. I don't want to install a web server for a simple app.
With DEBUG = True in urls
url(r'^404/$', views.handler400)
is not overriding the default Page not found (404) page.
What is the easy way to achieve a render e.g. when you type localhost/asdfhjfsda with staticfiles when DEBUG=True?
Thanks in advance...
Easiest way to do this post Django 1.9 is in your urls.py:
from django.views.defaults import page_not_found
url(r'^404/$', page_not_found, {'exception': Exception()})
It wants an exception, give it an exception :)
In django 1.10 docs:
Changed in Django 1.9:
The signature of page_not_found() changed. The function now accepts a second parameter, the exception that triggered the error. A useful representation of the exception is also passed in the template context.
Have a look at your 'app.views.handler404' definition, it might miss a parameter, and maybe it's that why the r'^404/$'handler doesn't provide you with the correct method invocation.
I have a complete solution
My development environment:
Windows 7, Python 3.5.2, Django 1.11, WAMP 3.0.6 (Apache 2.4.23, mod_wsgi)
Suppose you have error_404.html template with static files
Create next directory structure ("mysite" - Django project root folder)
mysite\
mysite\
settings.py
urls.py
views.py
static\
error404\
files\
style.css
image.jpg
templates\
error404\
error_404.html
mysite\mysite\settings.py
import os
DEBUG = False
TEMPLATES = [{
..
'DIRS': [os.path.join(BASE_DIR, 'templates')],
..
}]
STATIC_URL = '/static/'
STATIC_ROOT = 'FullPathToYourSite.com/mysite/static/'
mysite\mysite\urls.py
from django.conf.urls import handler404, handler500
from . import views
urlpatterns = [..]
handler404 = views.error_404
handler500 = views.error_404
mysite\mysite\views.py
from django.shortcuts import render
def error_404(request):
return render(request, 'error404/error_404.html')
Some Jinjo logic in "error_404.html" (pseudocode)
{% load staticfiles %}
...
link type="text/css" href="{% static 'error404/files/style.css' %}"
...
img src="{% static 'error404/files/image.jpg' %}"
...

Django-Twilio sending SMS on button click

OK possible noob question here: While learning Django, I thought it might be cool to explore telephony with Twilio. My immediate goal is to create a page with a button that, when clicked, causes a "Hello World" SMS to be sent to my phone. After sorting that out I have some ideas for cooler stuff.
I've completed several Django tutorials so far, and made a few little apps with simple views. But nothing I've learned has particularly shed any light on how to do something like this. I've also investigated (and installed) the Django-Twilio app and the Twilio Python Helper Library, but the docs for neither of these show how to send "hello world" SMS's.
Can anyone point out a resource that might show how to do this? Or, if it's trivially easy, just post some example code?
Edit in response to Kevin Burke:
Thanks for getting back to me, Kevin.
After modifying my urls.py to include:
urlpatterns = patterns('',
# ...
url(r'^sms/$', 'django_twilio.views.sms', {
'message': 'Hello world',
'to': '+12223334444',
'sender': '+18882223333',
'status_callback': '/sms/completed/',
}, name = 'send_message'),
# ...
)
and pointing my browser at
http://127.0.0.1:8000/sms/
the following error arises:
Exception Type: TwimlException at /sms/
Exception Value: Invalid method parameter, must be 'GET' or 'POST'
Perhaps this is because I have failed to make appropriate modifications to the view. But I don't have a good way of figuring out what I'm doing wrong from the minimal examples in the tutorial.
/Edit
twilio employee here.
The problem here is that the built in views for django_twilio run through a series of validation checks to make sure they're receiving content from twilio.com and only twilio.com. This is a security measure built into django-twilio.
There are two things you can do:
Make sure your settings.DEBUG = True in your Django settings, this will turn off the validation. You can then send a cURL request on your local machine whilst it is running like this in your terminal:
$ curl http://localhost:8000/sms/
This should return some TWiML like so:
<Response><Sms>Hello world</Sms></Response>
When you're running this online and you want to do to test this, set up your twilio number to point to http://mywebsite.com/sms/ and text the number. Ensure that settings.DEBUG = False and you should get back a message.
If you have anymore problems, let me know.
Here's the official docs: django-twilio official docs. More specifically, read this part about sending SMS: Sending sms messages
Here is a simple solution :
django startproject projectname
urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('message_api.urls')),
]
settings.py
TWILIO_ACCOUNT_SID = TWILIO_ACCOUNT_SID
TWILIO_AUTH_TOKEN = TWILIO_AUTH_TOKEN
DJANGO_TWILIO_FORGERY_PROTECTION = False
DJANGO_TWILIO_BLACKLIST_CHECK = True
Start new application
python manage.py startapp appname
Inside the app folder:`
urls.py
from django.conf.urls import url
import django_twilio
from . import views
urlpatterns = [
url(r'^api/$', views.home),
url(r'^send/', views.sms),
]
views.py
from django.shortcuts import render
from twilio.rest import Client
from twilio_api import settings
def home(request):
return render(request, 'index.html', {})
def sms(request):
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
message = client.messages.create(to='TO NUMBER', from_='YOUR TWILIO NUMBER', body='This message is sent through twilio api using django framework by akshat.')
print(message.sid)
return render(request, 'thankyou.html')
Make a templates directory inside your app folder
index.html
<body>
<button class="btn btn-outline-primary">Send Message</button>
</body>
thankyou.html
<body>
<h1>Success</h1>
</body>
`

Categories

Resources