Re: [Tutor] Where am I mistaken? (exec not working as I expect)

2017-03-14 Thread Peter Otten
Steven D'Aprano wrote:

> Hello Francesco, and welcome!
> 
> My comments below.
> 
> On Sun, Mar 12, 2017 at 11:48:35PM +0100, Francesco Loffredo via Tutor
> wrote:
> 
>> I did only find a way to access the current document, but that's
>> all. Armed with that, and hoping to find some field names, I wrote a
>> small routine to inspect the types of all elements in that document,
>> and I stumbled in a strange behaviour in the exec() function: it seems
>> that exec() only works if called from the interactive interpreter,
>> while it doesn't if called inside a program.
>> Why?
> 
> That is definitely not the case. You must be misinterpreting what you
> are seeing. Unfortunately, your code is so complex I cannot easily see
> where the problem is. Perhaps later I will have time to study it in more
> detail, or somebody else will.

I think the underlying problem is that Python 3 doesn't give you write 
access to the function's namespace:

>>> def f():
... x = "a"
... exec("print(x); x = 'b'; print(x)")
... print(x)
... 
>>> f()
a
b
a

Here exec()'s namespace is initialized with a copy of the local namespace 
whereas on the module level where global and local namespace are identical 
it operates directly on the module namespace:

>>> x = "a"
>>> exec("print(x); x = 'b'; print(x)")
a
b
>>> x
'b'

While exec() is the wrong choice in most cases (Steven already proposed a 
better way to solve your problem) you can see the rebound names if you pass 
a namespace explicitly:

>>> def f():
... ns = dict(x="a")
... exec("print(x); x = 'b'; print(x)", ns)
... print(ns["x"])
... 
>>> f()
a
b
b

> But you do not need exec here at all. exec is a very powerful command,
> but you should treat it as for experts only. Instead of writing:
> 
> exec("qqq = inspect.getmembers(xModel.%s)" % x)
> 
> a much safer way is:
> 
> qqq = inspect.getmembers(getattr(xModel, x))
> 
> which is faster, easier to understand, and easier to debug.
> 
> I also see you have not one, but two bare except clauses:
> 
> try:
> ...
> except:
> ...
> 
> 
> This is not a good idea! Please read this:
> 
> https://realpython.com/blog/python/the-most-diabolical-python-antipattern/
> 
> 
> I think your code is too complex. Here is a simpler function which does
> what you describe as "correct behaviour":
> 
> def esplora(xModel):
> i = 0
> for i, name in enumerate(dir(xModel), 1):
> what = type(getattr(xModel, name))
> print(name, what)
> print("Totale elementi: %s" % i)
> 
> 
> class prova(object):
> def __init__(self):
> self.abc = "ABC"
> self.num = 123
> self.tup = ("abc", 321)
> 
> lui = prova()
> 
> esplora(lui)
> 
> 
> 
> which gives this result:
> 
> __class__ 
> __delattr__ 
> __dict__ 
> __dir__ 
> __doc__ 
> __eq__ 
> __format__ 
> __ge__ 
> __getattribute__ 
> __gt__ 
> __hash__ 
> __init__ 
> __le__ 
> __lt__ 
> __module__ 
> __ne__ 
> __new__ 
> __reduce__ 
> __reduce_ex__ 
> __repr__ 
> __setattr__ 
> __sizeof__ 
> __str__ 
> __subclasshook__ 
> __weakref__ 
> abc 
> num 
> tup 
> Totale elementi: 28
> 
> 
> 
> 
> Hope this helps!
> 
> 
> 


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While until the end of a list

2017-03-14 Thread Toni Fuente via Tutor
* Peter Otten <__pete...@web.de> [2017-03-13 19:57:38 +0100]:
> 
> Toni Fuente via Tutor wrote:
> 
> > Hi,
> > 
> > I've got this script that goes through an httpd conf file, and gets the
> > related bits of it for a site, and writes a new config with values that
> > I am interested. The problem is that it finds the first chunk and
> > returns it, but I need to go to the end of all chunks list, because
> > there are also some chunks related to the same site that I need to
> > collect (virtualhost *:80 and virtualhost:443). I was
> > 
> > I was thinking in a while loop in the find_chunk function that will go
> > through all chunks and return the chunks that site is on, but I don't know
> > how to construct it.
> > 
> > Thank you in advance for any suggestion.
> 
> Currently the structure of your script seems to be
> 
> chunks = load_chunks()
> for site in get_sites():
> interesting_chunk = find_chunk(site, chunks)
> if interesting_chunk is not None:
> do_stuff_with(interesting_chunk)
> 
> If I am understanding you correctly you want
> 
> chunks = load_chunks()
> for site in get_sites():
> for interesting_chunk in find_chunks(site, chunks):
> do_stuff_with(interesting_chunk)
> 
> 
> One way to make that work was already mentioned, have find_chunks return a 
> list:
> 
> def find_chunks(site, chunks):
> matches = []
> for chunk in chunks:
> if any(site in line for line in chunk):
> matches.append(chunk)
> return matches

