I have a model with
class dbf_att(models.Model):
name = models.CharField(max_length=50, null=True)
And i'd like to check later that object.name match some regex:
if re.compile('^\d+$').match(att.name):
ret = 'Integer'
elif re.compile('^\d+\.\d+$').match(att.name):
ret = 'Float'
else:
ret = 'String'
return ret
This always return 'String' when some of the att.name should match those regex.
Thanks!
You can try with RegexValidator
Or you can to it with package django-regex-field, but i would rather recommand you to use built-in solution, the less third-party-apps the better.
Regex are great, but sometimes it is more simpler and readable to use other approaches. For example, How about just using builtin types to check for the type
try:
att_name = float(att.name)
ret = "Integer" if att_name.is_integer() else "Float"
except ValueError:
ret = "String"
FYI, your regex code works perfectly fine. You might want to inspect the data that is being checked.
Demo:
>>> import re
>>> a = re.compile('^\d+$')
>>> b = re.compile('^\d+\.\d+$')
>>> a.match('10')
<_sre.SRE_Match object at 0x10fe7eb28>
>>> a.match('10.94')
>>> b.match('10')
>>> b.match('10.94')
<_sre.SRE_Match object at 0x10fe7eb90>
>>> a.match("string")
>>> b.match("string")
Related
I have a config file with loads of paths and I want to organize them in a way. So I decided using types.SimpleNamespace to do that like:
paths = SimpleNamespace()
paths.base = '...'
paths.dataset.encoded = '...'
and I got:
AttributeError: 'types.SimpleNamespace' object has no attribute 'dataset'
I tried to define paths.dataset even though I didn't need it yet it didn't work:
paths = SimpleNamespace()
paths.base = '...'
paths.dataset = '...'
paths.dataset.encoded = '...'
AttributeError: 'str' object has no attribute 'encoded'
I also tried this:
_ = {
'base': '...',
'dataset': {
'encoded': '...',
}
}
paths = SimpleNamespace(**_)
and here is the result:
>>> paths.dataset.encoded # Error
AttributeError: 'dict' object has no attribute 'encoded'
>>> paths.dataset['encoded'] # works
'...'
This means that SimpleNamespace only works for one layer namespacing, right?
Is there another solution to this? I mean a solution other than using SimpleNamespace for every layer like this:
dataset = SimpleNamespace()
dataset.encoded = '...'
paths = SimpleNamespace()
paths.base = '???'
paths.dataset = dataset
>>> paths.base
'???'
>>> paths.dataset.encoded
'...'
Any ideas?
I came up with this solution:
def create_namespace(dictionary: dict):
"""Create a namespace of given dictionary
the difference between create_namespace and python's types.SimpleNamespace
is that the former will create name space recursively, but the later will
create the namespace in one layer indentation. See the examples to see the
difference.
Parameters
----------
dictionary : dict
A dict to be converted to a namespace object
Returns
-------
types.SimpleNamespace
A combination of SimpleNamespaces that will have an multilayer
namespace
Examples
--------
>>> dictionary = {
... 'layer1_a': '1a',
... 'layer1_b': {
... 'layer2_a': '2a',
... },
... }
>>> # types.SimpleNamespace
>>> simple = SimpleNamespace(**dictionary)
>>> simple.layer1_a
'1a'
>>> simple.layer1_b.layer2_a
AttributeError: 'dict' object has no attribute 'layer2_a'
# because layer1_b is still a dictionary
>>> # create_namespace
>>> complex = create_namespace(dictionary)
>>> complex.layer1_a
'1a'
>>> complex.layer1_a.layer2_a
'2a'
"""
space = {}
for key, value in dictionary.items():
if isinstance(value, dict):
value = create_namespace(value)
space[key] = value
return SimpleNamespace(**space)
but I think there is a better way that I'm not seeing. I appreciate any comments on this.
I am using Python's regex with an if-statement: if the match is None, then it should go to the else clause. But it shows this error:
AttributeError: 'NoneType' object has no attribute 'group'
The script is:
import string
chars = re.escape(string.punctuation)
sub='FW: Re: 29699'
if re.search("^FW: (\w{10})",sub).group(1) is not None :
d=re.search("^FW: (\w{10})",sub).group(1)
else:
a=re.sub(r'['+chars+']', ' ',sub)
d='_'.join(a.split())
Every help is great help!
Your problem is this: if your search doesn't find anything, it will return None. You can't do None.group(1), which is what your code amounts to. Instead, check whether the search result is None—not the search result's first group.
import re
import string
chars = re.escape(string.punctuation)
sub='FW: Re: 29699'
search_result = re.search(r"^FW: (\w{10})", sub)
if search_result is not None:
d = search_result.group(1)
else:
a = re.sub(r'['+chars+']', ' ', sub)
d = '_'.join(a.split())
print(d)
# FW_RE_29699
I am having two inputs for my task
>>> uri = u'/shop/amazonwow/getstates/1'
>>> uri_regex = u'/shop/(?P<shopid>.+)$/getstates/(?P<countryid>.+)$/'
Here uri is the request url and also i am passing a uri pattern(uri_regex) with it.
I need to fetch all dynamic data from uri .We will decide which data is dynamic as per our uri_regex .
Example : Here uri_regex has shopid , countryid as regular expression pattern and url is having values `amazonwow , 1 at same indexes.
My output will be like :
out = {'shopid': 'amazonwow', 'countryid' :1,}
My Try :
>>> uri_list = uri.split('/')
[u'', u'shop', u'amazonwow', u'getstates', u'1']
>>> regex = uri_regex.split('/')
>>> regex
[u'', u'shop', u'(?P<shopid>.+)$', u'getstates', u'(?P<countryid>.+)$']
>>> out = {}
>>> for i in range(len(regex)):
if regex[i].startswith('(?') & regex[i].endswith(')$'):
key = regex[i][regex[i].find("<")+1:regex[i].find(">")]
out[key] = uri_list[i]
>>> print out
{u'shopid': u'amazonwow', u'countryid': u'1'}
>>>
Note : i tried this but i do not think it is proper solution to above problem. Please guide me if you guys have much better way.
import re
uri = u'/shop/amazonwow/getstates/1'
pattern = re.compile(u'shop/(.+)/getstates/(.+)')
if pattern.search(uri):
out['shopid'] = pattern.search(uri).groups()[0]
out['countryid'] = pattern.search(uri).groups()[1]
Output:
out = {'countryid': '1', 'shopid': 'amazonwow'}
My Try:
def fetch_uri_variables(uri, uri_regex):
"""
function to fetch dynamic variables passed in uri as per
regular expression defined into uri_regex
"""
out, uri_list, uri_regex = {}, uri.split('/'), uri_regex.split('/')
for pattern in range(len(uri_regex)):
if re.search('^(\(\?)(.*)(\)\$)$', uri_regex[pattern]):
out[re.search('\<(.*)\>', uri_regex[pattern]).group(1)] = \
uri_list[pattern]
return out
>>> uri
u'/testing/shop/amazonwow/getstates/1'
>>> uri_regex
u'/(?P<test>.+)$/shop/(?P<shopid>.+)$/getstates/(?P<countryid>.+)$/'
>>> fetch_uri_variables(uri, uri_regex)
{u'test': u'testing', u'countryid': u'1', u'shopid': u'amazonwow'}
>>>
I'm trying to serialize the result (a list) of an sqlalchemy query to json.
this is the class:
class Wikilink(Base):
__tablename__='Wikilinks'
__table_args__={'extend_existing':True}
id = Column(Integer,autoincrement=True,primary_key=True)
title = Column(Unicode(350))
user_ip = Column(String(50))
page = Column(String(20))
revision = Column(String(20))
timestamp = Column(String(50))
and I guess my problem is with the __repr__(self): function.
I tried something like:
return '{{0}:{"title":{1}, "Ip":{2}, "page":{3} ,"revision":{4}}}'.format(self.id,self.title.encode('utf-8'),self.user_ip,self.page,self.revision)
or:
return '{"id"={0}, "title"={1}, "Ip"={2}}'.format(self.id,self.title.encode('utf-8'),self.user_ip.encode('utf-8'),self.page,self.revision)
and I got:
TypeError(repr(o) + " is not JSON serializable")
ValueError: Single '}' encountered in format string
I tried:
return '{id=%d, title=%s, Ip=%s}'%(self.id,self.title.encode('utf-8'),self.user_ip.encode('utf-8'))
and I got:
TypeError: {id=8126, title=1 בדצמבר, Ip=147.237.70.106} is not JSON serializable
adding "" around (according to the JSON formatting) like this: "id"="%d", "title"="%s", "Ip"="%s" didn't help either.
I know this is supposed to be dead simple but I just can't get this right
actually bottle is handling the jsonification part automatically, but trying to call json.dumps on the result gives me the same errors.
Instead of trying to convert to json a string, you could define, for example, your own to_dict method that returns the dictionary structure it seems you're trying to create and, after that, generate the json from that structure:
>>> import json
>>> d = {'id':8126, 'title':u'1 בדצמבר', 'ip':'147.237.70.106'}
>>> json.dumps(d)
'{"ip": "147.237.70.106", "id": 8126, "title": "1 \\u05d1\\u05d3\\u05e6\\u05de\\u05d1\\u05e8"}'
I'm not sure I understand what you tried. Couldn't you build the dict and let json.dumps() do the work for you?
Something like:
>>> class Foo:
... id = 1
... title = 'my title'
... to_jsonize = ['id', 'title']
>>>
>>> dct = {name: getattr(Foo,name) for name in Foo.to_jsonize}
>>> import json
>>> json.dumps(dct)
'{"id": 1, "title": "my title"}'
I have following python code:
TRAC_REQUEST_LOCATION=""
TRAC_ENV=TRAC_ENV_PARENT+"/"+re.sub(r'^'+TRAC_REQUEST_LOCATION+'/([^/]+).*', r'\1', environ['REQUEST_URI'])
The content of environ['REQUEST_URI'] is something like that /abc/DEF and I want to get only abc, but it doesn't work. Only sometimes it works, but why?
Thanks for any advices.
EDIT:
Here is the new code consisting on the given answers:
def check_password(environ, user, password):
global acct_mgr, TRAC_ENV
TRAC_ENV = ''
if 'REQUEST_URI' in environ:
if '/' in environ['REQUEST_URI']:
TRAC_ENV = environ['REQUEST_URI'].split('/')[1]
else:
return None
But I get as TRAC_ENV things like /abc/ or /abc, but I need only the abc part.
What is wrong with the code?
Why do you need a regexp? Use urlparse (Python 2.x, there is a link for Python 3.x in there).
If you want to extract the first part of the request path this is the simplest solution:
TRAC_ENV = ''
if '/' in environ['REQUEST_URI']:
TRAC_ENV = environ['REQUEST_URI'].split('/')[1]
EDIT
An example usage:
>>> def trac_env(environ):
... trac_env = ''
... if '/' in environ['REQUEST_URI']:
... trac_env = environ['REQUEST_URI'].split('/')[1]
... return trac_env
...
>>> trac_env({'REQUEST_URI': ''})
''
>>> trac_env({'REQUEST_URI': '/'})
''
>>> trac_env({'REQUEST_URI': '/foo'})
'foo'
>>> trac_env({'REQUEST_URI': '/foo/'})
'foo'
>>> trac_env({'REQUEST_URI': '/foo/bar'})
'foo'
>>> trac_env({'REQUEST_URI': '/foo/bar/'})
'foo'
I am back to my code above and it works fine now.
Perhaps the update of the components was the solution.