How can I import TemplateDoesNotExist in app engine (python)? - python

I can't believe I'm not able to find this, but this is quite simple:
from google.appengine.ext.webapp import template
try :
content = template.render(...)
except TemplateDoesNotExist:
content = ...
Then I don't know how to import TemplateDoesNotExist! Can anyone tell me its module path? Thanks!

TemplateDoesNotExist is defined in django.template However from what you are doing it appears your going down a deprecated path under Python 2.7 . If you have a look at the template.py you just imported from google.appengine.ext.webapp import template you will see the following deprecation warning.
_PYTHON27_DEPRECATION = (
'google.appengine.ext.webapp.template is deprecated. Please use another '
'templating system such as django.template or jinja2.')
You haven't said if your using python 2.5 or python 2.7 . If your starting a new project the recommendation from google is to use 2.7.

If you're using python 2.7 and importing template as
from google.appengine.ext.webapp import template
Then you can import the exception as
from google.appengine._internal.django.template import TemplateDoesNotExist
and then
try:
template.render(...)
except TemplateDoesNotExist:
# do something useful

Related

import error 'force_text' from 'django.utils.encoding'

I'm implementing a graphql solution using python, graphene and django and I'm getting the following import error:
Result: Failure Exception: ImportError: cannot import name 'force_text' from 'django.utils.encoding'
"/home/site/wwwroot/.python_packages/lib/site-packages/graphene_django/utils/utils.py", line 6, in <module> from django.utils.encoding import force_text
I'm not sure about the versions and whether I need to import an additional module.
My requirements.txt is like:
graphene>=2.1,<3
graphene-django>=2.1,<3
graphql-core>=2.1,<3
graphql-relay==2.0.1
django-filter>=2
Has someone had a similar problem and can look at the versions that I use?
Thanks
in django 4.0 we dont have force_text
https://docs.djangoproject.com/en/4.0/ref/utils/#module-django.utils.encoding
instead change force_text to force_str
linux:
YOUR_VENV/lib/PYTHON_VERSION/site-packages/graphene_django/utils/utils.py
windows:
YOUR_VENV/lib/site-packages/graphene_django/utils/utils.py
from django.utils.encoding import force_text
to
from django.utils.encoding import force_str
and
def _camelize_django_str(s):
if isinstance(s, Promise):
s = force_text(s)
return to_camel_case(s) if isinstance(s, six.string_types) else s
to
def _camelize_django_str(s):
if isinstance(s, Promise):
s = force_str(s)
return to_camel_case(s) if isinstance(s, six.string_types) else s
Based on answer given by #Osman.
The problem seems to be occuring with Django-4. Till the PR gets merged, probably this monkeypatching might work (not tested in prod):
import django
from django.utils.encoding import force_str
django.utils.encoding.force_text = force_str
Put this in entryfile. I kept it in settings.py for time being.
In Django version 4> just paste this snippet to your settinsg.py. Preferably on the top
import django
from django.utils.encoding import force_str
django.utils.encoding.force_text = force_str
"force_text" is removed from Django 4.0:
Features removed in 4.0
But graphene_django still uses "force_text" in utils.py.
utils.py:
from django.utils.encoding import force_text # Line 6
s = force_text(s) # Line 29
So you need to replace "force_text" with "force_str" as shown below:
utils.py:
from django.utils.encoding import force_str# Line 6
s = force_str(s) # Line 29
These are the paths to utils.py for Linux and Windows:
Linux:
<your_venv>/lib/<python_version>/site-packages/graphene_django/utils/utils.py
Windows:
<your_venv>/lib/site-packages/graphene_django/utils/utils.py
adding the following to the requirements.txt solved it:
django<=3
You can install graphene-django version 3.0.0b7
run the following command in your terminal:
pip install graphene-django==3.0.0b7
It's beta version, but i don't know why graphene-django 2.15 does'nt work, when patch note said they fixed issue since 2.8.1 version.
Thank's to #Behoston from this Github issue for this solution

