Python: 'module' object has no attribute 'getuid' - python

I am trying to write my first django webapp, and it work fine with a simple view but as soon as I include my model, it starts to give the following error
'module' object has no attribute 'getuid'
Request Method: POST
Request URL: http://localhost:8080/photos/
Django Version: 1.2.5
Exception Type: AttributeError
Exception Value:
'module' object has no attribute 'getuid'
Exception Location: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py in expanduser, line 321
Python Executable: /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python
I read that this might be because of circular import issue but I dont see anything in my model imports.
import logging
import sys
import os
import flickrapi
def get_photos_for_artist(artist=None):
if not artist:
logging.error('can not find photos for unknown artist')
return None
api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
flickr = flickrapi.FlickrAPI(api_key)
gen = flickr.walk(tags=artist, content_type=1, per_page=10)
return gen
def main():
pass
if __name__ == '__main__':
main()
What could be causing this?
Django Logs say :
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py in expanduser
return path
i = path.find('/', 1)
if i < 0:
i = len(path)
if i == 1:
if 'HOME' not in os.environ:
import pwd
userhome = pwd.getpwuid(os.getuid()).pw_dir ...
else:
userhome = os.environ['HOME']
else:
import pwd
try:
pwent = pwd.getpwnam(path[1:i])

Try to check version of python and check python installation and PYTHONPATH variable. May be problim with enveroment, not code.

Related

FastAPI - Use TestClient - Loading app fails to missing ENV Variables

I have the following main.py:
...
app = FastAPI(docs_url="/jopapi/documentation", redoc_url=None)
password_encryptor = PasswordEncryptor(
os.environ.get("JUPYTERHUB_COOKIE_SECRET"), fernet=Fernet
)
...
I already tried to use a custom fixture like this:
#mock.patch.dict(os.environ, {"JUPYTERHUB_COOKIE_SECRET": "471bAcmHjbIdu3KLWphYpgXSW1HNC8q7"}, clear=True)
#pytest.fixture(name="client")
def client_fixture():
client = TestClient(app)
yield client
But the following test:
def test_generic(client: TestClient):
response = client.get("/jobapi/generic")
assert response.status_code == 200
still fails, since the environment variable seems not to get set, which results in None
from src.app.main import app
src\app\main.py:38: in <module>
password_encryptor = PasswordEncryptor(
src\app\auth.py:33: in __init__
self.fernet = fernet(self._generate_fernet_key(self.secret))
src\app\auth.py:36: in _generate_fernet_key
bytestring = secret.encode()
E AttributeError: 'NoneType' object has no attribute 'encode'
When I set the env variable in the main.py file per hand, it works. How can I fix this?
I think you need to create a .env at the root of your project and then read that file using python's dotenv, so finally you can easily use it with os.environ.get() later in your main.py file,
.env
JUPYTERHUB_COOKIE_SECRET=471bAcmHjbIdu3KLWphYpgXSW1HNC8q7
main.py
import os
basedir = path.abspath(path.dirname(__file__))
load_dotenv(path.join(basedir, ".env"))
app = FastAPI(docs_url="/jopapi/documentation", redoc_url=None)
password_encryptor = PasswordEncryptor(
os.environ.get("JUPYTERHUB_COOKIE_SECRET"), fernet=Fernet
)

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.

AttributeError: 'module' object has no attribute 'ZKLib'

I'm trying to connect to biometric device. I have installed 'Zklib' using (Pip). My code as follows
`import sys
import zklib
import time
from zklib import zkconst
zk = zklib.ZKLib("192.168.0.188", 4370)
ret = zk.connect()
print "connection:", ret`
When I execute this, I get an error
AttributeError: 'module' object has no attribute 'ZKLib'
Help me to run this code successfully.
Try the following instead:
import sys
import time
from zklib import zklib, zkconst
zk = zklib.ZKLib("192.168.0.188", 4370)
ret = zk.connect()
print "connection:", ret
The ZKlib class is in zklib.zklib not zklib. It appears that there is a typo in the Getting Started section of their GitHub page (or they expect you to be in the zklib directory when running your code?).

unicode is not defined error - flask-flatpages and python 3

I installed Flask-FlatPages and am trying to run this simple app (to display .md files):
import sys
from flask import Flask, render_template
from flask_flatpages import FlatPages, pygments_style_defs
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FLATPAGES_ROOT = 'content'
POST_DIR = 'posts'
app = Flask(__name__)
flatpages = FlatPages(app)
app.config.from_object(__name__)
#app.route("/posts/")
def posts():
posts = [p for p in flatpages if p.path.startswith(POST_DIR)]
posts.sort(key=lambda item:item['date'], reverse=False)
return render_template('posts.html', posts=posts)
#app.route('/posts/<name>/')
def post(name):
path = '{}/{}'.format(POST_DIR, name)
post = flatpages.get_or_404(path)
return render_template('post.html', post=post)
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Whenever I run the app, I get this error:
NameError: name 'unicode' is not defined
The trackback (flask-flatpages) is this:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/flask_flatpages/__init__.py", line 290, in _pages
_walk(unicode(self.root))
I know unicode is now str in Python 3 -- can I fix the issue from my app (without modifying the package)?
Well if the package does not support Python 3, then you cannot easily make it work. You can wait for support or find alternative package. If the only problem is missing definition for unicode, then it can be monkeypathed like
import builtins
builtins.unicode = str
before importing flask_flatpages. But I doubt missing unicode is the only problem.

name 'grinder' is not defined when using Grinder

Grinder is new for me and I am trying to figure out how to get rid of this error:
my test.py script:
import string
import random
from java.lang import String
from java.net import URLEncoder
from net.grinder.plugin.http import HTTPRequest
from net.grinder.common import GrinderException
log = grinder.logger.info
stat = grinder.statistics.forLastTest
SERVER = "http://www.google.com"
URI = "/"
class TestRunner:
def __call__(self):
requestString = "%s%s" % (SERVER, URI)
request = HTTPRequest()
result = request.GET(requestString)
if string.find(result.getText(), "SUCCESS") < 1:
stat.setSuccess(0)
I run
java net.grinder.Console
java net.grinder.Grinder
in my localhost.
after starting the test, this message keeps popping up:
aborting process - Jython exception, <type 'exceptions.NameError'>: name 'grinder' is not defined [initialising test script]
net.grinder.scriptengine.jython.JythonScriptExecutionException: <type 'exceptions.NameError'>: name 'grinder' is not defined
log = grinder.logger.info
File "./test.py", line 8, in <module>
It looks like I have to include some Grinder module for this "grinder.logger.info" but I just have no clue of what I should import... ...
Any hint?
Thanks in advance
you imported items from grinder, not grinder itself, try
import grinder.logger.info
import grinder.statistics.forLastTest
it might also be net.grinder.logger.info and net.grinder.statistics.forLastTest if this is the case then your code will need changing to go with the change from grinder to net.grinder
You have not imported grinder.
from net.grinder.script.Grinder import grinder
and now try again.

Categories

Resources