Re: [Tutor] Regarding Python api script

2018-12-06 Thread Steven D'Aprano
On Thu, Dec 06, 2018 at 08:17:23AM -0600, Ravi Kumar wrote:

> I know I am asking a lot 

Yes you are. Please read this:

http://sscce.org/


It is written for Java programmers, but it applies equally to all 
languages, including Python.

Think about how difficult a job you are giving us: we don't have access 
to your network; we don't have the API key (which is understandable); we 
can't run the code; we can't even be confident that the code you give us 
is the same code you are running.

In fact we know that it cannot be the same code, because what you have 
given us has a Syntax Error in line 8:

> organization='4

(missing quote mark). Where there is one change to the code, there could 
be dozens for all we know.


> but I hit a road block on this i am assuming One
> small change in my last for loop I can get this working for all devices

That doesn't seem like a reasonable assumption to me. You might be 
right, or it could take many large changes.


> and
> I have hardcoded for one network how do I use the same code for different
> networks as well

You can read the network from the command line, or a config file, or an 
environment variable, or interactively by asking the user to enter the 
network using the "input" (Python 3) or "raw_input" (Python 2) 
functions.

I expect that you need more than one piece of information to change the 
network, it looks like you probably need at least four:

serveraddress
merakiAPIkey
organization
networkid

so it probably is best to read the details from a config file:

https://docs.python.org/3/library/configparser.html

is probably simplest, but you could use Property Lists as well:

https://docs.python.org/3/library/plistlib.html




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


Re: [Tutor] Regarding Python api script

2018-12-06 Thread Alan Gauld via Tutor
On 06/12/2018 14:17, Ravi Kumar wrote:

> 1)The for loops that have written I am able to access all the networks,able
> to loop through  all access points(Devices) in the network,able to loop
> through and get all clients in each access points but when it comea to
> client log events I am able to loop through and get only  the last row of
> accesspoints  list and get those particular and clients and its log events

I don't know the cause, but did take a quick look at the code.
One thing that makes it very difficult to follow is that you use the
same variable names over and over making it hard to keep track of what
any given 'item' or 'json_string' or 'r' actually holds at any given time.

Buy using  a different name for each json_string reflecting the
expected data - such as json_networks or json_clients - it would
be very much easier to follow the flow of the code.

> I assume I am going wrong in the last for loop code and output as shown
> below

Probably but I confess I couldn't spot it from a casual read through.

> for client in json_string:
> 
> hostname = client.get("dhcpHostname")
> description = client.get("description")
> ipaddress = client.get("ip")
> macaddress = client.get("mac")
> 
> usage = client.get("usage")
> sentbytes = usage.get("sent")
> recvbytes = usage.get("recv")
> 
> print ('{0:20}   {1:20}   {2:20}{3:30}   {4:20}
> {5:20}'.format(hostname, description, ipaddress, macaddress,sentbytes,
> recvbytes))
> 
> 
> 
> for  item in serialnumlist:
> print ("\nQuerying Meraki for clientlogevents on Devices: (" +
> item.get("mac") + ")")
> 
> for item  in json_string:
> config_url = "/networks/"+"/N_63***1050/"+"/clients/"+ item.get("mac")
> + "/events?perPage=1000"
> r = requests.get(base_url + config_url, headers=headers)
> 
> print ('{}  '.format(r.content))
> **>

The 'item's in the last loop appear to be the same as the 'client's
in the previous loop? Since 'json_string' never changes...

Also the setialnumlist only prints the result it never stores anything.

Then the last loop uses item.get(mac) which will not be the one printed
earlier since item is now read from json_string(back tome earlier
confusion over names!)

I suspect this lack of continuity may be the root of your problem
but the name collisions are twisting my brain and its late at night...


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


Re: [Tutor] Any 'graphical' ways of learning Python

2018-12-06 Thread Mike Barnett
Oh, one more thing on this topic... there are tutorial videos available for 
PySimpleGUI, both basic and advanced.

Basic 5 video series:
https://www.youtube.com/playlist?list=PLl8dD0doyrvHMoJGTdMtgLuHymaqJVjzt

Additional 9 in-depth videos:
https://www.youtube.com/playlist?list=PLl8dD0doyrvHMoJGTdMtgLuHymaqJVjzt


-mike

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


Re: [Tutor] Regarding Python api script

2018-12-06 Thread Ravi Kumar
Ya i do know SQL thanks I will look into it but before proceeding  I had
couple of concerns about my code to geneeate the client log events my
concerns


1)The for loops that have written I am able to access all the networks,able
to loop through  all access points(Devices) in the network,able to loop
through and get all clients in each access points but when it comea to
client log events I am able to loop through and get only  the last row of
accesspoints  list and get those particular and clients and its log events
I assume I am going wrong in the last for loop code and output as shown
below

import requests
import meraki
import json


serveraddress= 'meraki.com '
merakiAPIkey='3ce879efeafa5'
organization='4
networkid='N_639512046'

print ("Currently, the following organizations exist:\n")
base_url = "https://; + serveraddress + "/api/v0/organizations"
headers = {'X-Cisco-Meraki-API-Key': merakiAPIkey}

# Send the query to the Prime Infrastructure Server
r = requests.get(base_url,headers=headers)
# Retrieve the results in JSON format
json_string = r.json()


for org in json_string:

  print ("Organization: {}, ID: {}".format(org.get("name"), org.get("id")))
  print ("Meraki Query Engine Starting...\n")



 Section 2 Getting the networkID'S
#Construct the url for querying Prime Infrastructure
base_url=("https://"+serveraddress+"/api/v0;)
config_url=("/organizations/"+organization+"/networks")
headers = {'X-Cisco-Meraki-API-Key':merakiAPIkey}


r = requests.get(base_url+config_url,headers=headers)
json_string = r.json()

for network in json_string:
print("Network:{}, ID:  {}".format(network.get("name")
,network.get("id")))


for item in json_string:

if item['id'] == "N_630" :
network = item['id']
found_network = True

if not found_network:
print ("No Valid Network Found...")
exit()

print ("\n>>Querying Meraki for Access Points(Devices) on
Network:"+network)

 Section 2 Getting the Accesspoints(Devices)
config_url = "/networks/"+network+"/devices"
r = requests.get(base_url+config_url,headers=headers)
json_string = r.json()

print ('{0:20}   {1:20}   {2:20}   {3:30}   {4:20}'.format("Switch Name",
"MAC Address", "Serial Number", "IP Address","Device Type"))


serialnumlist=[]


for item in json_string:


# Extract all the appropriate fields
devicename = item.get("name")
macAddress = item.get("mac")
serialnum = item.get("serial")

serialnumlist.append(item)

devicetype = item.get("model")
ipaddress = item.get("lanIp")

# Print the resulting data to the screen
print ('{0:20}   {1:20}   {2:20}{3:30}   {4:20}'.format(devicename,
macAddress, serialnum,ipaddress, devicetype))

for item in serialnumlist:
print ("\n*>>Querying Meraki for clients on Access
Points:" + item.get("name")+ " (" + item.get("serial") + ")")
print ('{0:20}{1:30}{2:16}{3:18}  {4:15}
{5:20}'.format("Client Name", "Description", "IP Address", "MAC Address",
"Sent KBytes", "Recv KBytes"))


config_url = "/devices/" + item.get("serial") +
"/clients?timespan=86400"
r = requests.get(base_url + config_url, headers=headers)
json_string = r.json()

for client in json_string:

hostname = client.get("dhcpHostname")
description = client.get("description")
ipaddress = client.get("ip")
macaddress = client.get("mac")

usage = client.get("usage")
sentbytes = usage.get("sent")
recvbytes = usage.get("recv")

print ('{0:20}   {1:20}   {2:20}{3:30}   {4:20}
{5:20}'.format(hostname, description, ipaddress, macaddress,sentbytes,
recvbytes))



for  item in serialnumlist:
print ("\nQuerying Meraki for clientlogevents on Devices: (" +
item.get("mac") + ")")
   # print ('{0:20}   {1:30}   {2:16}   {3:18}   {4:10}
{5:11}'.format("Hostname", "Description", "IP Address", "MAC Address","Sent
KBytes", "Recv KBytes"))

for item  in json_string:
config_url = "/networks/"+"/N_63***1050/"+"/clients/"+ item.get("mac")
+ "/events?perPage=1000"
r = requests.get(base_url + config_url, headers=headers)

print ('{}  '.format(r.content))
**>

OUTPUT


Network:Room, ID:  N_631140260
Network:Ofce, ID:  N_639540739

***>>Querying Meraki for Access Points(Devices) on Network:N_639511050

Switch NameMAC Address

Serial Number

HA e0:cb:b:3e:95  Q2XD-USN6  172.16.172.

AB.  e0:cb:7:01:f4  Q2XD-G8Q8  172.16.172.


***>>Querying Meraki for clients on Access Points:HR (Q2XD-USN6)

Client NameMAC Address
Kiosk55:77:6a:5
Chphone.   44:91:60:a2:0

*>>Querying Meraki for clients on Access Points:DerbyRoom
(Q2XD--GQ8)

Client Name   MAC Address
iPhone  f0:98:9d:2c:   arphone
c8:21:58:79:b
it-min 

[Tutor] Any 'graphical' ways of learning Python

2018-12-06 Thread Mike Barnett
I stumbled onto this mailing list when Google found a mention of PySimpleGUI in 
a thread titled: Any 'graphical' ways of learning Python.

I wanted to respond with information on PySimpleGUI and why it's ideal for 
students.

If you're teaching kids and they want to learn how to do GUIs so that their 
programs run and look like Windows programs, then the PySimpleGUI package is 
the right choice.  It runs on top of either tkinter or Qt.  With tkinter it's 
easy to also package up the program into an EXE file that they kids can give to 
friends.  There are instructions in the PySimpleGUI documentation located at 
http://www.PySimpleGUI.org.

The GitHub http://www.PySimpleGUI.com has over 130 demo programs and there is a 
Cookbook filled with Recipes that you can copy, pate and run. There is a 
section with a bunch of exercises that are part of a course that an Aussie 
teacher developed.  You'll find them posted here:
https://github.com/MikeTheWatchGuy/PySimpleGUI/tree/master/ProgrammingClassExamples

There is extensive documentation for the package http://www.PySimpleGUI.org

The experience for the first time user was designed to be a positive one, 
filled with success, with the goal of having a GUI up on the screen within FIVE 
MINUTES of starting the process of installing.

PySimpleGUI was written with students and beginners in mind.  The idea was to 
enable the creation of any GUI layout using the same full-featured GUI widgets 
that are available if you coded directly in tkinter or Qt, but done without the 
boilerplate code.  The package does all the messy work for you.  It also hides 
the concepts like callbacks that are confusing to beginners.

Take a look at a small sampling of the GUIs made.
https://github.com/MikeTheWatchGuy/PySimpleGUI/issues/1
The better ones are towards the bottom. It's a long list dating back to the 1.0 
release so the early stuff looks a little primitive.

The reviews from users have been extremely positive on Reddit and on the GitHub 
site.

Today this was posted by a user on Reddit:
I'm finding it so easy to add a quick GUI front-end to some of my Python 
scripts with PySimpleGUI. There's so much less "boilerplate" needed than with 
more traditional GUI frameworks that I find myself adding simple GUIs to 
scripts which I would just run in console mode otherwise.

There are currently two flavors of PySimpleGUI, one that uses tkinter and the 
other Qt.  The great thing about PySimpleGUI is that you can create the same 
layout that you would if you coded directly in tkinter or Qt.  All of the same 
widgets are available for use.  They are just presented in an easier to 
understand manner.  The source code created in PySimpleGUI will run on either 
tkinter or Qt platform.  The only thing you have to change is the import 
statement.

PySimpleGUI has plenty of depth of features.  The result is a powerful GIU 
framework capable of running a large variety of user interfaces including 
running in the system tray.

PySimpleGUI is actively developed and maintained.  Should you run into a 
problem, it's typically addressed the same day.

There was a clear, large gap in the GUI landscape for Python.  In order to 
write even the most primitive of GUIs, you are required to know and use skills 
that are advanced beginner / intermediate.  GUIs are often taught towards the 
end of the curriculum for this reason.

With PySimpleGUI GUIs can be taught from the beginning of the course.  Rather 
than using the command line for input/output, it's easy to use windows instead.

If you want to learn more about the overall architecture, this recent post will 
help:
https://www.reddit.com/r/Python/comments/a1mj0p/pysimplegui_under_the_hood/



@mike

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


Re: [Tutor] Borrowing restricted code

2018-12-06 Thread Alex Kleider

On 2018-12-05 16:45, Steven D'Aprano wrote:

On Wed, Dec 05, 2018 at 11:22:35AM -0500, Avi Gross wrote:



Those following this thread might like to google "code V2"- the book by 
Laurence Lessig is relevant to many if not all of the disagreements.  
It's also a very interesting read (and free.)



I am NOT advocating copying code. Not even "free" code.

I am saying there may be times you want to package the code for 
special

purposes.


"Packaging" the code IS copying the code.



Perhaps someone can enlighten me on a subtle aspect here.

What does it mean to include something?


https://en.wiktionary.org/wiki/include


[... description of how #include works in C ...]
The above is not meant to be a precise description but indicates that 
your
code was rarely all your own. You could literally set it up so if 
someone
else left their code unguarded, you could arrange to grab text or 
library

code into your finished executable.


The precise details of what an individual programming language means by
"including" code will, naturally, depend on the language in question.

This is not really the place to go into a detailed description of all
the possible variations (this is supposed to be a *Python* forum after
all) but briefly there are at least two kinds of code which we might
"include": source code and compiled object code.

When "including" source code, the interpreter might read a command like
"load spam", look up a file "spam", read the contents into memory, 
parse

it and run it through the interpreter as if it had been copied and
pasted into the original file in place of the "load" line.

When "including" object code, the compiler (or often a separate program
called a linker) can make a copy of the object code and insert that 
code

directly into the object code it is generating. This is called "static
linking".

An alternative is to leave the object code where it is, but instead
insert instructions for how to access it at runtime. This is called
"dynamic linking".

https://kb.iu.edu/d/akqn

Python's import is (I think) closer to dynamic linking than the others.


In python, you can generally have access to the python code of what 
you can

import or at least to the byte code. But there may be different rules
attached to several categories.

If you use "import" you don't so much copy as USE the code. I mean the
interpreter pauses evaluating the current file and opens the one you 
asked

for and reads it as if it were your code.


That is not entirely wrong, but its not quite right either.

The action of the import command is surprisingly complex, and so I may
have got some subtle details wrong. But the high-level overview of what
the interpreter does when you run "import spam" is as follows.

1. Look for an already loaded module "spam"; if the interpreter finds
one, it creates an new variable called "spam" in the current namespace,
and assigns that module object to that name. The import is complete.

# Pseudo-code
if "spam" in sys.modules:
spam = sys.modules["spam"]
return


2. If no such already loaded module, then search a set of known
locations for a library called "spam":

# Pseudo-code
for location in sys.path:
for filename in os.listdir(location):
name, ext = path.splitext(filename)
if name == "spam":
if ext == ".py":
read the source code from spam.py into memory
parse it into bytecode into memory
write out the bytecode to spam.pyc
elif ext == ".pyc":
read the bytecode from spam.pyc into memory
else:
# other cases handled here, e.g. packages, zip files,
# C libraries (.dll or .so), other extensions etc.
# Assuming we get to here...
create a module object in memory
run that bytecode, using that module object as the 
namespace

cache the module object in sys.modules['spam']
spam = module object
return
# no such "spam" module or package found
raise ImportError


So you can see that modules are only executed the first time the
interpreter imports them, not on subsequent imports.

There really isn't a distinction to make between code treated "as if it
were your code" and other code. All code is treated the same.

How could it not be? The interpreter cannot know which modules or
libraries you wrote, which were collaborative efforts between you and
other people, and which were written by other people.




Some actions are transient. A line
like "5+3" evaluates to 8 and you ignore it. But many and perhaps most 
lines
end up creating instantiations of objects (yes, classes are also 
objects)

which then sit in memory.


Or get used and then disposed of by the garbage collector.



Functions are also objects and pretty much contain
within them everything you need to reconstruct the function if you 
know
where to look. Is what is copied really different than the original 
text

Re: [Tutor] Borrowing restricted code

2018-12-06 Thread Steven D'Aprano
On Thu, Dec 06, 2018 at 10:41:37AM +, Alan Gauld via Tutor wrote:
> On 06/12/2018 00:45, Steven D'Aprano wrote:
>
> > As for what is "not worth prosecuting", there are no copyright police 
> > who troll the internet looking for copied lines of code. Nobody is going 
> > to be scanning your Github repos looking for infringement (at least not 
> 
> Sorry, that's not strictly true. I know of at least two large companies
> who have full time teams whose job is to trawl Github, sourceforge
> and a few others looking at new checkins for unlicensed use of
> corporate code. And one of those teams is not even a technical
> team, they are corporate lawyers... And they do prosecute (or at least
> threaten to).

Ah, that's my error. When I said "copyright police", I was actually 
talking about *actual* law enforcement, not private companies. Sorry for 
not being more clear.


> > But they're not going to open up your Python folder and demand to see 
> > licences for everything or question whether or not you copy code from 
> > Stackoverflow without permission.
> 
> Again bodies like FAST(*) certainly do that (with police cooperation
> of course - they need a search warrant).

Again, I was specifically talking about customs agents.

I don't know who FAST is, but if they're like the Business Software 
Alliance they're effectively a front for Microsoft to strong-arm 
companies into buying Microsoft software under the threat of copyright 
infringement lawsuits.

https://en.wikipedia.org/wiki/BSA_%28The_Software_Alliance%29

If they're not in the pocket of Microsoft as the BSA is (was?) then 
they're in the pocket of their members. They're not White Knight 
palladins searching for pirated software out of their sense of ethical 
outrage, they're doing it because they're paid to.


> But they have been known to
> litigate and fines of several thousand pounds have been issued to
> infringers(?) But FAST is rarely interested in FOSS software its
> commercial code they worry about. 

Point of order: FOSS *is* commercial code (or at least can be). Just ask 
Red Hat, Apple, Mozilla and even Microsoft.

I think you mean that it is *proprietary* code they care about, and 
even then, I daresay they only litigate on behalf of their clients.



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


Re: [Tutor] Borrowing restricted code

2018-12-06 Thread Alan Gauld via Tutor
On 06/12/2018 00:45, Steven D'Aprano wrote:

> So you can see why many organisations are so paranoid about having 
> licences for every line of code they use. Failure to be fully licenced 
> could be *incredibly* time-consuming and expensive if they get into a 
> legal dispute. The only way to win is to avoid getting into a legal 
> dispute in the first place.
> 
> As for what is "not worth prosecuting", there are no copyright police 
> who troll the internet looking for copied lines of code. Nobody is going 
> to be scanning your Github repos looking for infringement (at least not 

Sorry, that's not strictly true. I know of at least two large companies
who have full time teams whose job is to trawl Github, sourceforge
and a few others looking at new checkins for unlicensed use of
corporate code. And one of those teams is not even a technical
team, they are corporate lawyers... And they do prosecute (or at least
threaten to).

> But they're not going to open up your Python folder and demand to see 
> licences for everything or question whether or not you copy code from 
> Stackoverflow without permission.

Again bodies like FAST(*) certainly do that (with police cooperation
of course - they need a search warrant). But they have been known to
litigate and fines of several thousand pounds have been issued to
infringers(?) But FAST is rarely interested in FOSS software its
commercial code they worry about. And usually it's unlicensed
binary code but they will pursue source code infringements if
asked. But having been on the receiving end of a FAST raid its an
unnerving experience (even though they didn't find anything).

(*)I wasn't sure if FAST are still active because I haven't
heard of any big prosecutions for about 10 years but their web
site suggests they are still very much around.

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