Python : Flask importing a file from current directory, but subcategory

I'm struggling to import a folder that has many engines I need to use. I'm importing from main_file.py.
So I think I can use - from engines import qr_code_gen, but I need to import a class which is named _QRCode_ so I tried using - from .engines.qr_code_gen import _QRCode_, but it says "module engines was not found".
Structure:
Server/start.sh
Server/wsgi.py
Server/application/main_file.py
Server/application/engines/qr_code_gen.py
Server/application/engines/__init__.py
...
I used sys.path in main_file.py and I got -
['C:\Users\Dzitc\Desktop\winteka2',
'C:\Users\Dzitc\AppData\Local\Programs\Python\Python37\Scripts\flask.exe',
'c:\users\dzitc\appdata\local\programs\python\python37\python37.zip',
'c:\users\dzitc\appdata\local\programs\python\python37\DLLs',
'c:\users\dzitc\appdata\local\programs\python\python37\lib',
'c:\users\dzitc\appdata\local\programs\python\python37',
'C:\Users\Dzitc\AppData\Roaming\Python\Python37\site-packages',
'c:\users\dzitc\appdata\local\programs\python\python37\lib\site-packages',
'c:\users\dzitc\appdata\local\programs\python\python37\lib\site-packages\win32',
'c:\users\dzitc\appdata\local\programs\python\python37\lib\site-packages\win32\lib',
'c:\users\dzitc\appdata\local\programs\python\python37\lib\site-packages\Pythonwin']
Going from comments you can import engine package.
Try this then:
import engines
engines.qr_code_gen._QRCode_

ModuleNotFoundError: No module named 'googlemaps'

I am a newcomer to Django python programming. Now I am working on the server side. I want to use google maps API, my view.py is like this:
from django.shortcuts import render
from django.shortcuts import HttpResponse
from googlemaps import *
# Create your views
gmaps = googlemaps.Client(key='A')
def index(request):
if request.method=="GET":
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
return geocode_result
Also, I have already installed 'googlemaps' using pip. And when I import it in IDE, nothing goes wrong. But when I want to start the server to test the code, the server won't run and tells me ModuleNotFoundError: No module named 'googlemaps', I am confused that I have already downloaded it and added it in settings.py, importing in IDE also seems fine. But where I did wrong makes it fail to start the server?
Change from googlemaps import * to import googlemaps
What from googlemaps import * does is that it imports all the contents of the googlemaps module. import googlemaps imports the whole googlemaps module as a whole.
I got it working two different ways (assuming valid API key). Either:
from googlemaps import Client
gmaps = Client(key='A')
or:
from googlemaps import *
gmaps = Client(key='A')
Do either of these work for you?
If you're still having problems, there's a good chance it's related to your virtualenv (if using). Try running:
pip freeze
from command line and searching for the requisite library.
If you don't have an API key, you may of course want to consider using geopy. Last I checked, didn't require API key.
from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.geocode("175 5th Avenue NYC")

How do i set django setting to a file which is outside the django tree?

