ModuleNotFoundError: No module named 'googlemaps' - python

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")

Related

How to solve Django app name conflict with external library

I made a big mistake by creating an app inside my Django project called requests that happened a long time ago and the system has already been running for years. now I need to use the requests library and it is being imported like import requests as mentioned in the documentation ... and of course whenever I do this import it imports my app instead of the library .. so how to solve this?
You can try importing the requests/__init__.py file directly as shown in docs: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly.
Example:
import sys
import importlib.util
module_name = 'requests'
# declare the full path to requests/__init__.py file below
module_path = '/path/to/virtualenv/site-packages/requests/__init__.py'
spec = importlib.util.spec_from_file_location(module_name, module_path)
requests = importlib.util.module_from_spec(spec)
sys.modules[module_name] = requests
spec.loader.exec_module(requests)
print(requests.post) # should not raise error

Trying to reuse code across multiple Flask servers, stuck on importing with errors "ModuleNotFoundError" or "ImportError"

My goal is to import code into three separate Flask servers. It's not going well. I am on python 3.10.4. I have read perhaps 10 different posts that say things like "put a __init__.py file in your folders" which I have done.
For context I'm not exactly new to Python but I've never learned the importing/module system properly.
I have three Flask servers that run scraping operations on different (but similar) websites. I need them to be separate for various reasons. Anyway, all three need to run the same procedure of getting an IP for a proxy from my proxy provider. For this I have some code:
# we don't need the details here so I snip it to save space
def get_proxy_ip(choice):
r = requests.get(download_list, headers={"Authorization": "Token " + token})
selected_proxy_ip = r.json()["results"][choice]["proxy_address"]
selected_proxy_port = r.json()["results"][choice]["port"]
print(selected_proxy_ip)
return selected_proxy_ip, selected_proxy_port
I want to use this function across all 3 of my Flask servers. Here are some various ways I've tried to import the code into one of the Flask servers:
scrapers/rentCanada/app.py
import requests
from flask import Flask, request, make_response
print("cats")
app = Flask(__name__)
print(__name__, __package__)
# from ..shared.ipgetter import get_proxy_ip
# from ..shared.checker import check_public_ip
# from scrapers.shared.ipgetter import get_proxy_ip
# from scrapers.shared.checker import check_public_ip
import shared.ipgetter as ipgetter
import shared.checker as checker
None of them work.
import shared.ipgetter as ipgetter yields:
cats
__main__ None
Traceback (most recent call last):
File "/home/rlm/Code/canadaAps/scrapers/rentCanada/app.py", line 10, in <module>
import shared.ipgetter as ipgetter
ModuleNotFoundError: No module named 'shared'
ModuleNotFoundError: No module named 'scrapers' yields: ModuleNotFoundError: No module named 'scrapers'
from ..shared.ipgetter import get_proxy_ip yields: ImportError: attempted relative import with no known parent package
At this point you need to see my folder structure.
/scrapers
..__init__.py
..setup.py
../rentCanada
.....__init__.py
.....app.py
../rentFaster
.....__init__.py
.....app.py
../rentSeeker
.....__init__.py
.....app.py
../shared
.....__init__.py
.....ipgetter.py
.....checker.py
I need to be able to use any of the app.py files as entry points.
I also tried setup.py with this:
from setuptools import setup, find_packages
setup(
name = 'tools',
packages = find_packages(),
)
followed by python setup.py install but that didn't make a "tools" import available in app.py like I wanted.
As a final note I suspect someone will tell me to use a blueprint. To me those look like a tool I'd use if I was adding a route. I'm not sure they're right for a simple function, but maybe I'm wrong.
My solution for now is to run Flask with python rentCanada/app.py from the /scrapers folder and use this code
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent)) # necessary so util folder is available
import requests
from flask import Flask, request, make_response
print("cats")
app = Flask(__name__)
print(__name__, __package__)
from util.ipgetter import get_proxy_ip
from util.checker import check_public_ip
So the program appends the app.py file folder's parent folder to the path. That makes the util folder (which used to be shared but had a naming conflict) available within the app.py file.

How to use Azure-Python SDK `ResourcesMoveInfo` class in python

I came across this python class ResourcesMoveInfo for moving resources(Azure Images) from one subscription to another with Azure python SDK.
But it's failing when I use it like below:
Pattern 1
reference from https://buildmedia.readthedocs.org/media/pdf/azure-sdk-for-python/v1.0.3/azure-sdk-for-python.pdf
Usage:
metadata = azure.mgmt.resource.resourcemanagement.ResourcesMoveInfo(resources=rid,target_resource_group='/subscriptions/{0}/resourceGroups/{1}'.format(self.prod_subscription_id,self.resource_group))
Error:
AttributeError: module 'azure.mgmt.resource' has no attribute 'resourcemanagement'
Pattern 2
reference from - https://learn.microsoft.com/en-us/python/api/azure-mgmt-resource/azure.mgmt.resource.resources.v2019_07_01.models.resourcesmoveinfo?view=azure-python
Usage:
metadata = azure.mgmt.resource.resources.v2020_06_01.models.ResourcesMoveInfo(resources=rid,target_resource_group='/subscriptions/{0}/resourceGroups/{1}'.format(self.prod_subscription_id,self.resource_group))
Error:
AttributeError: module 'azure.mgmt.resource.resources' has no attribute 'v2020_06_01'
Any help on this requirement/issue would be helpful. Thanks!
Adding code snippet here:
import sys
import os
import time
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
import azure.mgmt.resource
#from azure.mgmt.resource.resources.v2020_06_01.models import ResourcesMoveInfo
from azure.identity import ClientSecretCredential
from cred_wrapper import CredentialWrapper
class Move():
def __init__(self):
self.nonprod_subscription_id = "abc"
self.prod_subscription_id = "def"
self.credential = ClientSecretCredential(
client_id= os.environ["ARM_CLIENT_ID"],
client_secret= os.environ["ARM_CLIENT_SECRET"],
tenant_id= os.environ["ARM_TENANT_ID"]
)
#resource client for nonprod
self.sp = CredentialWrapper(self.credential)
self.resource_client = ResourceManagementClient(self.sp,self.nonprod_subscription_id)
self.resource_group = "imgs-rg"
def getresourceids(self):
resource_ids = list(resource.id for resource in self.resource_client.resources.list_by_resource_group("{0}".format(self.resource_group)) if resource.id.find("latest")>=0)
return resource_ids
def getresourcenames(self):
resource_names = list(resource.name for resource in self.resource_client.resources.list_by_resource_group("{0}".format(self.resource_group)) if resource.id.find("latest")>=0)
return resource_names
def deleteoldimages(self,name):
#resource client id for prod
rc = ResourceManagementClient(self.sp,self.prod_subscription_id)
for resource in rc.resources.list_by_resource_group("{0}".format(self.resource_group)):
if resource.name == name:
#2019-12-01 is the latest api_version supported for deleting the resource type "image"
rc.resources.begin_delete_by_id(resource.id,"2020-06-01")
print("deleted {0}".format(resource.name))
def moveimages(self):
rnames = self.getresourcenames()
for rname in rnames:
print(rname)
#self.deleteoldimages(rname)
time.sleep(10)
rids = self.getresourceids()
rid = list(rids[0:])
print(rid)
metadata = azure.mgmt.resource.resources.v2020_06_01.models.ResourcesMoveInfo(resources=rid,target_resource_group='/subscriptions/{0}/resourceGroups/{1}'.format(self.prod_subscription_id,self.resource_group))
#moving resources in the rid from nonprod subscription to prod subscription under the resource group avrc-imgs-rg
if rid != []:
print("moving {0}".format(rid))
print(self.resource_client.resources.move_resources(source_resource_group_name="{0}".format(self.resource_group),parameters=metadata))
#self.resource_client.resources.move_resources(source_resource_group_name="{0}".format(self.resource_group),resources=rid,target_resource_group='/subscriptions/{0}/resourceGroups/{1}'.format(self.prod_subscription_id,self.resource_group))
#self.resource_client.resources.begin_move_resources(source_resource_group_name="{0}".format(self.resource_group),parameters=metadata)
if __name__ == "__main__":
Move().moveimages()
From your inputs we can see that the code looks fine. From your error messages, the problem is with importing the modules.
Basically when we import a module few submodules will get installed along with and few will not. This will depend on the version of the package, to understand which modules are involved in a specific version we need to check for version-releases in official documentation.
In your case, looks like some resource modules were missing, if you could see the entire error-trace, there will be a path with sitepackages in our local. Try to find that package and its subfolder(Modules) and compare them with Azure SDK for Python under Resource module, you can find this here.
In such situation we need to explicitly add those sub modules under our package. In your case you can simple download the packaged code from Git link which I gave and can merge in your local folder.

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_

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