I've used the return list solution, that gave me a list of lists with the
different chunks, so I needed to convert it into a list of strings before I
could use it with the regular expression matching functions:

def new_chunk(chunk, user, site):
config = []
strings_chunk = list(itertools.chain.from_iterable(chunk))
for item in strings_chunk:
if "DocumentRoot" in item:
root_dir = item.rsplit('/', 1)[-1]
root_dir = root_dir.strip('\n')

config.append(re.sub('/home/httpd/vhosts/[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*/[a-zA-Z\d-]{,63}',
 '/websites/' + user.rstrip() + '/' + site + '/' + root_dir, item))
[...]

Thank you all for your help!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While until the end of a list

2017-03-14 Thread Peter Otten
Toni Fuente via Tutor wrote:

> strings_chunk = list(itertools.chain.from_iterable(chunk))
> for item in strings_chunk:
 ...

Note that if you are iterating over strings_chunk just once there is no need 
to create an in-memory list.

for item in itertools.chain.from_iterable(chunk):
   ...

will work, too, without the consumption of time and memory needed to build 
the list.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While until the end of a list

2017-03-14 Thread Toni Fuente via Tutor
> 
> for item in itertools.chain.from_iterable(chunk):
>...
> 
> will work, too, without the consumption of time and memory needed to build 
> the list.
> 
Thank you Peter, yes it works as I wanted like that. 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cx_Oracle and Pyinstaller

2017-03-14 Thread Madhu Venkat
Reg: https://mail.python.org/pipermail/tutor/2014-December/103608.html

Hi,
I am connecting to Oracle little differently, not using TNSnames.ORA file.
Here is a line of code to show how I am connecting.


def connect(self):

try:
Conn = cx_Oracle.connect (self.dsn)
except cx_Oracle.DatabaseError as exception:

dsn has all the required connection info.

In this case, I believe I don't need TNSnames.ora file, please confirm.

Though I I have multiple script files (not just one) only one connects to
DB. DB connect script is imported in to other script file, that file is
imported in to another file (for modular programs I had to do this).

In this case, do I place all script files along with the DLLs in
c:\python2.7\ folder before I run the installer?

Should run the installer against the parent script (this is not the DB
connect.py) ?
-- 
Thank you,
Madhu Venkat
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cx_Oracle and Pyinstaller

2017-03-14 Thread Alan Gauld via Tutor
On 14/03/17 14:29, Madhu Venkat wrote:

> try:
> Conn = cx_Oracle.connect (self.dsn)
> except cx_Oracle.DatabaseError as exception:
> 
> dsn has all the required connection info.
> 
> In this case, I believe I don't need TNSnames.ora file, please confirm.

I don't know about Oracle under Python but it sounds
reasonable. Hopefully someone else will confirm.

> In this case, do I place all script files along with the DLLs in
> c:\python2.7\ folder before I run the installer?

But this sounds wrong. Just to be clear...
Which specific installer are you talking about?
What exactly are you installing and how?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Django REST API Question

2017-03-14 Thread Sreenathan Nair
Hi,

I am trying to setup a django REST based service, following is my setup:

MySQL DB Table (Inventory) contents is retrieved by a Django REST API query
and finally passed as a list of dictionaries to a python code which will
then implement some business logic based on this list. The working
requirement right now is that there is no plan for users interacting with
the app using a web interface (planning to use a QT desktop app for this).

What I have so far, I've setup the models and model serializers, in my view
I've defined a ListApiView with a get_quey_set method that will return a
Response object with my list using json.dumps. The python code that does
the query is using request.get on a url in order to get this json formatted
list to work on.

My question is if this is a valid approach to what I am trying to achieve?
Am I missing something in the setup and/or would anyone recommend an
alternative approach to doing this?

I'm using Python 2.7 with the latest build of Django and the Django REST
framework, presently everything is running on a testing machine using
CentOS 7.

Any feedback is greatly appreciated, thank you for your time.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor