I am facing a problem in python. Tho the error is quite common, but since i am bit new to python, unable to comprehend the source hence asking you all. There are 2 modules: session.py and objects.py.
session.py
import copy
import pymongo
import spacy
import tweepy
import objects
objects.py:
import re
def refresh (sv = sv, obj = ''):
return 0
now, in python shell, i am getting the error before even executing objects.py:
$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import session
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "session.py", line 6, in <module>
import objects
File "objects.py", line 3, in <module>
def refresh (sv = sv, obj = ''):
NameError: name 'sv' is not defined
>>>
I came from perl background to maybe missing some very common thing, but still i am able to do this:
>>> def ff(t): print t
...
In above, whitout defining t, it is working while in objects.py, how can i define sv without starting execution?
Related
https://security.openstack.org/guidelines/dg_using-file-paths.html
If I try to run the given code from the above link:
import os
def is_safe_path(basedir, path, follow_symlinks=True):
# resolves symbolic links
if follow_symlinks:
matchpath = os.path.realpath(path).startswith(basedir)
else:
matchpath = os.path.abspath(path).startswith(basedir)
return basedir == os.path.commonpath((basedir, matchpath))
is_safe_path('/test', '/test/../abc')
It clearly does not work:
$ python
Python 3.8.8 (default, Mar 4 2021, 21:24:42)
[GCC 10.2.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> def is_safe_path(basedir, path, follow_symlinks=True):
... # resolves symbolic links
... if follow_symlinks:
... matchpath = os.path.realpath(path).startswith(basedir)
... else:
... matchpath = os.path.abspath(path).startswith(basedir)
... return basedir == os.path.commonpath((basedir, matchpath))
...
>>> is_safe_path('/test', '/test/../abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in is_safe_path
File "/usr/lib/python3.8/posixpath.py", line 496, in commonpath
paths = tuple(map(os.fspath, paths))
TypeError: expected str, bytes or os.PathLike object, not bool
What's the spurious bit of code here?
Should the .startswith() be removed?
Am I totally misunderstanding what the purpose of having a boolean in the tuple is?
I found the edit where this was changed:
https://bugs.launchpad.net/ossa/+bug/1815422
https://review.opendev.org/c/openstack/ossa/+/771854/
This is a typo in the code, .startswith(basedir) isn't meant to follow realpath or abspath. Most likely a copy and paste issue to be honest. I would highly recommend that you submit a fix for the issue!
In my Django project, I have a models.py that looks like this:
from django.db import models
class Battle(models.Model):
def __str__(self):
return self.battle_name
battle_name = models.CharField(max_length=200)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
password = models.CharField(max_length=50)
When I drop to the Django shell (python manage.py shell), I can't interact either of the DateTimeField properties.
$ python manage.py shell
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from battles.models import Battle
>>> Battle.objects.all()
<QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]>
>>> Battle.objects.filter(battle_name='my first battle')
<QuerySet [<Battle: my first battle>]>
>>> import datetime
>>> Battle.objects.filter(end_time<datetime.datetime.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
>>> Battle.objects.filter(end_time < datetime.datetime.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
Am I missing something?
Let me add a bit of explanation..
Battle.objects.filter(end_time < datetime.datetime.now())
here filter() is a callable that accepts arguments (args or kwargs). With the above code you are trying to pass a boolean value (object < object) to the filter callable as argument. Now, does a boolean value True or False specify anything about a model field?
What you should be doing is pass a keyword argument, namely
Battle.objects.filter(end_time__lt=datetime.datetime.now())
Now the filter() gets the info it needs, the kwarg parameter end_time__lt (which specifies the model field along with the compare method) and the value that needs to be compared with datetime.datetime.now()
You make syntax error
Try this
Battle.objects.filter(end_time__lt=datetime.datetime.now())
To do
import itertools
dynamically, I can do the following
import importlib
importlib.import_module('itertools')
But what should I do to do the following dynamically
import itertools as iters
Problem Context:
I need to import a different version (0.10) of a module('pika' in my case), installed in a separate directory instead of default version(0.9).
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python !!
>>> import importlib
>>> import pika
>>> pika.__version__
'0.9.14'
>>> import scale.lib.hypervisor.esx65.pika_3_5 as pika35
>>> pika35.__version__
'0.10.0'
>>> importlib.import_module('scale.lib.hypervisor.esx65.pika_3_5')
<module 'scale.lib.hypervisor.esx65.pika_3_5' from 'scale/lib/hypervisor/esx65/pika_3_5/__init__.pyc'>
As we can see regular imports are working fine. However when importing dynamically, importing relative to the location is causing issues. As per importlib.import_module documentaion , following should work but it doesn't.
>>> importlib.import_module('pika_3_5', 'scale.lib.hypervisor.esx65')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named pika_3_5
And when trying to import 'pika' from a relative path, which should fail as there is no module pika under the relative path, it is still importing it from default module.
>>> importlib.import_module('pika', 'scale.lib.hypervisor.esx65.pika_3_5')
<module 'pika' from '/usr/local/lib/python2.7/dist-packages/pika/__init__.pyc'>
>>>
What is it that I am missing ? I mainly want to do the following dynamically.
import scale.lib.hypervisor.esx65.pika_3_5 as pika
To do
import itertools
dynamically, I can do the following
import importlib
importlib.import_module('itertools')
No, you do the following:
import importlib
itertools = importlib.import_module('itertools')
Similarly, to replicate import itertools as iters, you do
import importlib
iters = importlib.import_module('itertools')
importlib.import_module doesn't care what you call the module. as is not and cannot be part of importlib.import_module's functionality. It just gives you the module object; what you call that object is up to you.
As for your context, you've misunderstood what a relative import is. The second argument to importlib.import_module has nothing to do with from imports, and importlib.import_module('thing', 'whatever') is not supposed to be equivalent to from whatever import thing.
If you want to do
import scale.lib.hypervisor.esx65.pika_3_5 as pika
that's pika = importlib.import_module('scale.lib.hypervisor.esx65.pika_3_5'). The second argument doesn't enter the picture. You seem to think this is somehow not dynamic, but it's as dynamic as any other importlib call.
I wrote a Python module which is just two methods, help and check. Check just takes a string file name and does something with it. When I import the module, there are no methods in it. Only __name__ and the like, but neither check nor help appears in the dir.
I am just importing the file. lyricCheck.py
Here's my code in lyricCheck.py:
#!/usr/bin/python
#python lyric checker
#Jim Boulter
#January 19, 2015
#Copyright 2015
import sys
import urllib2
import fileinput
from decimal import *
from re import *
from pygoogle import pygoogle
def help():
print 'usage: python check.py filename.txt\n'
print 'input line structure: artist name; song title\n'
def check(filename):
if(str(filename).lower == "help" or str(filename).lower == "-h"):
help()
return
#do lots of other stuff
If you are creating your package like this, and I believe you are, you need to import your module from your package:
~/tmp$ mkdir lyricCheck
~/tmp$ cd lyricCheck/
~/tmp/lyricCheck$ touch __init__.py
~/tmp/lyricCheck$ cat > lyricCheck.py
#!/usr/bin/python
#python lyric checker
#Jim Boulter
#January 19, 2015
#Copyright 2015
import sys
import urllib2
import fileinput
from decimal import *
from re import *
from pygoogle import pygoogle
def help():
print 'usage: python check.py filename.txt\n'
print 'input line structure: artist name; song title\n'
def check(filename):
if(str(filename).lower == "help" or str(filename).lower == "-h"):
help()
return
#do lots of other stuff
~/tmp/lyricCheck$ cd ..
~/tmp$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lyricCheck
>>> dir(lyricCheck)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
Here's my payoff, and this should have worked if I had pygoogle, so this is how I know I found the issue:
>>> from lyricCheck import lyricCheck
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lyricCheck/lyricCheck.py", line 12, in <module>
from pygoogle import pygoogle
ImportError: No module named pygoogle
You can put this in your __init__.py file to import the functions from the lower level module and make them available right at the package level:
from lyricCheck import help, check
Also note, when you do this:
from decimal import *
from re import *
You dump all the names in those modules into your module's namespace. It's generally considered better to declare them individually.
My Django unit tests have stopped working. Instantiating the Django test client now fails with the following error:
Traceback (most recent call last):
File "/vagrant/my/app/tests.py", line 43, in setUp
self.client = Client(HTTP_USER_AGENT='Mozilla/5.0')
File "/usr/local/lib/python2.6/dist-packages/Django-1.4.1-py2.6.egg/django/db/models/base.py", line 367, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
TypeError: 'HTTP_USER_AGENT' is an invalid keyword argument for this function
They fail when I instantiate the Django test client.
from django.test.client import Client
...
class MyAppTestCase(TestCase):
base_fixtures = ['fixtures.json']
def setUp(self):
self.client = Client(HTTP_USER_AGENT='Mozilla/5.0') # fails here
self.setupSession()
self.authenticateUser()
When I run python manage.py shell and enter the following, it works fine.
vagrant#lucid32:/var/www/mytraps.com/spensa$ python manage.py shell
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.test.client import Client
>>> client = Client(HTTP_USER_AGENT='Mozilla/5.0')
>>>
Any thoughts on why it is chocking on the HTTP_USER_AGENT keyword?
I found the solution.
I had a model class named 'Client'. My models were imported after the django test Client class.
You can't fix stupid.