I have this python file tasks.py
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebProject.settings')
from django.contrib.auth.models import User
from logreg.models import ActivationCode
import datetime
def remove_users():
print 'hello worldddddddddddddddddddddddddddddddddd'
inactive_users = []
activation_codes = ActivationCode.objects.all()
for activation_code in activation_codes:
if datetime.datetime.date(activation_code.key_expires) < datetime.datetime.date(datetime.datetime.now()):
inactive_users.append(activation_code.user_id)
for inactive_user in inactive_users:
User.objects.filter(id=inactive_user).delete()
But this is in the root folder and when i try to execute it, it gives me the following error
File
"C:\Users\deybala1\AppData\Local\Continuum\Anaconda2\lib\site-packages\dj
ango\apps\registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
How do i fix this?
If you're creating any script that is using your django project, it is absolutely necessary to set path to settings of your project before any import from django or your project. And you're importing user model from django in 1st line and model from your project in second.
Also, you will need to call django.setup() first.
To fix that, move import os and setting path to django settings to the very beginning of your script, and put django.setup() just after that (with proper import), like this:
# first, set path to project settings
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebProject.settings')
import django
django.setup()
# now you can import anything else
from django.contrib.auth.models import User
from logreg.models import ActivationCode
import datetime
def remove_users():
print 'hello worldddddddddddddddddddddddddddddddddd'
inactive_users = []
activation_codes = ActivationCode.objects.all()
for activation_code in activation_codes:
if datetime.datetime.date(activation_code.key_expires) < datetime.datetime.date(datetime.datetime.now()):
inactive_users.append(activation_code.user_id)
for inactive_user in inactive_users:
User.objects.filter(id=inactive_user).delete()
Note that you're trying to add a settings module inside a script that already requires it.
Wouldn't it be easier if you add a specific django command? Thanks to it you'd be able to start your task with python manage.py --settings=<path_to_your_settings>.
Another tip:
Move every django import statement below
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebProject.settings')

Django Templatetags Import Error

I've been banging my head against this for a while, but can't seem to figure it out.
I've got an app with a set of custom template tags:
from django import template
from crowd.models import Payment, Project, ProjectCategory
register = template.Library()
#register.filter
def is_customer(user, project):
try:
return Payment.objects.filter(user=user, project=project).count() > 0
except:
return False
That throws:
'project_tags' is not a valid tag library: ImportError raised loading crowd.templatetags.project_tags: No module named models
The app tree looks like:
crowd/
-- __init__.py
-- models.py
templatetags/
-- __init__.py
-- project_tags.py
Importing from just models and crowd.models both give me the same error.
Traceback: here
Update
I was working on something unrelated when I noticed this was broken, so I reverted to an earlier, known working version of the project. Still the same problem, so I think Daniels answer about the PYTHONPATH is correct, however, how can I repair this?
>>> import sys
>>> sys.path
['/Users/****/Documents/dev/product/src/Product', ...]
The __init__.py's are all there all the way down, and crowd is in Product, so shouldn't it be on the path?
Update 2
I've done some investigating in the shell:
>>> from crowd.models import *
>>> from crowd.managers import *
>>> from crowd.constants import *
>>> from crowd.templatetags import *
>>> from crowd.templatetags import project_tags
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/Murph/Documents/dev/product/src/Product/crowd/templatetags/project_tags.py", line 4, in <module>
from crowd.forms import SearchForm
File "/Users/Murph/Documents/dev/product/src/Product/crowd/forms.py", line 5, in <module>
from crowd.models import Payment, Project, ProjectUpdate, GalleryPhoto
ImportError: No module named models
>>>
Still don't know why specifically that's failing, especially since the blanket import works.
Update 3
Took me a while to see that the shell command was giving a more useful message than the django one, which led to this:
Turns out it wasn't even related to project_tags directly, it just wasn't a very useful error message. The import in project_tags.py of:
from crowd.forms import SearchForm
was calling:
from crowd.models import Payment, Project, RewardLevel, ProjectUpdate, GalleryPhoto
in forms.py, which should have been:
from models import Payment, Project, RewardLevel, ProjectUpdate, GalleryPhoto
I'll add this as the answer when I can, apparently can't until 8 hours later.
Your crowd app itself is probably not on your Pythonpath. Either add it, or import from the project: from myproject.crowd.models import Foo, Bar.
Took me a while to see that the shell command was giving a more useful message than the django one, which led to this:
Turns out it wasn't even related to project_tags directly, it just wasn't a very useful error message. The import in project_tags.py of:
from crowd.forms import SearchForm
was calling:
from crowdfunder.models import Payment, Project, RewardLevel, ProjectUpdate, GalleryPhoto
in forms.py, which should have been:
from models import Payment, Project, RewardLevel, ProjectUpdate, GalleryPhoto

Categories

Resources